idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
49,800
def run ( self , stim , merge = True , ** merge_kwargs ) : results = list ( chain ( * [ self . run_node ( n , stim ) for n in self . roots ] ) ) results = list ( flatten ( results ) ) self . _results = results return merge_results ( results , ** merge_kwargs ) if merge else results
Executes the graph by calling all Transformers in sequence .
49,801
def run_node ( self , node , stim ) : if isinstance ( node , string_types ) : node = self . nodes [ node ] result = node . transformer . transform ( stim ) if node . is_leaf ( ) : return listify ( result ) stim = result if len ( node . children ) > 1 and isgenerator ( stim ) : stim = list ( stim ) return list ( chain (...
Executes the Transformer at a specific node .
49,802
def draw ( self , filename , color = True ) : verify_dependencies ( [ 'pgv' ] ) if not hasattr ( self , '_results' ) : raise RuntimeError ( "Graph cannot be drawn before it is executed. " "Try calling run() first." ) g = pgv . AGraph ( directed = True ) g . node_attr [ 'colorscheme' ] = 'set312' for elem in self . _res...
Render a plot of the graph via pygraphviz .
49,803
def to_json ( self ) : roots = [ ] for r in self . roots : roots . append ( r . to_json ( ) ) return { 'roots' : roots }
Returns the JSON representation of this graph .
49,804
def flatten ( l ) : for el in l : if isinstance ( el , collections . Iterable ) and not isinstance ( el , string_types ) : for sub in flatten ( el ) : yield sub else : yield el
Flatten an iterable .
49,805
def set_iterable_type ( obj ) : if not isiterable ( obj ) : return obj if config . get_option ( 'use_generators' ) : return obj if isgenerator ( obj ) else ( i for i in obj ) else : return [ set_iterable_type ( i ) for i in obj ]
Returns either a generator or a list depending on config - level settings . Should be used to wrap almost every internal iterable return . Also inspects elements recursively in the case of list returns to ensure that there are no nested generators .
49,806
def isgenerator ( obj ) : return isinstance ( obj , GeneratorType ) or ( hasattr ( obj , 'iterable' ) and isinstance ( getattr ( obj , 'iterable' ) , GeneratorType ) )
Returns True if object is a generator or a generator wrapped by a tqdm object .
49,807
def progress_bar_wrapper ( iterable , ** kwargs ) : return tqdm ( iterable , ** kwargs ) if ( config . get_option ( 'progress_bar' ) and not isinstance ( iterable , tqdm ) ) else iterable
Wrapper that applies tqdm progress bar conditional on config settings .
49,808
def get_frame ( self , index ) : frame_num = self . frame_index [ index ] onset = float ( frame_num ) / self . fps if index < self . n_frames - 1 : next_frame_num = self . frame_index [ index + 1 ] end = float ( next_frame_num ) / self . fps else : end = float ( self . duration ) duration = end - onset if end > onset e...
Get video frame at the specified index .
49,809
def save ( self , path ) : self . clip . write_videofile ( path , audio_fps = self . clip . audio . fps )
Save source video to file .
49,810
def get_frame ( self , index = None , onset = None ) : if onset : index = int ( onset * self . fps ) return super ( VideoStim , self ) . get_frame ( index )
Overrides the default behavior by giving access to the onset argument .
49,811
def hash_data ( data , blocksize = 65536 ) : data = pickle . dumps ( data ) hasher = hashlib . sha1 ( ) hasher . update ( data ) return hasher . hexdigest ( )
Hashes list of data strings or data
49,812
def check_updates ( transformers , datastore = None , stimuli = None ) : datastore = datastore or expanduser ( '~/.pliers_updates' ) prior_data = pd . read_csv ( datastore ) if exists ( datastore ) else None stimuli = stimuli or glob . glob ( join ( dirname ( realpath ( __file__ ) ) , '../tests/data/image/CC0/*' ) ) st...
Run transformers through a battery of stimuli and check if output has changed . Store results in csv file for comparison .
49,813
def scan ( args ) : backend = _get_backend ( args ) print ( 'Scanning for 10 seconds...' ) devices = miflora_scanner . scan ( backend , 10 ) print ( 'Found {} devices:' . format ( len ( devices ) ) ) for device in devices : print ( ' {}' . format ( device ) )
Scan for sensors .
49,814
def _get_backend ( args ) : if args . backend == 'gatttool' : backend = GatttoolBackend elif args . backend == 'bluepy' : backend = BluepyBackend elif args . backend == 'pygatt' : backend = PygattBackend else : raise Exception ( 'unknown backend: {}' . format ( args . backend ) ) return backend
Extract the backend class from the command line arguments .
49,815
def list_backends ( _ ) : backends = [ b . __name__ for b in available_backends ( ) ] print ( '\n' . join ( backends ) )
List all available backends .
49,816
def scan ( backend , timeout = 10 ) : result = [ ] for ( mac , name ) in backend . scan_for_devices ( timeout ) : if ( name is not None and name . lower ( ) in VALID_DEVICE_NAMES ) or mac is not None and mac . upper ( ) . startswith ( DEVICE_PREFIX ) : result . append ( mac . upper ( ) ) return result
Scan for miflora devices .
49,817
def parameter_value ( self , parameter , read_cached = True ) : if parameter == MI_BATTERY : return self . battery_level ( ) with self . lock : if ( read_cached is False ) or ( self . _last_read is None ) or ( datetime . now ( ) - self . _cache_timeout > self . _last_read ) : self . fill_cache ( ) else : _LOGGER . debu...
Return a value of one of the monitored paramaters .
49,818
def parse_version_string ( version_string ) : string_parts = version_string . split ( "." ) version_parts = [ int ( re . match ( "([0-9]*)" , string_parts [ 0 ] ) . group ( 0 ) ) , int ( re . match ( "([0-9]*)" , string_parts [ 1 ] ) . group ( 0 ) ) , int ( re . match ( "([0-9]*)" , string_parts [ 2 ] ) . group ( 0 ) )...
Parses a semver version string stripping off rc stuff if present .
49,819
def bigger_version ( version_string_a , version_string_b ) : major_a , minor_a , patch_a = parse_version_string ( version_string_a ) major_b , minor_b , patch_b = parse_version_string ( version_string_b ) if major_a > major_b : return version_string_a elif major_a == major_b and minor_a > minor_b : return version_strin...
Returns the bigger version of two version strings .
49,820
def api_version ( created_ver , last_changed_ver , return_value_ver ) : def api_min_version_decorator ( function ) : def wrapper ( function , self , * args , ** kwargs ) : if not self . version_check_mode == "none" : if self . version_check_mode == "created" : version = created_ver else : version = bigger_version ( las...
Version check decorator . Currently only checks Bigger Than .
49,821
def verify_minimum_version ( self , version_str ) : self . retrieve_mastodon_version ( ) major , minor , patch = parse_version_string ( version_str ) if major > self . mastodon_major : return False elif major == self . mastodon_major and minor > self . mastodon_minor : return False elif major == self . mastodon_major a...
Update version info from server and verify that at least the specified version is present . Returns True if version requirement is satisfied False if not .
49,822
def log_in ( self , username = None , password = None , code = None , redirect_uri = "urn:ietf:wg:oauth:2.0:oob" , refresh_token = None , scopes = __DEFAULT_SCOPES , to_file = None ) : if username is not None and password is not None : params = self . __generate_params ( locals ( ) , [ 'scopes' , 'to_file' , 'code' , '...
Get the access token for a user . The username is the e - mail used to log in into mastodon .
49,823
def timeline_list ( self , id , max_id = None , min_id = None , since_id = None , limit = None ) : id = self . __unpack_id ( id ) return self . timeline ( 'list/{0}' . format ( id ) , max_id = max_id , min_id = min_id , since_id = since_id , limit = limit )
Fetches a timeline containing all the toots by users in a given list .
49,824
def conversations ( self , max_id = None , min_id = None , since_id = None , limit = None ) : if max_id != None : max_id = self . __unpack_id ( max_id ) if min_id != None : min_id = self . __unpack_id ( min_id ) if since_id != None : since_id = self . __unpack_id ( since_id ) params = self . __generate_params ( locals ...
Fetches a users conversations . Returns a list of conversation dicts _ .
49,825
def status ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about a single toot .
49,826
def status_context ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/context' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about ancestors and descendants of a toot .
49,827
def status_reblogged_by ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/reblogged_by' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch a list of users that have reblogged a status .
49,828
def status_favourited_by ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/favourited_by' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch a list of users that have favourited a status .
49,829
def scheduled_status ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/scheduled_statuses/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about the scheduled status with the given id .
49,830
def poll ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/polls/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch information about the poll with the given id
49,831
def account ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetch account information by user id . Does not require authentication . Returns a user dict _ .
49,832
def account_following ( self , id , max_id = None , min_id = None , since_id = None , limit = None ) : id = self . __unpack_id ( id ) if max_id != None : max_id = self . __unpack_id ( max_id ) if min_id != None : min_id = self . __unpack_id ( min_id ) if since_id != None : since_id = self . __unpack_id ( since_id ) par...
Fetch users the given user is following .
49,833
def account_lists ( self , id ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/accounts/{0}/lists' . format ( str ( id ) ) return self . __api_request ( 'GET' , url , params )
Get all of the logged - in users lists which the specified user is a member of . Returns a list of list dicts _ .
49,834
def filter ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/filters/{0}' . format ( str ( id ) ) return self . __api_request ( 'GET' , url )
Fetches information about the filter with the specified id . Returns a filter dict _ .
49,835
def search ( self , q , resolve = True , result_type = None , account_id = None , offset = None , min_id = None , max_id = None ) : return self . search_v2 ( q , resolve = resolve , result_type = result_type , account_id = account_id , offset = offset , min_id = min_id , max_id = max_id )
Fetch matching hashtags accounts and statuses . Will perform webfinger lookups if resolve is True . Full - text search is only enabled if the instance supports it and is restricted to statuses the logged - in user wrote or was mentioned in . result_type can be one of accounts hashtags or statuses to only search for tha...
49,836
def list ( self , id ) : id = self . __unpack_id ( id ) return self . __api_request ( 'GET' , '/api/v1/lists/{0}' . format ( id ) )
Fetch info about a specific list . Returns a list dict _ .
49,837
def list_accounts ( self , id , max_id = None , min_id = None , since_id = None , limit = None ) : id = self . __unpack_id ( id ) if max_id != None : max_id = self . __unpack_id ( max_id ) if min_id != None : min_id = self . __unpack_id ( min_id ) if since_id != None : since_id = self . __unpack_id ( since_id ) params ...
Get the accounts that are on the given list . A limit of 0 can be specified to get all accounts without pagination . Returns a list of user dicts _ .
49,838
def status_reply ( self , to_status , status , media_ids = None , sensitive = False , visibility = None , spoiler_text = None , language = None , idempotency_key = None , content_type = None , scheduled_at = None , poll = None , untag = False ) : user_id = self . __get_logged_in_id ( ) mentioned_accounts = collections ...
Helper function - acts like status_post but prepends the name of all the users that are being replied to to the status text and retains CW and visibility if not explicitly overridden . Set untag to True if you want the reply to only go to the user you are replying to removing every other mentioned user from the convers...
49,839
def status_delete ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}' . format ( str ( id ) ) self . __api_request ( 'DELETE' , url )
Delete a status
49,840
def status_unreblog ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unreblog' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Un - reblog a status .
49,841
def status_favourite ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/favourite' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Favourite a status .
49,842
def status_unfavourite ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unfavourite' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Un - favourite a status .
49,843
def status_mute ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/mute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Mute notifications for a status .
49,844
def status_unmute ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unmute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unmute notifications for a status .
49,845
def status_pin ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/pin' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Pin a status for the logged - in user .
49,846
def status_unpin ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/statuses/{0}/unpin' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unpin a pinned status for the logged - in user .
49,847
def scheduled_status_update ( self , id , scheduled_at ) : scheduled_at = self . __consistent_isoformat_utc ( scheduled_at ) id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/scheduled_statuses/{0}' . format ( str ( id ) ) return self . __api_request ( 'PUT' , url...
Update the scheduled time of a scheduled status . New time must be at least 5 minutes into the future . Returns a scheduled toot dict _
49,848
def scheduled_status_delete ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/scheduled_statuses/{0}' . format ( str ( id ) ) self . __api_request ( 'DELETE' , url )
Deletes a scheduled status .
49,849
def poll_vote ( self , id , choices ) : id = self . __unpack_id ( id ) if not isinstance ( choices , list ) : choices = [ choices ] params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/polls/{0}/votes' . format ( id ) self . __api_request ( 'POST' , url , params )
Vote in the given poll . choices is the index of the choice you wish to register a vote for ( i . e . its index in the corresponding polls options field . In case of a poll that allows selection of more than one option a list of indices can be passed . You can only submit choices for any given poll once in case of sing...
49,850
def notifications_dismiss ( self , id ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) ) self . __api_request ( 'POST' , '/api/v1/notifications/dismiss' , params )
Deletes a single notification
49,851
def account_block ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}/block' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Block a user .
49,852
def account_unblock ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}/unblock' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unblock a user .
49,853
def account_mute ( self , id , notifications = True ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) url = '/api/v1/accounts/{0}/mute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url , params )
Mute a user .
49,854
def account_unmute ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/accounts/{0}/unmute' . format ( str ( id ) ) return self . __api_request ( 'POST' , url )
Unmute a user .
49,855
def account_update_credentials ( self , display_name = None , note = None , avatar = None , avatar_mime_type = None , header = None , header_mime_type = None , locked = None , fields = None ) : params_initial = collections . OrderedDict ( locals ( ) ) if not avatar is None : if avatar_mime_type is None and ( isinstance...
Update the profile for the currently logged - in user .
49,856
def filter_create ( self , phrase , context , irreversible = False , whole_word = True , expires_in = None ) : params = self . __generate_params ( locals ( ) ) for context_val in context : if not context_val in [ 'home' , 'notifications' , 'public' , 'thread' ] : raise MastodonIllegalArgumentError ( 'Invalid filter con...
Creates a new keyword filter . phrase is the phrase that should be filtered out context specifies from where to filter the keywords . Valid contexts are home notifications public and thread . Set irreversible to True if you want the filter to just delete statuses server side . This works only for the home and notificat...
49,857
def filter_delete ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/filters/{0}' . format ( str ( id ) ) self . __api_request ( 'DELETE' , url )
Deletes the filter with the given id .
49,858
def suggestion_delete ( self , account_id ) : account_id = self . __unpack_id ( account_id ) url = '/api/v1/suggestions/{0}' . format ( str ( account_id ) ) self . __api_request ( 'DELETE' , url )
Remove the user with the given account_id from the follow suggestions .
49,859
def list_create ( self , title ) : params = self . __generate_params ( locals ( ) ) return self . __api_request ( 'POST' , '/api/v1/lists' , params )
Create a new list with the given title . Returns the list dict _ of the created list .
49,860
def list_update ( self , id , title ) : id = self . __unpack_id ( id ) params = self . __generate_params ( locals ( ) , [ 'id' ] ) return self . __api_request ( 'PUT' , '/api/v1/lists/{0}' . format ( id ) , params )
Update info about a list where info is really the lists title . Returns the list dict _ of the modified list .
49,861
def list_delete ( self , id ) : id = self . __unpack_id ( id ) self . __api_request ( 'DELETE' , '/api/v1/lists/{0}' . format ( id ) )
Delete a list .
49,862
def report ( self , account_id , status_ids = None , comment = None , forward = False ) : account_id = self . __unpack_id ( account_id ) if not status_ids is None : if not isinstance ( status_ids , list ) : status_ids = [ status_ids ] status_ids = list ( map ( lambda x : self . __unpack_id ( x ) , status_ids ) ) params...
Report statuses to the instances administrators .
49,863
def follow_request_authorize ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/follow_requests/{0}/authorize' . format ( str ( id ) ) self . __api_request ( 'POST' , url )
Accept an incoming follow request .
49,864
def follow_request_reject ( self , id ) : id = self . __unpack_id ( id ) url = '/api/v1/follow_requests/{0}/reject' . format ( str ( id ) ) self . __api_request ( 'POST' , url )
Reject an incoming follow request .
49,865
def domain_block ( self , domain = None ) : params = self . __generate_params ( locals ( ) ) self . __api_request ( 'POST' , '/api/v1/domain_blocks' , params )
Add a block for all statuses originating from the specified domain for the logged - in user .
49,866
def domain_unblock ( self , domain = None ) : params = self . __generate_params ( locals ( ) ) self . __api_request ( 'DELETE' , '/api/v1/domain_blocks' , params )
Remove a domain block for the logged - in user .
49,867
def push_subscription_update ( self , follow_events = None , favourite_events = None , reblog_events = None , mention_events = None ) : params = { } if follow_events != None : params [ 'data[alerts][follow]' ] = follow_events if favourite_events != None : params [ 'data[alerts][favourite]' ] = favourite_events if reblo...
Modifies what kind of events the app wishes to subscribe to . Returns the updated push subscription dict _ .
49,868
def stream_user ( self , listener , run_async = False , timeout = __DEFAULT_STREAM_TIMEOUT , reconnect_async = False , reconnect_async_wait_sec = __DEFAULT_STREAM_RECONNECT_WAIT_SEC ) : return self . __stream ( '/api/v1/streaming/user' , listener , run_async = run_async , timeout = timeout , reconnect_async = reconnect...
Streams events that are relevant to the authorized user i . e . home timeline and notifications .
49,869
def stream_hashtag ( self , tag , listener , run_async = False , timeout = __DEFAULT_STREAM_TIMEOUT , reconnect_async = False , reconnect_async_wait_sec = __DEFAULT_STREAM_RECONNECT_WAIT_SEC ) : if tag . startswith ( "#" ) : raise MastodonIllegalArgumentError ( "Tag parameter should omit leading #" ) return self . __st...
Stream for all public statuses for the hashtag tag seen by the connected instance .
49,870
def stream_list ( self , id , listener , run_async = False , timeout = __DEFAULT_STREAM_TIMEOUT , reconnect_async = False , reconnect_async_wait_sec = __DEFAULT_STREAM_RECONNECT_WAIT_SEC ) : id = self . __unpack_id ( id ) return self . __stream ( "/api/v1/streaming/list?list={}" . format ( id ) , listener , run_async =...
Stream events for the current user restricted to accounts on the given list .
49,871
def __datetime_to_epoch ( self , date_time ) : date_time_utc = None if date_time . tzinfo is None : date_time_utc = date_time . replace ( tzinfo = pytz . utc ) else : date_time_utc = date_time . astimezone ( pytz . utc ) epoch_utc = datetime . datetime . utcfromtimestamp ( 0 ) . replace ( tzinfo = pytz . utc ) return (...
Converts a python datetime to unix epoch accounting for time zones and such .
49,872
def __get_logged_in_id ( self ) : if self . __logged_in_id == None : self . __logged_in_id = self . account_verify_credentials ( ) . id return self . __logged_in_id
Fetch the logged in users ID with caching . ID is reset on calls to log_in .
49,873
def __json_date_parse ( json_object ) : known_date_fields = [ "created_at" , "week" , "day" , "expires_at" , "scheduled_at" ] for k , v in json_object . items ( ) : if k in known_date_fields : if v != None : try : if isinstance ( v , int ) : json_object [ k ] = datetime . datetime . fromtimestamp ( v , pytz . utc ) els...
Parse dates in certain known json fields if possible .
49,874
def __json_strnum_to_bignum ( json_object ) : for key in ( 'id' , 'week' , 'in_reply_to_id' , 'in_reply_to_account_id' , 'logins' , 'registrations' , 'statuses' ) : if ( key in json_object and isinstance ( json_object [ key ] , six . text_type ) ) : try : json_object [ key ] = int ( json_object [ key ] ) except ValueEr...
Converts json string numerals to native python bignums .
49,875
def __json_hooks ( json_object ) : json_object = Mastodon . __json_strnum_to_bignum ( json_object ) json_object = Mastodon . __json_date_parse ( json_object ) json_object = Mastodon . __json_truefalse_parse ( json_object ) json_object = Mastodon . __json_allow_dict_attrs ( json_object ) return json_object
All the json hooks . Used in request parsing .
49,876
def __consistent_isoformat_utc ( datetime_val ) : isotime = datetime_val . astimezone ( pytz . utc ) . strftime ( "%Y-%m-%dT%H:%M:%S%z" ) if isotime [ - 2 ] != ":" : isotime = isotime [ : - 2 ] + ":" + isotime [ - 2 : ] return isotime
Function that does what isoformat does but it actually does the same every time instead of randomly doing different things on some systems and also it represents that time as the equivalent UTC time .
49,877
def __generate_params ( self , params , exclude = [ ] ) : params = collections . OrderedDict ( params ) del params [ 'self' ] param_keys = list ( params . keys ( ) ) for key in param_keys : if isinstance ( params [ key ] , bool ) and params [ key ] == False : params [ key ] = '0' if isinstance ( params [ key ] , bool )...
Internal named - parameters - to - dict helper .
49,878
def __decode_webpush_b64 ( self , data ) : missing_padding = len ( data ) % 4 if missing_padding != 0 : data += '=' * ( 4 - missing_padding ) return base64 . urlsafe_b64decode ( data )
Re - pads and decodes urlsafe base64 .
49,879
def __set_token_expired ( self , value ) : self . _token_expired = datetime . datetime . now ( ) + datetime . timedelta ( seconds = value ) return
Internal helper for oauth code
49,880
def __protocolize ( base_url ) : if not base_url . startswith ( "http://" ) and not base_url . startswith ( "https://" ) : base_url = "https://" + base_url base_url = base_url . rstrip ( "/" ) return base_url
Internal add - protocol - to - url helper
49,881
def status ( self ) : if self . report == None : return SentSms . ENROUTE else : return SentSms . DELIVERED if self . report . deliveryStatus == StatusReport . DELIVERED else SentSms . FAILED
Status of this SMS . Can be ENROUTE DELIVERED or FAILED The actual status report object may be accessed via the report attribute if status is DELIVERED or FAILED
49,882
def write ( self , data , waitForResponse = True , timeout = 5 , parseError = True , writeTerm = '\r' , expectedResponseTermSeq = None ) : self . log . debug ( 'write: %s' , data ) responseLines = super ( GsmModem , self ) . write ( data + writeTerm , waitForResponse = waitForResponse , timeout = timeout , expectedResp...
Write data to the modem .
49,883
def smsTextMode ( self , textMode ) : if textMode != self . _smsTextMode : if self . alive : self . write ( 'AT+CMGF={0}' . format ( 1 if textMode else 0 ) ) self . _smsTextMode = textMode self . _compileSmsRegexes ( )
Set to True for the modem to use text mode for SMS or False for it to use PDU mode
49,884
def _compileSmsRegexes ( self ) : if self . _smsTextMode : if self . CMGR_SM_DELIVER_REGEX_TEXT == None : self . CMGR_SM_DELIVER_REGEX_TEXT = re . compile ( r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$' ) self . CMGR_SM_REPORT_REGEXT_TEXT = re . compile ( r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)...
Compiles regular expression used for parsing SMS messages based on current mode
49,885
def smsc ( self , smscNumber ) : if smscNumber != self . _smscNumber : if self . alive : self . write ( 'AT+CSCA="{0}"' . format ( smscNumber ) ) self . _smscNumber = smscNumber
Set the default SMSC number to use when sending SMS messages
49,886
def dial ( self , number , timeout = 5 , callStatusUpdateCallbackFunc = None ) : if self . _waitForCallInitUpdate : self . _dialEvent = threading . Event ( ) try : self . write ( 'ATD{0};' . format ( number ) , timeout = timeout , waitForResponse = self . _waitForAtdResponse ) except Exception : self . _dialEvent = Non...
Calls the specified phone number using a voice phone call
49,887
def _handleCallInitiated ( self , regexMatch , callId = None , callType = 1 ) : if self . _dialEvent : if regexMatch : groups = regexMatch . groups ( ) if len ( groups ) >= 2 : self . _dialResponse = ( int ( groups [ 0 ] ) , int ( groups [ 1 ] ) ) else : self . _dialResponse = ( int ( groups [ 0 ] ) , 1 ) else : self ....
Handler for outgoing call initiated event notification line
49,888
def _handleCallAnswered ( self , regexMatch , callId = None ) : if regexMatch : groups = regexMatch . groups ( ) if len ( groups ) > 1 : callId = int ( groups [ 0 ] ) self . activeCalls [ callId ] . answered = True else : for call in dictValuesIter ( self . activeCalls ) : if call . answered == False and type ( call ) ...
Handler for outgoing call answered event notification line
49,889
def _handleSmsReceived ( self , notificationLine ) : self . log . debug ( 'SMS message received' ) cmtiMatch = self . CMTI_REGEX . match ( notificationLine ) if cmtiMatch : msgMemory = cmtiMatch . group ( 1 ) msgIndex = cmtiMatch . group ( 2 ) sms = self . readStoredSms ( msgIndex , msgMemory ) self . deleteStoredSms (...
Handler for new SMS unsolicited notification line
49,890
def _handleSmsStatusReport ( self , notificationLine ) : self . log . debug ( 'SMS status report received' ) cdsiMatch = self . CDSI_REGEX . match ( notificationLine ) if cdsiMatch : msgMemory = cdsiMatch . group ( 1 ) msgIndex = cdsiMatch . group ( 2 ) report = self . readStoredSms ( msgIndex , msgMemory ) self . dele...
Handler for SMS status reports
49,891
def hangup ( self ) : if self . active : self . _gsmModem . write ( 'ATH' ) self . answered = False self . active = False if self . id in self . _gsmModem . activeCalls : del self . _gsmModem . activeCalls [ self . id ]
End the phone call . Does nothing if the call is already inactive .
49,892
def _color ( self , color , msg ) : if self . useColor : return '{0}{1}{2}' . format ( color , msg , self . RESET_SEQ ) else : return msg
Converts a message to be printed to the user s terminal in red
49,893
def _cursorLeft ( self ) : if self . cursorPos > 0 : self . cursorPos -= 1 sys . stdout . write ( console . CURSOR_LEFT ) sys . stdout . flush ( )
Handles cursor left events
49,894
def _cursorRight ( self ) : if self . cursorPos < len ( self . inputBuffer ) : self . cursorPos += 1 sys . stdout . write ( console . CURSOR_RIGHT ) sys . stdout . flush ( )
Handles cursor right events
49,895
def _cursorUp ( self ) : if self . historyPos > 0 : self . historyPos -= 1 clearLen = len ( self . inputBuffer ) self . inputBuffer = list ( self . history [ self . historyPos ] ) self . cursorPos = len ( self . inputBuffer ) self . _refreshInputPrompt ( clearLen )
Handles cursor up events
49,896
def _handleBackspace ( self ) : if self . cursorPos > 0 : self . inputBuffer = self . inputBuffer [ 0 : self . cursorPos - 1 ] + self . inputBuffer [ self . cursorPos : ] self . cursorPos -= 1 self . _refreshInputPrompt ( len ( self . inputBuffer ) + 1 )
Handles backspace characters
49,897
def _handleDelete ( self ) : if self . cursorPos < len ( self . inputBuffer ) : self . inputBuffer = self . inputBuffer [ 0 : self . cursorPos ] + self . inputBuffer [ self . cursorPos + 1 : ] self . _refreshInputPrompt ( len ( self . inputBuffer ) + 1 )
Handles delete characters
49,898
def _handleEnd ( self ) : self . cursorPos = len ( self . inputBuffer ) self . _refreshInputPrompt ( len ( self . inputBuffer ) )
Handles end character
49,899
def _doCommandCompletion ( self ) : prefix = '' . join ( self . inputBuffer ) . strip ( ) . upper ( ) matches = self . completion . keys ( prefix ) matchLen = len ( matches ) if matchLen == 0 and prefix [ - 1 ] == '=' : try : command = prefix [ : - 1 ] except KeyError : pass else : self . __printCommandSyntax ( command...
Command - completion method