idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
18,600
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__ ) ) ) 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 .
18,601
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
18,602
def labels ( self ) : if self . _labels is None : self . _labels = self . instance . labels return self . _labels
Get list of labels from the target instance .
18,603
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 .
18,604
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 .
18,605
def _checkout ( self ) : cmd = [ "atomic" , "mount" , "--storage" , "ostree" , self . ref_image_name , self . mount_point ] 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
18,606
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 : 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
18,607
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 : req_func = self . _post return req_func ( 'login_with_google' , params , ** kwargs )
Login to Todoist using Google s oauth2 authentication .
18,608
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 .
18,609
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 .
18,610
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 : req_func = self . _get params [ 'resource_types' ] = resource_types return req_func ( 'sync' , params , ** kwargs )
Update and retrieve Todoist data .
18,611
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 .
18,612
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 .
18,613
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 .
18,614
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 .
18,615
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 .
18,616
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 .
18,617
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 .
18,618
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 .
18,619
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 .
18,620
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 .
18,621
def login_with_api_token ( api_token ) : response = API . sync ( api_token , '*' , '["user"]' ) _fail_if_contains_errors ( response ) user_json = response . json ( ) [ 'user' ] user_json [ 'api_token' ] = user_json [ 'token' ] return User ( user_json )
Login to Todoist using a user s api token .
18,622
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 .
18,623
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 .
18,624
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 .
18,625
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 .
18,626
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 .
18,627
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 .
18,628
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 .
18,629
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 .
18,630
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 : continue project = self . projects [ project_id ] self . tasks [ task_id ] = Task ( task_json , project )
Populate the user s tasks from a JSON encoded list .
18,631
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 : continue task = self . tasks [ task_id ] self . notes [ note_id ] = Note ( note_json , task )
Populate the user s notes from a JSON encoded list .
18,632
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 .
18,633
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 .
18,634
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 : continue task = self . tasks [ task_id ] self . reminders [ reminder_id ] = Reminder ( reminder_json , task )
Populate the user s reminders from a JSON encoded list .
18,635
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 .
18,636
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 .
18,637
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 .
18,638
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 .
18,639
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 .
18,640
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 .
18,641
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 .
18,642
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 .
18,643
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 .
18,644
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 .
18,645
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 .
18,646
def archive ( self ) : args = { 'id' : self . id } _perform_command ( self . owner , 'project_archive' , args ) self . is_archived = '1'
Archive the project .
18,647
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
18,648
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 .
18,649
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 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 .
18,650
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 .
18,651
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 .
18,652
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 .
18,653
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 .
18,654
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 .
18,655
def complete ( self ) : args = { 'id' : self . id } _perform_command ( self . project . owner , 'item_close' , args )
Mark the task complete .
18,656
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 .
18,657
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 .
18,658
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 .
18,659
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 .
18,660
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 .
18,661
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 .
18,662
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 .
18,663
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 .
18,664
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 .
18,665
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 .
18,666
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 .
18,667
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 .
18,668
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 .
18,669
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 .
18,670
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 .
18,671
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 .
18,672
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 .
18,673
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 .
18,674
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 .
18,675
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 .
18,676
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 .
18,677
def list_tags ( ) : 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 ] four_item_tuples = [ ( v [ 1 ] , k , v [ 2 ] , v [ 0 ] ) for k , v in reverse_dict . items ( ) ] def sorter ( four_item ) : if not four_item [ 2 ] : return four_item [ 3 ] - 200 if four_item [ 2 ] < 10 or four_item [ 0 ] . startswith ( 'auto' ) : return four_item [ 2 ] - 100 return four_item [ 2 ] four_item_tuples . sort ( key = sorter ) return four_item_tuples
List the available tags .
18,678
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 .
18,679
def get_console_info ( kernel32 , handle ) : csbi = ConsoleScreenBufferInfo ( ) lpcsbi = ctypes . byref ( csbi ) dword = ctypes . c_ulong ( ) lpdword = ctypes . byref ( dword ) if not kernel32 . GetConsoleScreenBufferInfo ( handle , lpcsbi ) or not kernel32 . GetConsoleMode ( handle , lpdword ) : raise ctypes . WinError ( ) 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 .
18,680
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 .
18,681
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 .
18,682
def colors ( self , color_code ) : if color_code is None : color_code = WINDOWS_CODES [ '/all' ] current_fg , current_bg = self . colors if color_code == WINDOWS_CODES [ '/fg' ] : final_color_code = self . default_fg | current_bg elif color_code == WINDOWS_CODES [ '/bg' ] : final_color_code = current_fg | self . default_bg elif color_code == WINDOWS_CODES [ '/all' ] : final_color_code = self . default_fg | self . default_bg elif color_code == WINDOWS_CODES [ 'bgblack' ] : final_color_code = current_fg 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 ) self . _kernel32 . SetConsoleTextAttribute ( self . _stream_handle , final_color_code )
Change the foreground and background colors for subsequently printed characters .
18,683
def write ( self , p_str ) : for segment in RE_SPLIT . split ( p_str ) : if not segment : continue if not RE_SPLIT . match ( segment ) : 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 .
18,684
def prune_overridden ( ansi_string ) : multi_seqs = set ( p for p in RE_ANSI . findall ( ansi_string ) if ';' in p [ 1 ] ) for escape , codes in multi_seqs : r_codes = list ( reversed ( codes . split ( ';' ) ) ) try : r_codes = r_codes [ : r_codes . index ( '0' ) + 1 ] except ValueError : pass 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 ) 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 .
18,685
def parse_input ( tagged_string , disable_colors , keep_tags ) : codes = ANSICodeMapping ( tagged_string ) output_colors = getattr ( tagged_string , 'value_colors' , tagged_string ) 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 ) output_no_colors = RE_ANSI . sub ( '' , output_colors ) if disable_colors : return output_no_colors , output_no_colors while True : simplified = RE_COMBINE . sub ( r'\033[\1;\2m' , output_colors ) if simplified == output_colors : break output_colors = simplified output_colors = prune_overridden ( output_colors ) 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 .
18,686
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 .
18,687
def find_char_color ( ansi_string , pos ) : result = list ( ) position = 0 for item in ( i for i in RE_SPLIT . split ( ansi_string ) if i ) : if RE_SPLIT . match ( item ) : result . append ( item ) if position is not None : position += len ( item ) elif position is not None : for char in item : if position == pos : result . append ( char ) position = None break position += 1 return '' . join ( result )
Determine what color a character is in the string .
18,688
def angular_distance_fast ( ra1 , dec1 , ra2 , dec2 ) : lon1 = np . deg2rad ( ra1 ) lat1 = np . deg2rad ( dec1 ) lon2 = np . deg2rad ( ra2 ) lat2 = np . deg2rad ( dec2 ) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np . sin ( dlat / 2.0 ) ** 2 + np . cos ( lat1 ) * np . cos ( lat2 ) * np . sin ( dlon / 2.0 ) ** 2 c = 2 * np . arcsin ( np . sqrt ( a ) ) return np . rad2deg ( c )
Compute angular distance using the Haversine formula . Use this one when you know you will never ask for points at their antipodes . If this is not the case use the angular_distance function which is slower but works also for antipodes .
18,689
def angular_distance ( ra1 , dec1 , ra2 , dec2 ) : lon1 = np . deg2rad ( ra1 ) lat1 = np . deg2rad ( dec1 ) lon2 = np . deg2rad ( ra2 ) lat2 = np . deg2rad ( dec2 ) sdlon = np . sin ( lon2 - lon1 ) cdlon = np . cos ( lon2 - lon1 ) slat1 = np . sin ( lat1 ) slat2 = np . sin ( lat2 ) clat1 = np . cos ( lat1 ) clat2 = np . cos ( lat2 ) num1 = clat2 * sdlon num2 = clat1 * slat2 - slat1 * clat2 * cdlon denominator = slat1 * slat2 + clat1 * clat2 * cdlon return np . rad2deg ( np . arctan2 ( np . sqrt ( num1 ** 2 + num2 ** 2 ) , denominator ) )
Returns the angular distance between two points two sets of points or a set of points and one point .
18,690
def memoize ( method ) : cache = method . cache = collections . OrderedDict ( ) _get = cache . get _popitem = cache . popitem @ functools . wraps ( method ) def memoizer ( instance , x , * args , ** kwargs ) : if not _WITH_MEMOIZATION or isinstance ( x , u . Quantity ) : return method ( instance , x , * args , ** kwargs ) unique_id = tuple ( float ( yy . value ) for yy in instance . parameters . values ( ) ) + ( x . size , x . min ( ) , x . max ( ) ) key = hash ( unique_id ) result = _get ( key ) if result is not None : return result else : result = method ( instance , x , * args , ** kwargs ) cache [ key ] = result if len ( cache ) > _CACHE_SIZE : [ _popitem ( False ) for i in range ( max ( _CACHE_SIZE // 2 , 1 ) ) ] return result memoizer . input_object = method return memoizer
A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls
18,691
def free_parameters ( self ) : self . _update_parameters ( ) free_parameters_dictionary = collections . OrderedDict ( ) for parameter_name , parameter in self . _parameters . iteritems ( ) : if parameter . free : free_parameters_dictionary [ parameter_name ] = parameter return free_parameters_dictionary
Get a dictionary with all the free parameters in this model
18,692
def set_free_parameters ( self , values ) : assert len ( values ) == len ( self . free_parameters ) for parameter , this_value in zip ( self . free_parameters . values ( ) , values ) : parameter . value = this_value
Set the free parameters in the model to the provided values .
18,693
def add_independent_variable ( self , variable ) : assert isinstance ( variable , IndependentVariable ) , "Variable must be an instance of IndependentVariable" if self . _has_child ( variable . name ) : self . _remove_child ( variable . name ) self . _add_child ( variable ) self . _independent_variables [ variable . name ] = variable
Add a global independent variable to this model such as time .
18,694
def remove_independent_variable ( self , variable_name ) : self . _remove_child ( variable_name ) self . _independent_variables . pop ( variable_name )
Remove an independent variable which was added with add_independent_variable
18,695
def add_external_parameter ( self , parameter ) : assert isinstance ( parameter , Parameter ) , "Variable must be an instance of IndependentVariable" if self . _has_child ( parameter . name ) : if isinstance ( self . _get_child ( parameter . name ) , Parameter ) : warnings . warn ( "External parameter %s already exist in the model. Overwriting it..." % parameter . name , RuntimeWarning ) self . _remove_child ( parameter . name ) self . _add_child ( parameter )
Add a parameter that comes from something other than a function to the model .
18,696
def unlink ( self , parameter ) : if not isinstance ( parameter , list ) : parameter_list = [ parameter ] else : parameter_list = list ( parameter ) for param in parameter_list : if param . has_auxiliary_variable ( ) : param . remove_auxiliary_variable ( ) else : with warnings . catch_warnings ( ) : warnings . simplefilter ( "always" , RuntimeWarning ) warnings . warn ( "Parameter %s has no link to be removed." % param . path , RuntimeWarning )
Sets free one or more parameters which have been linked previously
18,697
def display ( self , complete = False ) : self . _complete_display = bool ( complete ) super ( Model , self ) . display ( ) self . _complete_display = False
Display information about the point source .
18,698
def save ( self , output_file , overwrite = False ) : if os . path . exists ( output_file ) and overwrite is False : raise ModelFileExists ( "The file %s exists already. If you want to overwrite it, use the 'overwrite=True' " "options as 'model.save(\"%s\", overwrite=True)'. " % ( output_file , output_file ) ) else : data = self . to_dict_with_types ( ) try : representation = my_yaml . dump ( data , default_flow_style = False ) with open ( output_file , "w+" ) as f : f . write ( representation . replace ( "\n" , "\n\n" ) ) except IOError : raise CannotWriteModel ( os . path . dirname ( os . path . abspath ( output_file ) ) , "Could not write model file %s. Check your permissions to write or the " "report on the free space which follows: " % output_file )
Save the model to disk
18,699
def get_point_source_fluxes ( self , id , energies , tag = None ) : return self . _point_sources . values ( ) [ id ] ( energies , tag = tag )
Get the fluxes from the id - th point source