idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
26,500 | def dispatch ( self , handler_input ) : try : for request_interceptor in self . request_interceptors : request_interceptor . process ( handler_input = handler_input ) output = self . __dispatch_request ( handler_input ) for response_interceptor in self . response_interceptors : response_interceptor . process ( handler_... | Dispatches an incoming request to the appropriate request handler and returns the output . |
26,501 | def __dispatch_request ( self , handler_input ) : request_handler_chain = None for mapper in self . request_mappers : request_handler_chain = mapper . get_request_handler_chain ( handler_input ) if request_handler_chain is not None : break if request_handler_chain is None : raise DispatchException ( "Unable to find a s... | Process the request and return handler output . |
26,502 | def lambda_handler ( self ) : def wrapper ( event , context ) : skill = CustomSkill ( skill_configuration = self . skill_configuration ) request_envelope = skill . serializer . deserialize ( payload = json . dumps ( event ) , obj_type = RequestEnvelope ) response_envelope = skill . invoke ( request_envelope = request_e... | Create a handler function that can be used as handler in AWS Lambda console . |
26,503 | def verify_request_and_dispatch ( self , http_request_headers , http_request_body ) : request_envelope = self . _skill . serializer . deserialize ( payload = http_request_body , obj_type = RequestEnvelope ) for verifier in self . _verifiers : verifier . verify ( headers = http_request_headers , serialized_request_env =... | Entry point for webservice skill invocation . |
26,504 | def init_app ( self , app ) : app . config . setdefault ( VERIFY_SIGNATURE_APP_CONFIG , True ) app . config . setdefault ( VERIFY_TIMESTAMP_APP_CONFIG , True ) if EXTENSION_NAME not in app . extensions : app . extensions [ EXTENSION_NAME ] = { } app . extensions [ EXTENSION_NAME ] [ self . _skill_id ] = self with app .... | Register the extension on the given Flask application . |
26,505 | def _create_webservice_handler ( self , skill , verifiers ) : if verifiers is None : verifiers = [ ] self . _webservice_handler = WebserviceSkillHandler ( skill = skill , verify_signature = current_app . config . get ( VERIFY_SIGNATURE_APP_CONFIG , True ) , verify_timestamp = current_app . config . get ( VERIFY_TIMESTA... | Create the handler for request verification and dispatch . |
26,506 | def dispatch_request ( self ) : if flask_request . method != "POST" : raise exceptions . MethodNotAllowed ( ) try : content = flask_request . data . decode ( verifier_constants . CHARACTER_ENCODING ) response = self . _webservice_handler . verify_request_and_dispatch ( http_request_headers = flask_request . headers , h... | Method that handles request verification and routing . |
26,507 | def register ( self , app , route , endpoint = None ) : if app is None or not isinstance ( app , Flask ) : raise TypeError ( "Expected a valid Flask instance" ) if route is None or not isinstance ( route , str ) : raise TypeError ( "Expected a valid URL rule string" ) app . add_url_rule ( route , view_func = self . dis... | Method to register the routing on the app at provided route . |
26,508 | def serialize ( self , obj ) : if obj is None : return None elif isinstance ( obj , self . PRIMITIVE_TYPES ) : return obj elif isinstance ( obj , list ) : return [ self . serialize ( sub_obj ) for sub_obj in obj ] elif isinstance ( obj , tuple ) : return tuple ( self . serialize ( sub_obj ) for sub_obj in obj ) elif is... | Builds a serialized object . |
26,509 | def deserialize ( self , payload , obj_type ) : if payload is None : return None try : payload = json . loads ( payload ) except Exception : raise SerializationException ( "Couldn't parse response body: {}" . format ( payload ) ) return self . __deserialize ( payload , obj_type ) | Deserializes payload into an instance of provided obj_type . |
26,510 | def __deserialize ( self , payload , obj_type ) : if payload is None : return None if isinstance ( obj_type , str ) : if obj_type . startswith ( 'list[' ) : sub_obj_type = re . match ( 'list\[(.*)\]' , obj_type ) if sub_obj_type is None : return [ ] sub_obj_types = sub_obj_type . group ( 1 ) deserialized_list = [ ] if ... | Deserializes payload into a model object . |
26,511 | def __load_class_from_name ( self , class_name ) : try : module_class_list = class_name . rsplit ( "." , 1 ) if len ( module_class_list ) > 1 : module_name = module_class_list [ 0 ] resolved_class_name = module_class_list [ 1 ] module = __import__ ( module_name , fromlist = [ resolved_class_name ] ) resolved_class = ge... | Load the class from the class_name provided . |
26,512 | def __deserialize_primitive ( self , payload , obj_type ) : obj_cast = cast ( Any , obj_type ) try : return obj_cast ( payload ) except UnicodeEncodeError : return unicode_type ( payload ) except TypeError : return payload except ValueError : raise SerializationException ( "Failed to parse {} into '{}' object" . format... | Deserialize primitive datatypes . |
26,513 | def __deserialize_model ( self , payload , obj_type ) : try : obj_cast = cast ( Any , obj_type ) if issubclass ( obj_cast , Enum ) : return obj_cast ( payload ) if hasattr ( obj_cast , 'deserialized_types' ) : if hasattr ( obj_cast , 'get_real_child_model' ) : obj_cast = self . __get_obj_by_discriminator ( payload , ob... | Deserialize instance to model object . |
26,514 | def __get_obj_by_discriminator ( self , payload , obj_type ) : obj_cast = cast ( Any , obj_type ) namespaced_class_name = obj_cast . get_real_child_model ( payload ) if not namespaced_class_name : raise SerializationException ( "Couldn't resolve object by discriminator type " "for {} class" . format ( obj_type ) ) retu... | Get correct subclass instance using the discriminator in payload . |
26,515 | def persistent_attributes ( self ) : if not self . _persistence_adapter : raise AttributesManagerException ( "Cannot get PersistentAttributes without Persistence adapter" ) if not self . _persistent_attributes_set : self . _persistence_attributes = ( self . _persistence_adapter . get_attributes ( request_envelope = sel... | Attributes stored at the Persistence level of the skill lifecycle . |
26,516 | def persistent_attributes ( self , persistent_attributes ) : if not self . _persistence_adapter : raise AttributesManagerException ( "Cannot set PersistentAttributes without persistence adapter!" ) self . _persistence_attributes = persistent_attributes self . _persistent_attributes_set = True | Overwrites and caches the persistent attributes value . |
26,517 | def save_persistent_attributes ( self ) : if not self . _persistence_adapter : raise AttributesManagerException ( "Cannot save PersistentAttributes without " "persistence adapter!" ) if self . _persistent_attributes_set : self . _persistence_adapter . save_attributes ( request_envelope = self . _request_envelope , attr... | Save persistent attributes to the persistence layer if a persistence adapter is provided . |
26,518 | def user_agent_info ( sdk_version , custom_user_agent ) : python_version = "." . join ( str ( x ) for x in sys . version_info [ 0 : 3 ] ) user_agent = "ask-python/{} Python/{}" . format ( sdk_version , python_version ) if custom_user_agent is None : return user_agent else : return user_agent + " {}" . format ( custom_u... | Return the user agent info along with the SDK and Python Version information . |
26,519 | def get_attributes ( self , request_envelope ) : try : table = self . dynamodb . Table ( self . table_name ) partition_key_val = self . partition_keygen ( request_envelope ) response = table . get_item ( Key = { self . partition_key_name : partition_key_val } , ConsistentRead = True ) if "Item" in response : return res... | Get attributes from table in Dynamodb resource . |
26,520 | def save_attributes ( self , request_envelope , attributes ) : try : table = self . dynamodb . Table ( self . table_name ) partition_key_val = self . partition_keygen ( request_envelope ) table . put_item ( Item = { self . partition_key_name : partition_key_val , self . attribute_name : attributes } ) except ResourceNo... | Saves attributes to table in Dynamodb resource . |
26,521 | def delete_attributes ( self , request_envelope ) : try : table = self . dynamodb . Table ( self . table_name ) partition_key_val = self . partition_keygen ( request_envelope ) table . delete_item ( Key = { self . partition_key_name : partition_key_val } ) except ResourceNotExistsError : raise PersistenceException ( "D... | Deletes attributes from table in Dynamodb resource . |
26,522 | def __create_table_if_not_exists ( self ) : if self . create_table : try : self . dynamodb . create_table ( TableName = self . table_name , KeySchema = [ { 'AttributeName' : self . partition_key_name , 'KeyType' : 'HASH' } ] , AttributeDefinitions = [ { 'AttributeName' : self . partition_key_name , 'AttributeType' : 'S... | Creates table in Dynamodb resource if it doesn t exist and create_table is set as True . |
26,523 | def add_request_handler ( self , request_handler ) : if request_handler is None : raise RuntimeConfigException ( "Valid Request Handler instance to be provided" ) if not isinstance ( request_handler , AbstractRequestHandler ) : raise RuntimeConfigException ( "Input should be a RequestHandler instance" ) self . request_... | Register input to the request handlers list . |
26,524 | def add_exception_handler ( self , exception_handler ) : if exception_handler is None : raise RuntimeConfigException ( "Valid Exception Handler instance to be provided" ) if not isinstance ( exception_handler , AbstractExceptionHandler ) : raise RuntimeConfigException ( "Input should be an ExceptionHandler instance" ) ... | Register input to the exception handlers list . |
26,525 | def add_global_request_interceptor ( self , request_interceptor ) : if request_interceptor is None : raise RuntimeConfigException ( "Valid Request Interceptor instance to be provided" ) if not isinstance ( request_interceptor , AbstractRequestInterceptor ) : raise RuntimeConfigException ( "Input should be a RequestInte... | Register input to the global request interceptors list . |
26,526 | def add_global_response_interceptor ( self , response_interceptor ) : if response_interceptor is None : raise RuntimeConfigException ( "Valid Response Interceptor instance to be provided" ) if not isinstance ( response_interceptor , AbstractResponseInterceptor ) : raise RuntimeConfigException ( "Input should be a Respo... | Register input to the global response interceptors list . |
26,527 | def get_runtime_configuration ( self ) : request_mapper = GenericRequestMapper ( request_handler_chains = self . request_handler_chains ) exception_mapper = GenericExceptionMapper ( exception_handlers = self . exception_handlers ) handler_adapter = GenericHandlerAdapter ( ) runtime_configuration = RuntimeConfiguration ... | Build the runtime configuration object from the registered components . |
26,528 | def user_id_partition_keygen ( request_envelope ) : try : user_id = request_envelope . context . system . user . user_id return user_id except AttributeError : raise PersistenceException ( "Couldn't retrieve user id from request " "envelope, for partition key use" ) | Retrieve user id from request envelope to use as partition key . |
26,529 | def device_id_partition_keygen ( request_envelope ) : try : device_id = request_envelope . context . system . device . device_id return device_id except AttributeError : raise PersistenceException ( "Couldn't retrieve device id from " "request envelope, for partition key use" ) | Retrieve device id from request envelope to use as partition key . |
26,530 | def is_canfulfill_intent_name ( name ) : def can_handle_wrapper ( handler_input ) : return ( isinstance ( handler_input . request_envelope . request , CanFulfillIntentRequest ) and handler_input . request_envelope . request . intent . name == name ) return can_handle_wrapper | A predicate function returning a boolean when name matches the intent name in a CanFulfill Intent Request . |
26,531 | def is_intent_name ( name ) : def can_handle_wrapper ( handler_input ) : return ( isinstance ( handler_input . request_envelope . request , IntentRequest ) and handler_input . request_envelope . request . intent . name == name ) return can_handle_wrapper | A predicate function returning a boolean when name matches the name in Intent Request . |
26,532 | def is_request_type ( request_type ) : def can_handle_wrapper ( handler_input ) : return ( handler_input . request_envelope . request . object_type == request_type ) return can_handle_wrapper | A predicate function returning a boolean when request type is the passed - in type . |
26,533 | def invoke ( self , request ) : try : http_method = self . _resolve_method ( request ) http_headers = self . _convert_list_tuples_to_dict ( headers_list = request . headers ) parsed_url = parse_url ( request . url ) if parsed_url . scheme is None or parsed_url . scheme != "https" : raise ApiClientException ( "Requests ... | Dispatches a request to an API endpoint described in the request . |
26,534 | def _resolve_method ( self , request ) : try : return getattr ( requests , request . method . lower ( ) ) except AttributeError : raise ApiClientException ( "Invalid request method: {}" . format ( request . method ) ) | Resolve the method from request object to requests http call . |
26,535 | def _convert_list_tuples_to_dict ( self , headers_list ) : headers_dict = { } if headers_list is not None : for header_tuple in headers_list : key , value = header_tuple [ 0 ] , header_tuple [ 1 ] if key in headers_dict : headers_dict [ key ] = "{}, {}" . format ( headers_dict [ key ] , value ) else : headers_dict [ he... | Convert list of tuples from headers of request object to dictionary format . |
26,536 | def _convert_dict_to_list_tuples ( self , headers_dict ) : headers_list = [ ] if headers_dict is not None : for key , values in six . iteritems ( headers_dict ) : for value in values . split ( "," ) : value = value . strip ( ) if value is not None and value is not '' : headers_list . append ( ( key , value . strip ( ) ... | Convert headers dict to list of string tuples format for ApiClientResponse headers variable . |
26,537 | def add_request_handler_chain ( self , request_handler_chain ) : if request_handler_chain is None or not isinstance ( request_handler_chain , GenericRequestHandlerChain ) : raise DispatchException ( "Request Handler Chain is not a GenericRequestHandlerChain " "instance" ) self . _request_handler_chains . append ( reque... | Checks the type before adding it to the request_handler_chains instance variable . |
26,538 | def get_request_handler_chain ( self , handler_input ) : for chain in self . request_handler_chains : handler = chain . request_handler if handler . can_handle ( handler_input = handler_input ) : return chain return None | Get the request handler chain that can handle the dispatch input . |
26,539 | def add_exception_handler ( self , exception_handler ) : if exception_handler is None or not isinstance ( exception_handler , AbstractExceptionHandler ) : raise DispatchException ( "Input is not an AbstractExceptionHandler instance" ) self . _exception_handlers . append ( exception_handler ) | Checks the type before adding it to the exception_handlers instance variable . |
26,540 | def get_handler ( self , handler_input , exception ) : for handler in self . exception_handlers : if handler . can_handle ( handler_input = handler_input , exception = exception ) : return handler return None | Get the exception handler that can handle the input and exception . |
26,541 | def verify ( self , headers , serialized_request_env , deserialized_request_env ) : cert_url = headers . get ( self . _signature_cert_chain_url_key ) signature = headers . get ( self . _signature_key ) if cert_url is None or signature is None : raise VerificationException ( "Missing Signature/Certificate for the skill ... | Verify if the input request signature and the body matches . |
26,542 | def _retrieve_and_validate_certificate_chain ( self , cert_url ) : self . _validate_certificate_url ( cert_url ) cert_chain = self . _load_cert_chain ( cert_url ) self . _validate_cert_chain ( cert_chain ) return cert_chain | Retrieve and validate certificate chain . |
26,543 | def _validate_certificate_url ( self , cert_url ) : parsed_url = urlparse ( cert_url ) protocol = parsed_url . scheme if protocol . lower ( ) != CERT_CHAIN_URL_PROTOCOL . lower ( ) : raise VerificationException ( "Signature Certificate URL has invalid protocol: {}. " "Expecting {}" . format ( protocol , CERT_CHAIN_URL_... | Validate the URL containing the certificate chain . |
26,544 | def _load_cert_chain ( self , cert_url , x509_backend = default_backend ( ) ) : try : if cert_url in self . _cert_cache : return self . _cert_cache . get ( cert_url ) else : with urlopen ( cert_url ) as cert_response : cert_data = cert_response . read ( ) x509_certificate = load_pem_x509_certificate ( cert_data , x509_... | Loads the certificate chain from the URL . |
26,545 | def _validate_cert_chain ( self , cert_chain ) : now = datetime . utcnow ( ) if not ( cert_chain . not_valid_before <= now <= cert_chain . not_valid_after ) : raise VerificationException ( "Signing Certificate expired" ) ext = cert_chain . extensions . get_extension_for_oid ( ExtensionOID . SUBJECT_ALTERNATIVE_NAME ) i... | Validate the certificate chain . |
26,546 | def _valid_request_body ( self , cert_chain , signature , serialized_request_env ) : decoded_signature = base64 . b64decode ( signature ) public_key = cert_chain . public_key ( ) request_env_bytes = serialized_request_env . encode ( CHARACTER_ENCODING ) try : public_key . verify ( decoded_signature , request_env_bytes ... | Validate the request body hash with signature . |
26,547 | def verify ( self , headers , serialized_request_env , deserialized_request_env ) : local_now = datetime . now ( tz . tzutc ( ) ) request_timestamp = deserialized_request_env . request . timestamp if ( abs ( ( local_now - request_timestamp ) . seconds ) > ( self . _tolerance_in_millis / 1000 ) ) : raise VerificationExc... | Verify if the input request timestamp is in tolerated limits . |
26,548 | def escape ( identifier , ansi_quotes , should_quote ) : if not should_quote ( identifier ) : return identifier quote = '"' if ansi_quotes else '`' identifier = identifier . replace ( quote , 2 * quote ) return '{0}{1}{2}' . format ( quote , identifier , quote ) | Escape identifiers . |
26,549 | def ma_bias_ratio ( self , day1 , day2 ) : 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 ] | Calculate moving average bias ratio |
26,550 | def ma_bias_ratio_pivot ( self , data , sample_size = 5 , position = False ) : sample = data [ - sample_size : ] if position is True : check_value = max ( sample ) pre_check_value = max ( sample ) > 0 elif position is False : check_value = min ( sample ) pre_check_value = max ( sample ) < 0 return ( ( sample_size - sam... | Calculate pivot point |
26,551 | def fetch ( self , year : int , month : int ) : self . raw_data = [ self . fetcher . fetch ( year , month , self . sid ) ] self . data = self . raw_data [ 0 ] [ 'data' ] return self . data | Fetch year month data |
26,552 | def fetch_from ( self , year : int , month : int ) : self . raw_data = [ ] self . data = [ ] today = datetime . datetime . today ( ) for year , month in self . _month_year_iter ( month , year , today . month , today . year ) : self . raw_data . append ( self . fetcher . fetch ( year , month , self . sid ) ) self . data... | Fetch data from year month to current year month data |
26,553 | def fetch_31 ( self ) : 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 | Fetch 31 days data |
26,554 | 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 |
26,555 | def proxy_num ( self , protocol = None ) : http_num = len ( self . proxies [ 'http' ] ) https_num = len ( self . proxies [ 'https' ] ) if protocol == 'http' : return http_num elif protocol == 'https' : return https_num else : return http_num + https_num | Get the number of proxies in the pool |
26,556 | def get_next ( self , protocol = 'http' , format = False , policy = 'loop' ) : if not self . proxies [ protocol ] : return None if policy == 'loop' : idx = self . idx [ protocol ] self . idx [ protocol ] = ( idx + 1 ) % len ( self . proxies [ protocol ] ) elif policy == 'random' : idx = random . randint ( 0 , self . pr... | Get the next proxy |
26,557 | def save ( self , filename ) : proxies = { 'http' : [ ] , 'https' : [ ] } for protocol in [ 'http' , 'https' ] : for proxy in self . proxies [ protocol ] : serializable_proxy = self . proxies [ protocol ] [ proxy ] . to_dict ( ) proxies [ protocol ] . append ( serializable_proxy ) with open ( filename , 'w' ) as fout :... | Save proxies to file |
26,558 | def load ( self , filename ) : with open ( filename , 'r' ) as fin : proxies = json . load ( fin ) for protocol in proxies : for proxy in proxies [ protocol ] : self . proxies [ protocol ] [ proxy [ 'addr' ] ] = Proxy ( proxy [ 'addr' ] , proxy [ 'protocol' ] , proxy [ 'weight' ] , proxy [ 'last_checked' ] ) self . add... | Load proxies from file |
26,559 | def add_proxy ( self , proxy ) : protocol = proxy . protocol addr = proxy . addr if addr in self . proxies : self . proxies [ protocol ] [ addr ] . last_checked = proxy . last_checked else : self . proxies [ protocol ] [ addr ] = proxy self . addr_list [ protocol ] . append ( addr ) | Add a valid proxy into pool |
26,560 | def remove_proxy ( self , proxy ) : del self . search_flag [ proxy . protocol ] [ proxy . addr ] del self . addr_list [ proxy . protocol ] [ proxy . addr ] | Remove a proxy out of the pool |
26,561 | def increase_weight ( self , proxy ) : new_weight = proxy . weight * self . inc_ratio if new_weight < 1.0 : proxy . weight = new_weight else : proxy . weight = 1.0 | Increase the weight of a proxy by multiplying inc_ratio |
26,562 | def decrease_weight ( self , proxy ) : new_weight = proxy . weight * self . dec_ratio if new_weight < self . weight_thr : self . remove_proxy ( proxy ) else : proxy . weight = new_weight | Decreasing the weight of a proxy by multiplying dec_ratio |
26,563 | def is_valid ( self , addr , protocol = 'http' , timeout = 5 ) : start = time . time ( ) try : r = requests . get ( self . test_url [ protocol ] , timeout = timeout , proxies = { protocol : 'http://' + addr } ) except KeyboardInterrupt : raise except requests . exceptions . Timeout : return { 'valid' : False , 'msg' : ... | Check if a proxy is valid |
26,564 | def validate ( self , proxy_scanner , expected_num = 20 , queue_timeout = 3 , val_timeout = 5 ) : while self . proxy_num ( ) < expected_num : try : candidate_proxy = proxy_scanner . proxy_queue . get ( timeout = queue_timeout ) except queue . Empty : if proxy_scanner . is_scanning ( ) : continue else : break addr = can... | Target function of validation threads |
26,565 | 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 ( ) self . logger . info ( 'starting {} threads to validating proxies...' . format ( val_thr_num ) ) val_threads = [ ] for i in range ( val_thr_num ) : t... | Scan and validate proxies |
26,566 | 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 ) : if expected_num > 30 : self . logger . warn ( 'The more proxy you expect, the more time it ' 'will take. It is highly recommended to limit the' ' e... | Default scan method to simplify the usage of scan method . |
26,567 | def register_func ( self , func_name , func_kwargs ) : self . scan_funcs . append ( func_name ) self . scan_kwargs . append ( func_kwargs ) | Register a scan function |
26,568 | 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 : proxies = json . load ( fin ) for protocol in proxies . keys ( ) : for proxy in proxies [ protocol ] : self . proxy_queue . put ( { 'addr' : proxy [ 'addr' ... | Scan candidate proxies from an existing file |
26,569 | 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 in range ( len ( self . scan_funcs ) ) : t = threading . Thread ( name = self . scan_funcs [ i ] . __name__ , target = self . scan_funcs [ i... | Start a thread for each registered scan function to scan proxy lists |
26,570 | def is_duplicated ( self , item ) : if isinstance ( item , dict ) : hashable_item = json . dumps ( item , sort_keys = True ) elif isinstance ( item , list ) : hashable_item = frozenset ( item ) else : hashable_item = item if hashable_item in self . _cache : return True else : if self . cache_capacity > 0 and len ( self... | Check whether the item has been in the cache |
26,571 | def put ( self , item , block = True , timeout = None , dup_callback = None ) : if not self . is_duplicated ( item ) : super ( CachedQueue , self ) . put ( item , block , timeout ) else : if dup_callback : dup_callback ( item ) | Put an item to queue if it is not duplicated . |
26,572 | def set ( self , ** signals ) : for name in signals : if name not in self . _signals : self . _init_status [ name ] = signals [ name ] self . _signals [ name ] = signals [ name ] | Set signals . |
26,573 | def worker_exec ( self , ** kwargs ) : self . feed ( ** kwargs ) self . logger . info ( 'thread {} exit' . format ( current_thread ( ) . name ) ) | Target function of workers |
26,574 | def feed ( self , url_template , keyword , offset , max_num , page_step ) : for i in range ( offset , offset + max_num , page_step ) : url = url_template . format ( keyword , i ) self . out_queue . put ( url ) self . logger . debug ( 'put url to url_queue: {}' . format ( url ) ) | Feed urls once |
26,575 | def connect ( self , component ) : if not isinstance ( component , ThreadPool ) : raise TypeError ( '"component" must be a ThreadPool object' ) component . in_queue = self . out_queue return component | Connect two ThreadPools . |
26,576 | 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' : self . file_idx_offset = self . storage . max_file_idx ( ) else : raise ValueError ( '"file_idx_offset" must be an integer or `auto`' ) | Set offset of file index . |
26,577 | def get_filename ( self , task , default_ext ) : url_path = urlparse ( task [ 'file_url' ] ) [ 2 ] extension = url_path . split ( '.' ) [ - 1 ] if '.' in url_path else default_ext file_idx = self . fetched_num + self . file_idx_offset return '{:06d}.{}' . format ( file_idx , extension ) | Set the path where the image will be saved . |
26,578 | 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 : return True else : return False | Check if downloaded images reached max num . |
26,579 | def download ( self , task , default_ext , timeout = 5 , max_retry = 3 , overwrite = False , ** kwargs ) : file_url = task [ 'file_url' ] task [ 'success' ] = False task [ 'filename' ] = None retry = max_retry if not overwrite : with self . lock : self . fetched_num += 1 filename = self . get_filename ( task , default_... | Download the image and save it to the corresponding path . |
26,580 | def keep_file ( self , task , response , min_size = None , max_size = None ) : try : img = Image . open ( BytesIO ( response . content ) ) except ( IOError , OSError ) : return False task [ 'img_size' ] = img . size if min_size and not self . _size_gt ( img . size , min_size ) : return False if max_size and not self . ... | Decide whether to keep the image |
26,581 | def set_logger ( self , log_level = logging . INFO ) : logging . basicConfig ( format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s' , level = log_level , stream = sys . stderr ) self . logger = logging . getLogger ( __name__ ) logging . getLogger ( 'requests' ) . setLevel ( logging . WARNING ) | Configure the logger with log_level . |
26,582 | def set_storage ( self , storage ) : if isinstance ( storage , BaseStorage ) : self . storage = storage elif isinstance ( storage , dict ) : if 'backend' not in storage and 'root_dir' in storage : storage [ 'backend' ] = 'FileSystem' try : backend_cls = getattr ( storage_package , storage [ 'backend' ] ) except Attribu... | Set storage backend for downloader |
26,583 | 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.2564.116 Safari/537.36' ) } elif not isinstance ( headers , dict ) : raise TypeError ( '"headers" must be a dict object'... | Init session with default or custom headers |
26,584 | def value ( self ) : if self . root . stale : self . root . update ( self . root . now , None ) return self . _value | Current value of the Node |
26,585 | 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 . |
26,586 | def universe ( self ) : if self . now == self . _last_chk : return self . _funiverse else : self . _last_chk = self . now self . _funiverse = self . _universe . loc [ : self . now ] return self . _funiverse | Data universe available at the current time . Universe contains the data passed in when creating a Backtest . Use this data to determine strategy logic . |
26,587 | def outlays ( self ) : return pd . DataFrame ( { x . name : x . outlays for x in self . securities } ) | Returns a DataFrame of outlays for each child SecurityBase |
26,588 | def setup ( self , universe ) : self . _original_data = universe if self is not self . parent : self . _paper_trade = True self . _paper_amount = 1000000 paper = deepcopy ( self ) paper . parent = paper paper . root = paper paper . _paper_trade = False paper . setup ( self . _original_data ) paper . adjust ( self . _pa... | Setup strategy with universe . This will speed up future calculations and updates . |
26,589 | def update ( self , date , data = None , inow = None ) : self . root . stale = False newpt = False if self . now == 0 : newpt = True elif date != self . now : self . _net_flows = 0 self . _last_price = self . _price self . _last_value = self . _value self . _last_fee = 0.0 newpt = True self . now = date if inow is None... | Update strategy . Updates prices values weight etc . |
26,590 | def adjust ( self , amount , update = True , flow = True , fee = 0.0 ) : self . _capital += amount self . _last_fee += fee if flow : self . _net_flows += amount if update : self . root . stale = True | Adjust capital - used to inject capital to a Strategy . This injection of capital will have no effect on the children . |
26,591 | def allocate ( self , amount , child = None , update = True ) : if child is not None : if child not in self . children : c = SecurityBase ( child ) c . setup ( self . _universe ) c . update ( self . now ) self . _add_child ( c ) self . children [ child ] . allocate ( amount ) else : if self . parent == self : self . pa... | 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 . |
26,592 | def rebalance ( self , weight , child , base = np . nan , update = True ) : if weight == 0 : if child in self . children : return self . close ( child ) else : return if np . isnan ( base ) : base = self . value if child not in self . children : c = SecurityBase ( child ) c . setup ( self . _universe ) c . update ( sel... | Rebalance a child to a given weight . |
26,593 | def flatten ( self ) : [ c . allocate ( - c . value ) for c in self . _childrenv if c . value != 0 ] | Close all child positions . |
26,594 | def setup ( self , universe ) : try : prices = universe [ self . name ] except KeyError : prices = None if prices is not None : self . _prices = prices self . data = pd . DataFrame ( index = universe . index , columns = [ 'value' , 'position' ] , data = 0.0 ) self . _prices_set = True else : self . data = pd . DataFram... | Setup Security with universe . Speeds up future runs . |
26,595 | def update ( self , date , data = None , inow = None ) : if date == self . now and self . _last_pos == self . _position : return if inow is None : if date == 0 : inow = 0 else : inow = self . data . index . get_loc ( date ) if date != self . now : self . now = date if self . _prices_set : self . _price = self . _prices... | Update security with a given date and optionally some data . This will update price value weight etc . |
26,596 | def name ( self ) : if self . _name is None : self . _name = self . __class__ . __name__ return self . _name | Algo name . |
26,597 | def convert_notebooks ( ) : convert_status = call ( [ 'ipython' , 'nbconvert' , '--to' , 'rst' , '*.ipynb' ] ) if convert_status != 0 : raise SystemError ( 'Conversion failed! Status was %s' % convert_status ) notebooks = [ x for x in os . listdir ( '.' ) if '.ipynb' in x and os . path . isfile ( x ) ] names = [ os . p... | Converts IPython Notebooks to proper . rst files and moves static content to the _static directory . |
26,598 | def load ( self , local = 'localsettings.py' , default = 'settings.py' ) : self . _load_defaults ( default ) self . _load_custom ( local ) return self . settings ( ) | Load the settings dict |
26,599 | def _load_defaults ( self , default = 'settings.py' ) : if default [ - 3 : ] == '.py' : default = default [ : - 3 ] self . my_settings = { } try : settings = importlib . import_module ( default ) self . my_settings = self . _convert_to_dict ( settings ) except ImportError : log . warning ( "No default settings found" ) | Load the default settings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.