idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
18,500 | def retry ( retry_count = 5 , delay = 2 ) : if retry_count <= 0 : raise ValueError ( "retry_count have to be positive" ) def decorator ( f ) : @ functools . wraps ( f ) def wrapper ( * args , * * kwargs ) : for i in range ( retry_count , 0 , - 1 ) : try : return f ( * args , * * kwargs ) except Exception : if i <= 1 : raise time . sleep ( delay ) return wrapper return decorator | Use as decorator to retry functions few times with delays | 118 | 12 |
18,501 | def parse ( cls , image_name ) : result = cls ( ) # registry.org/namespace/repo:tag s = image_name . split ( '/' , 2 ) if len ( s ) == 2 : if '.' in s [ 0 ] or ':' in s [ 0 ] : result . registry = s [ 0 ] else : result . namespace = s [ 0 ] elif len ( s ) == 3 : result . registry = s [ 0 ] result . namespace = s [ 1 ] result . repository = s [ - 1 ] try : result . repository , result . digest = result . repository . rsplit ( "@" , 1 ) except ValueError : try : result . repository , result . tag = result . repository . rsplit ( ":" , 1 ) except ValueError : result . tag = "latest" return result | Get the instance of ImageName from the string representation . | 180 | 11 |
18,502 | def other_attributes ( self ) : return { k : v for k , v in self . c . items ( ) if k not in [ "name" , "names" , "tags" , "additional_tags" , "usable_targets" ] } | return dict with all other data except for the described above | 59 | 11 |
18,503 | def should_we_load ( kls ) : # we don't load abstract classes if kls . __name__ . endswith ( "AbstractCheck" ) : return False # and we only load checks if not kls . __name__ . endswith ( "Check" ) : return False mro = kls . __mro__ # and the class needs to be a child of AbstractCheck for m in mro : if m . __name__ == "AbstractCheck" : return True return False | should we load this class as a check? | 108 | 9 |
18,504 | def obtain_check_classes ( self ) : check_classes = set ( ) for path in self . paths : for root , _ , files in os . walk ( path ) : for fi in files : if not fi . endswith ( ".py" ) : continue path = os . path . join ( root , fi ) check_classes = check_classes . union ( set ( load_check_classes_from_file ( path ) ) ) return list ( check_classes ) | find children of AbstractCheck class and return them as a list | 102 | 12 |
18,505 | def import_class ( self , import_name ) : module_name , class_name = import_name . rsplit ( "." , 1 ) mod = import_module ( module_name ) check_class = getattr ( mod , class_name ) self . mapping [ check_class . name ] = check_class logger . info ( "successfully loaded class %s" , check_class ) return check_class | import selected class | 89 | 3 |
18,506 | def _dict_of_results ( self ) : result_json = { } result_list = [ ] for r in self . results : result_list . append ( { 'name' : r . check_name , 'ok' : r . ok , 'status' : r . status , 'description' : r . description , 'message' : r . message , 'reference_url' : r . reference_url , 'logs' : r . logs , } ) result_json [ "checks" ] = result_list return result_json | Get the dictionary representation of results | 118 | 6 |
18,507 | def statistics ( self ) : result = { } for r in self . results : result . setdefault ( r . status , 0 ) result [ r . status ] += 1 return result | Get the dictionary with the count of the check - statuses | 38 | 12 |
18,508 | def generate_pretty_output ( self , stat , verbose , output_function , logs = True ) : has_check = False for r in self . results : has_check = True if stat : output_function ( OUTPUT_CHARS [ r . status ] , fg = COLOURS [ r . status ] , nl = False ) else : output_function ( str ( r ) , fg = COLOURS [ r . status ] ) if verbose : output_function ( " -> {}\n" " -> {}" . format ( r . description , r . reference_url ) , fg = COLOURS [ r . status ] ) if logs and r . logs : output_function ( " -> logs:" , fg = COLOURS [ r . status ] ) for l in r . logs : output_function ( " -> {}" . format ( l ) , fg = COLOURS [ r . status ] ) if not has_check : output_function ( "No check found." ) elif stat and not verbose : output_function ( "" ) else : output_function ( "" ) for status , count in six . iteritems ( self . statistics ) : output_function ( "{}:{} " . format ( status , count ) , nl = False ) output_function ( "" ) | Send the formated to the provided function | 284 | 8 |
18,509 | def get_pretty_string ( self , stat , verbose ) : pretty_output = _PrettyOutputToStr ( ) self . generate_pretty_output ( stat = stat , verbose = verbose , output_function = pretty_output . save_output ) return pretty_output . result | Pretty string representation of the results | 62 | 6 |
18,510 | def receive_fmf_metadata ( name , path , object_list = False ) : output = { } fmf_tree = ExtendedTree ( path ) logger . debug ( "get FMF metadata for test (path:%s name=%s)" , path , name ) # ignore items with @ in names, to avoid using unreferenced items items = [ x for x in fmf_tree . climb ( ) if x . name . endswith ( "/" + name ) and "@" not in x . name ] if object_list : return items if len ( items ) == 1 : output = items [ 0 ] elif len ( items ) > 1 : raise Exception ( "There is more FMF test metadata for item by name:{}({}) {}" . format ( name , len ( items ) , [ x . name for x in items ] ) ) elif not items : raise Exception ( "Unable to get FMF metadata for: {}" . format ( name ) ) return output | search node identified by name fmfpath | 215 | 9 |
18,511 | def list_checks ( ruleset , ruleset_file , debug , json , skip , tag , verbose , checks_paths ) : if ruleset and ruleset_file : raise click . BadOptionUsage ( "Options '--ruleset' and '--file-ruleset' cannot be used together." ) try : if not debug : logging . basicConfig ( stream = six . StringIO ( ) ) log_level = _get_log_level ( debug = debug , verbose = verbose ) checks = get_checks ( ruleset_name = ruleset , ruleset_file = ruleset_file , logging_level = log_level , tags = tag , checks_paths = checks_paths , skips = skip ) _print_checks ( checks = checks ) if json : AbstractCheck . save_checks_to_json ( file = json , checks = checks ) except ColinException as ex : logger . error ( "An error occurred: %r" , ex ) if debug : raise else : raise click . ClickException ( str ( ex ) ) except Exception as ex : logger . error ( "An error occurred: %r" , ex ) if debug : raise else : raise click . ClickException ( str ( ex ) ) | Print the checks . | 265 | 4 |
18,512 | def list_rulesets ( debug ) : try : rulesets = get_rulesets ( ) max_len = max ( [ len ( r [ 0 ] ) for r in rulesets ] ) for r in rulesets : click . echo ( '{0: <{1}} ({2})' . format ( r [ 0 ] , max_len , r [ 1 ] ) ) except Exception as ex : logger . error ( "An error occurred: %r" , ex ) if debug : raise else : raise click . ClickException ( str ( ex ) ) | List available rulesets . | 118 | 5 |
18,513 | def info ( ) : installation_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . path . pardir ) ) click . echo ( "colin {} {}" . format ( __version__ , installation_path ) ) click . echo ( "colin-cli {}\n" . format ( os . path . realpath ( __file__ ) ) ) # click.echo(get_version_of_the_python_package(module=conu)) rpm_installed = is_rpm_installed ( ) click . echo ( get_version_msg_from_the_cmd ( package_name = "podman" , use_rpm = rpm_installed ) ) click . echo ( get_version_msg_from_the_cmd ( package_name = "skopeo" , use_rpm = rpm_installed ) ) click . echo ( get_version_msg_from_the_cmd ( package_name = "ostree" , use_rpm = rpm_installed , max_lines_of_the_output = 3 ) ) | Show info about colin and its dependencies . | 241 | 9 |
18,514 | def _print_results ( results , stat = False , verbose = False ) : results . generate_pretty_output ( stat = stat , verbose = verbose , output_function = click . secho ) | Prints the results to the stdout | 45 | 8 |
18,515 | def labels ( self ) : if self . _labels is None : self . _labels = self . instance . labels return self . _labels | Get list of labels from the target instance . | 32 | 9 |
18,516 | def labels ( self ) : if self . _labels is None : cmd = [ "skopeo" , "inspect" , self . skopeo_target ] self . _labels = json . loads ( subprocess . check_output ( cmd ) ) [ "Labels" ] return self . _labels | Provide labels without the need of dockerd . Instead skopeo is being used . | 69 | 18 |
18,517 | def tmpdir ( self ) : if self . _tmpdir is None : self . _tmpdir = mkdtemp ( prefix = "colin-" , dir = "/var/tmp" ) return self . _tmpdir | Temporary directory holding all the runtime data . | 47 | 9 |
18,518 | def _checkout ( self ) : cmd = [ "atomic" , "mount" , "--storage" , "ostree" , self . ref_image_name , self . mount_point ] # self.mount_point has to be created by us self . _run_and_log ( cmd , self . ostree_path , "Failed to mount selected image as an ostree repo." ) | check out the image filesystem on self . mount_point | 87 | 11 |
18,519 | def _run_and_log ( cmd , ostree_repo_path , error_msg , wd = None ) : logger . debug ( "running command %s" , cmd ) kwargs = { "stderr" : subprocess . STDOUT , "env" : os . environ . copy ( ) , } if ostree_repo_path : # must not exist, ostree will create it kwargs [ "env" ] [ "ATOMIC_OSTREE_REPO" ] = ostree_repo_path if wd : kwargs [ "cwd" ] = wd try : out = subprocess . check_output ( cmd , * * kwargs ) except subprocess . CalledProcessError as ex : logger . error ( ex . output ) logger . error ( error_msg ) raise logger . debug ( "%s" , out ) | run provided command and log all of its output ; set path to ostree repo | 192 | 16 |
18,520 | def login_with_google ( self , email , oauth2_token , * * kwargs ) : params = { 'email' : email , 'oauth2_token' : oauth2_token } req_func = self . _get if kwargs . get ( 'auto_signup' , 0 ) == 1 : # POST if we're creating a user. req_func = self . _post return req_func ( 'login_with_google' , params , * * kwargs ) | Login to Todoist using Google s oauth2 authentication . | 112 | 13 |
18,521 | def register ( self , email , full_name , password , * * kwargs ) : params = { 'email' : email , 'full_name' : full_name , 'password' : password } return self . _post ( 'register' , params , * * kwargs ) | Register a new Todoist user . | 63 | 8 |
18,522 | def delete_user ( self , api_token , password , * * kwargs ) : params = { 'token' : api_token , 'current_password' : password } return self . _post ( 'delete_user' , params , * * kwargs ) | Delete a registered Todoist user s account . | 59 | 10 |
18,523 | def sync ( self , api_token , sync_token , resource_types = '["all"]' , * * kwargs ) : params = { 'token' : api_token , 'sync_token' : sync_token , } req_func = self . _post if 'commands' not in kwargs : # GET if we're not changing data. req_func = self . _get params [ 'resource_types' ] = resource_types return req_func ( 'sync' , params , * * kwargs ) | Update and retrieve Todoist data . | 117 | 8 |
18,524 | def query ( self , api_token , queries , * * kwargs ) : params = { 'token' : api_token , 'queries' : queries } return self . _get ( 'query' , params , * * kwargs ) | Search all of a user s tasks using date priority and label queries . | 54 | 14 |
18,525 | def add_item ( self , api_token , content , * * kwargs ) : params = { 'token' : api_token , 'content' : content } return self . _post ( 'add_item' , params , * * kwargs ) | Add a task to a project . | 57 | 7 |
18,526 | def quick_add ( self , api_token , text , * * kwargs ) : params = { 'token' : api_token , 'text' : text } return self . _post ( 'quick/add' , params , * * kwargs ) | Add a task using the Todoist Quick Add Task syntax . | 57 | 13 |
18,527 | def get_all_completed_tasks ( self , api_token , * * kwargs ) : params = { 'token' : api_token } return self . _get ( 'get_all_completed_items' , params , * * kwargs ) | Return a list of a user s completed tasks . | 60 | 10 |
18,528 | def upload_file ( self , api_token , file_path , * * kwargs ) : params = { 'token' : api_token , 'file_name' : os . path . basename ( file_path ) } with open ( file_path , 'rb' ) as f : files = { 'file' : f } return self . _post ( 'upload_file' , params , files , * * kwargs ) | Upload a file suitable to be passed as a file_attachment . | 96 | 14 |
18,529 | def get_productivity_stats ( self , api_token , * * kwargs ) : params = { 'token' : api_token } return self . _get ( 'get_productivity_stats' , params , * * kwargs ) | Return a user s productivity stats . | 55 | 7 |
18,530 | def update_notification_settings ( self , api_token , event , service , should_notify ) : params = { 'token' : api_token , 'notification_type' : event , 'service' : service , 'dont_notify' : should_notify } return self . _post ( 'update_notification_setting' , params ) | Update a user s notification settings . | 80 | 7 |
18,531 | def _get ( self , end_point , params = None , * * kwargs ) : return self . _request ( requests . get , end_point , params , * * kwargs ) | Send a HTTP GET request to a Todoist API end - point . | 43 | 15 |
18,532 | def _post ( self , end_point , params = None , files = None , * * kwargs ) : return self . _request ( requests . post , end_point , params , files , * * kwargs ) | Send a HTTP POST request to a Todoist API end - point . | 49 | 15 |
18,533 | def _request ( self , req_func , end_point , params = None , files = None , * * kwargs ) : url = self . URL + end_point if params and kwargs : params . update ( kwargs ) return req_func ( url , params = params , files = files ) | Send a HTTP request to a Todoist API end - point . | 68 | 14 |
18,534 | def login_with_api_token ( api_token ) : response = API . sync ( api_token , '*' , '["user"]' ) _fail_if_contains_errors ( response ) user_json = response . json ( ) [ 'user' ] # Required as sync doesn't return the api_token. user_json [ 'api_token' ] = user_json [ 'token' ] return User ( user_json ) | Login to Todoist using a user s api token . | 98 | 12 |
18,535 | def _login ( login_func , * args ) : response = login_func ( * args ) _fail_if_contains_errors ( response ) user_json = response . json ( ) return User ( user_json ) | A helper function for logging in . It s purpose is to avoid duplicate code in the login functions . | 49 | 20 |
18,536 | def register ( full_name , email , password , lang = None , timezone = None ) : response = API . register ( email , full_name , password , lang = lang , timezone = timezone ) _fail_if_contains_errors ( response ) user_json = response . json ( ) user = User ( user_json ) user . password = password return user | Register a new Todoist account . | 81 | 8 |
18,537 | def register_with_google ( full_name , email , oauth2_token , lang = None , timezone = None ) : response = API . login_with_google ( email , oauth2_token , auto_signup = 1 , full_name = full_name , lang = lang , timezone = timezone ) _fail_if_contains_errors ( response ) user_json = response . json ( ) user = User ( user_json ) return user | Register a new Todoist account by linking a Google account . | 103 | 13 |
18,538 | def _fail_if_contains_errors ( response , sync_uuid = None ) : if response . status_code != _HTTP_OK : raise RequestError ( response ) response_json = response . json ( ) if sync_uuid and 'sync_status' in response_json : status = response_json [ 'sync_status' ] if sync_uuid in status and 'error' in status [ sync_uuid ] : raise RequestError ( response ) | Raise a RequestError Exception if a given response does not denote a successful request . | 102 | 17 |
18,539 | def _perform_command ( user , command_type , command_args ) : command_uuid = _gen_uuid ( ) command = { 'type' : command_type , 'args' : command_args , 'uuid' : command_uuid , 'temp_id' : _gen_uuid ( ) } commands = json . dumps ( [ command ] ) response = API . sync ( user . api_token , user . sync_token , commands = commands ) _fail_if_contains_errors ( response , command_uuid ) response_json = response . json ( ) user . sync_token = response_json [ 'sync_token' ] | Perform an operation on Todoist using the API sync end - point . | 147 | 16 |
18,540 | def update ( self ) : args = { attr : getattr ( self , attr ) for attr in self . to_update } _perform_command ( self , 'user_update' , args ) | Update the user s details on Todoist . | 46 | 10 |
18,541 | def sync ( self , resource_types = '["all"]' ) : response = API . sync ( self . api_token , '*' , resource_types ) _fail_if_contains_errors ( response ) response_json = response . json ( ) self . sync_token = response_json [ 'sync_token' ] if 'projects' in response_json : self . _sync_projects ( response_json [ 'projects' ] ) if 'items' in response_json : self . _sync_tasks ( response_json [ 'items' ] ) if 'notes' in response_json : self . _sync_notes ( response_json [ 'notes' ] ) if 'labels' in response_json : self . _sync_labels ( response_json [ 'labels' ] ) if 'filters' in response_json : self . _sync_filters ( response_json [ 'filters' ] ) if 'reminders' in response_json : self . _sync_reminders ( response_json [ 'reminders' ] ) | Synchronize the user s data with the Todoist server . | 233 | 14 |
18,542 | def _sync_projects ( self , projects_json ) : for project_json in projects_json : project_id = project_json [ 'id' ] self . projects [ project_id ] = Project ( project_json , self ) | Populate the user s projects from a JSON encoded list . | 51 | 12 |
18,543 | def _sync_tasks ( self , tasks_json ) : for task_json in tasks_json : task_id = task_json [ 'id' ] project_id = task_json [ 'project_id' ] if project_id not in self . projects : # ignore orphan tasks continue project = self . projects [ project_id ] self . tasks [ task_id ] = Task ( task_json , project ) | Populate the user s tasks from a JSON encoded list . | 91 | 12 |
18,544 | def _sync_notes ( self , notes_json ) : for note_json in notes_json : note_id = note_json [ 'id' ] task_id = note_json [ 'item_id' ] if task_id not in self . tasks : # ignore orphan notes continue task = self . tasks [ task_id ] self . notes [ note_id ] = Note ( note_json , task ) | Populate the user s notes from a JSON encoded list . | 90 | 12 |
18,545 | def _sync_labels ( self , labels_json ) : for label_json in labels_json : label_id = label_json [ 'id' ] self . labels [ label_id ] = Label ( label_json , self ) | Populate the user s labels from a JSON encoded list . | 52 | 12 |
18,546 | def _sync_filters ( self , filters_json ) : for filter_json in filters_json : filter_id = filter_json [ 'id' ] self . filters [ filter_id ] = Filter ( filter_json , self ) | Populate the user s filters from a JSON encoded list . | 52 | 12 |
18,547 | def _sync_reminders ( self , reminders_json ) : for reminder_json in reminders_json : reminder_id = reminder_json [ 'id' ] task_id = reminder_json [ 'item_id' ] if task_id not in self . tasks : # ignore orphan reminders continue task = self . tasks [ task_id ] self . reminders [ reminder_id ] = Reminder ( reminder_json , task ) | Populate the user s reminders from a JSON encoded list . | 92 | 12 |
18,548 | def quick_add ( self , text , note = None , reminder = None ) : response = API . quick_add ( self . api_token , text , note = note , reminder = reminder ) _fail_if_contains_errors ( response ) task_json = response . json ( ) return Task ( task_json , self ) | Add a task using the Quick Add Task syntax . | 72 | 10 |
18,549 | def add_project ( self , name , color = None , indent = None , order = None ) : args = { 'name' : name , 'color' : color , 'indent' : indent , 'order' : order } args = { k : args [ k ] for k in args if args [ k ] is not None } _perform_command ( self , 'project_add' , args ) return self . get_project ( name ) | Add a project to the user s account . | 97 | 9 |
18,550 | def get_project ( self , project_name ) : for project in self . get_projects ( ) : if project . name == project_name : return project | Return the project with a given name . | 34 | 8 |
18,551 | def get_uncompleted_tasks ( self ) : tasks = ( p . get_uncompleted_tasks ( ) for p in self . get_projects ( ) ) return list ( itertools . chain . from_iterable ( tasks ) ) | Return all of a user s uncompleted tasks . | 56 | 10 |
18,552 | def search_tasks ( self , * queries ) : queries = json . dumps ( queries ) response = API . query ( self . api_token , queries ) _fail_if_contains_errors ( response ) query_results = response . json ( ) tasks = [ ] for result in query_results : if 'data' not in result : continue all_tasks = result [ 'data' ] if result [ 'type' ] == Query . ALL : all_projects = all_tasks for project_json in all_projects : uncompleted_tasks = project_json . get ( 'uncompleted' , [ ] ) completed_tasks = project_json . get ( 'completed' , [ ] ) all_tasks = uncompleted_tasks + completed_tasks for task_json in all_tasks : project_id = task_json [ 'project_id' ] project = self . projects [ project_id ] task = Task ( task_json , project ) tasks . append ( task ) return tasks | Return a list of tasks that match some search criteria . | 222 | 11 |
18,553 | def get_label ( self , label_name ) : for label in self . get_labels ( ) : if label . name == label_name : return label | Return the user s label that has a given name . | 35 | 11 |
18,554 | def add_filter ( self , name , query , color = None , item_order = None ) : args = { 'name' : name , 'query' : query , 'color' : color , 'item_order' : item_order } _perform_command ( self , 'filter_add' , args ) return self . get_filter ( name ) | Create a new filter . | 78 | 5 |
18,555 | def get_filter ( self , name ) : for flter in self . get_filters ( ) : if flter . name == name : return flter | Return the filter that has the given filter name . | 34 | 10 |
18,556 | def _update_notification_settings ( self , event , service , should_notify ) : response = API . update_notification_settings ( self . api_token , event , service , should_notify ) _fail_if_contains_errors ( response ) | Update the settings of a an events notifications . | 59 | 9 |
18,557 | def get_productivity_stats ( self ) : response = API . get_productivity_stats ( self . api_token ) _fail_if_contains_errors ( response ) return response . json ( ) | Return the user s productivity stats . | 46 | 7 |
18,558 | def delete ( self , reason = None ) : response = API . delete_user ( self . api_token , self . password , reason = reason , in_background = 0 ) _fail_if_contains_errors ( response ) | Delete the user s account from Todoist . | 50 | 10 |
18,559 | def archive ( self ) : args = { 'id' : self . id } _perform_command ( self . owner , 'project_archive' , args ) self . is_archived = '1' | Archive the project . | 45 | 5 |
18,560 | def add_task ( self , content , date = None , priority = None ) : response = API . add_item ( self . owner . token , content , project_id = self . id , date_string = date , priority = priority ) _fail_if_contains_errors ( response ) task_json = response . json ( ) return Task ( task_json , self ) | Add a task to the project | 82 | 6 |
18,561 | def get_uncompleted_tasks ( self ) : all_tasks = self . get_tasks ( ) completed_tasks = self . get_completed_tasks ( ) return [ t for t in all_tasks if t not in completed_tasks ] | Return a list of all uncompleted tasks in this project . | 61 | 12 |
18,562 | def get_completed_tasks ( self ) : self . owner . sync ( ) tasks = [ ] offset = 0 while True : response = API . get_all_completed_tasks ( self . owner . api_token , limit = _PAGE_LIMIT , offset = offset , project_id = self . id ) _fail_if_contains_errors ( response ) response_json = response . json ( ) tasks_json = response_json [ 'items' ] if len ( tasks_json ) == 0 : break # There are no more completed tasks to retreive. for task_json in tasks_json : project = self . owner . projects [ task_json [ 'project_id' ] ] tasks . append ( Task ( task_json , project ) ) offset += _PAGE_LIMIT return tasks | Return a list of all completed tasks in this project . | 181 | 11 |
18,563 | def get_tasks ( self ) : self . owner . sync ( ) return [ t for t in self . owner . tasks . values ( ) if t . project_id == self . id ] | Return all tasks in this project . | 42 | 7 |
18,564 | def add_note ( self , content ) : args = { 'project_id' : self . id , 'content' : content } _perform_command ( self . owner , 'note_add' , args ) | Add a note to the project . | 47 | 7 |
18,565 | def get_notes ( self ) : self . owner . sync ( ) notes = self . owner . notes . values ( ) return [ n for n in notes if n . project_id == self . id ] | Return a list of all of the project s notes . | 44 | 11 |
18,566 | def share ( self , email , message = None ) : args = { 'project_id' : self . id , 'email' : email , 'message' : message } _perform_command ( self . owner , 'share_project' , args ) | Share the project with another Todoist user . | 55 | 10 |
18,567 | def delete_collaborator ( self , email ) : args = { 'project_id' : self . id , 'email' : email , } _perform_command ( self . owner , 'delete_collaborator' , args ) | Remove a collaborating user from the shared project . | 52 | 9 |
18,568 | def complete ( self ) : args = { 'id' : self . id } _perform_command ( self . project . owner , 'item_close' , args ) | Mark the task complete . | 37 | 5 |
18,569 | def uncomplete ( self ) : args = { 'project_id' : self . project . id , 'ids' : [ self . id ] } owner = self . project . owner _perform_command ( owner , 'item_uncomplete' , args ) | Mark the task uncomplete . | 56 | 6 |
18,570 | def get_notes ( self ) : owner = self . project . owner owner . sync ( ) return [ n for n in owner . notes . values ( ) if n . item_id == self . id ] | Return all notes attached to this Task . | 44 | 8 |
18,571 | def move ( self , project ) : args = { 'project_items' : { self . project . id : [ self . id ] } , 'to_project' : project . id } _perform_command ( self . project . owner , 'item_move' , args ) self . project = project | Move this task to another project . | 66 | 7 |
18,572 | def add_date_reminder ( self , service , due_date ) : args = { 'item_id' : self . id , 'service' : service , 'type' : 'absolute' , 'due_date_utc' : due_date } _perform_command ( self . project . owner , 'reminder_add' , args ) | Add a reminder to the task which activates on a given date . | 78 | 13 |
18,573 | def add_location_reminder ( self , service , name , lat , long , trigger , radius ) : args = { 'item_id' : self . id , 'service' : service , 'type' : 'location' , 'name' : name , 'loc_lat' : str ( lat ) , 'loc_long' : str ( long ) , 'loc_trigger' : trigger , 'radius' : radius } _perform_command ( self . project . owner , 'reminder_add' , args ) | Add a reminder to the task which activates on at a given location . | 113 | 14 |
18,574 | def get_reminders ( self ) : owner = self . project . owner return [ r for r in owner . get_reminders ( ) if r . task . id == self . id ] | Return a list of the task s reminders . | 41 | 9 |
18,575 | def delete ( self ) : args = { 'ids' : [ self . id ] } _perform_command ( self . project . owner , 'item_delete' , args ) del self . project . owner . tasks [ self . id ] | Delete the task . | 52 | 4 |
18,576 | def delete ( self ) : args = { 'id' : self . id } owner = self . task . project . owner _perform_command ( owner , 'note_delete' , args ) | Delete the note removing it from it s task . | 42 | 10 |
18,577 | def update ( self ) : args = { attr : getattr ( self , attr ) for attr in self . to_update } args [ 'id' ] = self . id _perform_command ( self . owner , 'filter_update' , args ) | Update the filter s details on Todoist . | 58 | 10 |
18,578 | def apply_text ( incoming , func ) : split = RE_SPLIT . split ( incoming ) for i , item in enumerate ( split ) : if not item or RE_SPLIT . match ( item ) : continue split [ i ] = func ( item ) return incoming . __class__ ( ) . join ( split ) | Call func on text portions of incoming color string . | 71 | 10 |
18,579 | def decode ( self , encoding = 'utf-8' , errors = 'strict' ) : original_class = getattr ( self , 'original_class' ) return original_class ( super ( ColorBytes , self ) . decode ( encoding , errors ) ) | Decode using the codec registered for encoding . Default encoding is utf - 8 . | 56 | 17 |
18,580 | def center ( self , width , fillchar = None ) : if fillchar is not None : result = self . value_no_colors . center ( width , fillchar ) else : result = self . value_no_colors . center ( width ) return self . __class__ ( result . replace ( self . value_no_colors , self . value_colors ) , keep_tags = True ) | Return centered in a string of length width . Padding is done using the specified fill character or space . | 89 | 21 |
18,581 | def endswith ( self , suffix , start = 0 , end = None ) : args = [ suffix , start ] + ( [ ] if end is None else [ end ] ) return self . value_no_colors . endswith ( * args ) | Return True if ends with the specified suffix False otherwise . | 55 | 11 |
18,582 | def encode ( self , encoding = None , errors = 'strict' ) : return ColorBytes ( super ( ColorStr , self ) . encode ( encoding , errors ) , original_class = self . __class__ ) | Encode using the codec registered for encoding . encoding defaults to the default encoding . | 46 | 16 |
18,583 | def decode ( self , encoding = None , errors = 'strict' ) : return self . __class__ ( super ( ColorStr , self ) . decode ( encoding , errors ) , keep_tags = True ) | Decode using the codec registered for encoding . encoding defaults to the default encoding . | 45 | 16 |
18,584 | def format ( self , * args , * * kwargs ) : return self . __class__ ( super ( ColorStr , self ) . format ( * args , * * kwargs ) , keep_tags = True ) | Return a formatted version using substitutions from args and kwargs . | 48 | 14 |
18,585 | def join ( self , iterable ) : return self . __class__ ( super ( ColorStr , self ) . join ( iterable ) , keep_tags = True ) | Return a string which is the concatenation of the strings in the iterable . | 36 | 17 |
18,586 | def splitlines ( self , keepends = False ) : return [ self . __class__ ( l ) for l in self . value_colors . splitlines ( keepends ) ] | Return a list of the lines in the string breaking at line boundaries . | 39 | 14 |
18,587 | def startswith ( self , prefix , start = 0 , end = - 1 ) : return self . value_no_colors . startswith ( prefix , start , end ) | Return True if string starts with the specified prefix False otherwise . | 39 | 12 |
18,588 | def zfill ( self , width ) : if not self . value_no_colors : result = self . value_no_colors . zfill ( width ) else : result = self . value_colors . replace ( self . value_no_colors , self . value_no_colors . zfill ( width ) ) return self . __class__ ( result , keep_tags = True ) | Pad a numeric string with zeros on the left to fill a field of the specified width . | 88 | 19 |
18,589 | def colorize ( cls , color , string , auto = False ) : tag = '{0}{1}' . format ( 'auto' if auto else '' , color ) return cls ( '{%s}%s{/%s}' % ( tag , string , tag ) ) | Color - code entire string using specified color . | 64 | 9 |
18,590 | def list_tags ( ) : # Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi]. reverse_dict = dict ( ) for tag , ansi in sorted ( BASE_CODES . items ( ) ) : if tag . startswith ( '/' ) : reverse_dict [ tag ] = [ ansi , None , None ] else : reverse_dict [ '/' + tag ] [ 1 : ] = [ tag , ansi ] # Collapse four_item_tuples = [ ( v [ 1 ] , k , v [ 2 ] , v [ 0 ] ) for k , v in reverse_dict . items ( ) ] # Sort. def sorter ( four_item ) : """Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors. :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value] :return Sorting weight. :rtype: int """ if not four_item [ 2 ] : # /all /fg /bg return four_item [ 3 ] - 200 if four_item [ 2 ] < 10 or four_item [ 0 ] . startswith ( 'auto' ) : # b f i u or auto colors return four_item [ 2 ] - 100 return four_item [ 2 ] four_item_tuples . sort ( key = sorter ) return four_item_tuples | List the available tags . | 320 | 5 |
18,591 | def disable_if_no_tty ( cls ) : if sys . stdout . isatty ( ) or sys . stderr . isatty ( ) : return False cls . disable_all_colors ( ) return True | Disable all colors only if there is no TTY available . | 52 | 12 |
18,592 | def get_console_info ( kernel32 , handle ) : # Query Win32 API. csbi = ConsoleScreenBufferInfo ( ) # Populated by GetConsoleScreenBufferInfo. lpcsbi = ctypes . byref ( csbi ) dword = ctypes . c_ulong ( ) # Populated by GetConsoleMode. lpdword = ctypes . byref ( dword ) if not kernel32 . GetConsoleScreenBufferInfo ( handle , lpcsbi ) or not kernel32 . GetConsoleMode ( handle , lpdword ) : raise ctypes . WinError ( ) # Parse data. # buffer_width = int(csbi.dwSize.X - 1) # buffer_height = int(csbi.dwSize.Y) # terminal_width = int(csbi.srWindow.Right - csbi.srWindow.Left) # terminal_height = int(csbi.srWindow.Bottom - csbi.srWindow.Top) fg_color = csbi . wAttributes % 16 bg_color = csbi . wAttributes & 240 native_ansi = bool ( dword . value & ENABLE_VIRTUAL_TERMINAL_PROCESSING ) return fg_color , bg_color , native_ansi | Get information about this current console window . | 280 | 8 |
18,593 | def bg_color_native_ansi ( kernel32 , stderr , stdout ) : try : if stderr == INVALID_HANDLE_VALUE : raise OSError bg_color , native_ansi = get_console_info ( kernel32 , stderr ) [ 1 : ] except OSError : try : if stdout == INVALID_HANDLE_VALUE : raise OSError bg_color , native_ansi = get_console_info ( kernel32 , stdout ) [ 1 : ] except OSError : bg_color , native_ansi = WINDOWS_CODES [ 'black' ] , False return bg_color , native_ansi | Get background color and if console supports ANSI colors natively for both streams . | 164 | 16 |
18,594 | def colors ( self ) : try : return get_console_info ( self . _kernel32 , self . _stream_handle ) [ : 2 ] except OSError : return WINDOWS_CODES [ 'white' ] , WINDOWS_CODES [ 'black' ] | Return the current foreground and background colors . | 64 | 8 |
18,595 | def colors ( self , color_code ) : if color_code is None : color_code = WINDOWS_CODES [ '/all' ] # Get current color code. current_fg , current_bg = self . colors # Handle special negative codes. Also determine the final color code. if color_code == WINDOWS_CODES [ '/fg' ] : final_color_code = self . default_fg | current_bg # Reset the foreground only. elif color_code == WINDOWS_CODES [ '/bg' ] : final_color_code = current_fg | self . default_bg # Reset the background only. elif color_code == WINDOWS_CODES [ '/all' ] : final_color_code = self . default_fg | self . default_bg # Reset both. elif color_code == WINDOWS_CODES [ 'bgblack' ] : final_color_code = current_fg # Black background. else : new_is_bg = color_code in self . ALL_BG_CODES final_color_code = color_code | ( current_fg if new_is_bg else current_bg ) # Set new code. self . _kernel32 . SetConsoleTextAttribute ( self . _stream_handle , final_color_code ) | Change the foreground and background colors for subsequently printed characters . | 290 | 11 |
18,596 | def write ( self , p_str ) : for segment in RE_SPLIT . split ( p_str ) : if not segment : # Empty string. p_str probably starts with colors so the first item is always ''. continue if not RE_SPLIT . match ( segment ) : # No color codes, print regular text. print ( segment , file = self . _original_stream , end = '' ) self . _original_stream . flush ( ) continue for color_code in ( int ( c ) for c in RE_NUMBER_SEARCH . findall ( segment ) [ 0 ] . split ( ';' ) ) : if color_code in self . COMPILED_CODES : self . colors = self . COMPILED_CODES [ color_code ] | Write to stream . | 171 | 4 |
18,597 | def prune_overridden ( ansi_string ) : multi_seqs = set ( p for p in RE_ANSI . findall ( ansi_string ) if ';' in p [ 1 ] ) # Sequences with multiple color codes. for escape , codes in multi_seqs : r_codes = list ( reversed ( codes . split ( ';' ) ) ) # Nuke everything before {/all}. try : r_codes = r_codes [ : r_codes . index ( '0' ) + 1 ] except ValueError : pass # Thin out groups. for group in CODE_GROUPS : for pos in reversed ( [ i for i , n in enumerate ( r_codes ) if n in group ] [ 1 : ] ) : r_codes . pop ( pos ) # Done. reduced_codes = ';' . join ( sorted ( r_codes , key = int ) ) if codes != reduced_codes : ansi_string = ansi_string . replace ( escape , '\033[' + reduced_codes + 'm' ) return ansi_string | Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes . | 236 | 18 |
18,598 | def parse_input ( tagged_string , disable_colors , keep_tags ) : codes = ANSICodeMapping ( tagged_string ) output_colors = getattr ( tagged_string , 'value_colors' , tagged_string ) # Convert: '{b}{red}' -> '\033[1m\033[31m' if not keep_tags : for tag , replacement in ( ( '{' + k + '}' , '' if v is None else '\033[%dm' % v ) for k , v in codes . items ( ) ) : output_colors = output_colors . replace ( tag , replacement ) # Strip colors. output_no_colors = RE_ANSI . sub ( '' , output_colors ) if disable_colors : return output_no_colors , output_no_colors # Combine: '\033[1m\033[31m' -> '\033[1;31m' while True : simplified = RE_COMBINE . sub ( r'\033[\1;\2m' , output_colors ) if simplified == output_colors : break output_colors = simplified # Prune: '\033[31;32;33;34;35m' -> '\033[35m' output_colors = prune_overridden ( output_colors ) # Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST' previous_escape = None segments = list ( ) for item in ( i for i in RE_SPLIT . split ( output_colors ) if i ) : if RE_SPLIT . match ( item ) : if item != previous_escape : segments . append ( item ) previous_escape = item else : segments . append ( item ) output_colors = '' . join ( segments ) return output_colors , output_no_colors | Perform the actual conversion of tags to ANSI escaped codes . | 447 | 13 |
18,599 | def build_color_index ( ansi_string ) : mapping = list ( ) color_offset = 0 for item in ( i for i in RE_SPLIT . split ( ansi_string ) if i ) : if RE_SPLIT . match ( item ) : color_offset += len ( item ) else : for _ in range ( len ( item ) ) : mapping . append ( color_offset ) color_offset += 1 return tuple ( mapping ) | Build an index between visible characters and a string with invisible color codes . | 99 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.