idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
55,500
def execute ( self ) : if self . args and self . argument ( 0 ) == "help" : self . error ( self . usage ( ) + "\n\n" + self . help ( ) ) return False return True
Execute the command . Intercepts the help subsubcommand to show the help text .
55,501
def argument ( self , p_number ) : try : return self . args [ p_number ] except IndexError as ie : raise InvalidCommandArgument from ie
Retrieves a value from the argument list at the given position .
55,502
def config ( p_path = None , p_overrides = None ) : if not config . instance or p_path is not None or p_overrides is not None : try : config . instance = _Config ( p_path , p_overrides ) except configparser . ParsingError as perr : raise ConfigError ( str ( perr ) ) from perr return config . instance
Retrieve the config instance .
55,503
def colors ( self , p_hint_possible = True ) : lookup = { 'false' : 0 , 'no' : 0 , '0' : 0 , '1' : 16 , 'true' : 16 , 'yes' : 16 , '16' : 16 , '256' : 256 , } try : forced = self . cp . get ( 'topydo' , 'force_colors' ) == '1' except ValueError : forced = self . defaults [ 'topydo' ] [ 'force_colors' ] == '1' try : colors = lookup [ self . cp . get ( 'topydo' , 'colors' ) . lower ( ) ] except ValueError : colors = lookup [ self . defaults [ 'topydo' ] [ 'colors' ] . lower ( ) ] except KeyError : colors = 16 if p_hint_possible else 0 return 0 if not forced and not p_hint_possible else colors
Returns 0 16 or 256 representing the number of colors that should be used in the output .
55,504
def hidden_tags ( self ) : hidden_tags = self . cp . get ( 'ls' , 'hide_tags' ) return [ ] if hidden_tags == '' else [ tag . strip ( ) for tag in hidden_tags . split ( ',' ) ]
Returns a list of tags to be hidden from the ls output .
55,505
def hidden_item_tags ( self ) : hidden_item_tags = self . cp . get ( 'ls' , 'hidden_item_tags' ) return [ ] if hidden_item_tags == '' else [ tag . strip ( ) for tag in hidden_item_tags . split ( ',' ) ]
Returns a list of tags which hide an item from the ls output .
55,506
def priority_color ( self , p_priority ) : def _str_to_dict ( p_string ) : pri_colors_dict = dict ( ) for pri_color in p_string . split ( ',' ) : pri , color = pri_color . split ( ':' ) pri_colors_dict [ pri ] = Color ( color ) return pri_colors_dict try : pri_colors_str = self . cp . get ( 'colorscheme' , 'priority_colors' ) if pri_colors_str == '' : pri_colors_dict = _str_to_dict ( 'A:-1,B:-1,C:-1' ) else : pri_colors_dict = _str_to_dict ( pri_colors_str ) except ValueError : pri_colors_dict = _str_to_dict ( self . defaults [ 'colorscheme' ] [ 'priority_colors' ] ) return pri_colors_dict [ p_priority ] if p_priority in pri_colors_dict else Color ( 'NEUTRAL' )
Returns a dict with priorities as keys and color numbers as value .
55,507
def aliases ( self ) : aliases = self . cp . items ( 'aliases' ) alias_dict = dict ( ) for alias , meaning in aliases : try : meaning = shlex . split ( meaning ) real_subcommand = meaning [ 0 ] alias_args = meaning [ 1 : ] alias_dict [ alias ] = ( real_subcommand , alias_args ) except ValueError as verr : alias_dict [ alias ] = str ( verr ) return alias_dict
Returns dict with aliases names as keys and pairs of actual subcommand and alias args as values .
55,508
def column_keymap ( self ) : keystates = set ( ) shortcuts = self . cp . items ( 'column_keymap' ) keymap_dict = dict ( shortcuts ) for combo , action in shortcuts : combo_as_list = re . split ( '(<[A-Z].+?>|.)' , combo ) [ 1 : : 2 ] if len ( combo_as_list ) > 1 : keystates |= set ( accumulate ( combo_as_list [ : - 1 ] ) ) if action in [ 'pri' , 'postpone' , 'postpone_s' ] : keystates . add ( combo ) if action == 'pri' : for c in ascii_lowercase : keymap_dict [ combo + c ] = 'cmd pri {} ' + c return ( keymap_dict , keystates )
Returns keymap and keystates used in column mode
55,509
def editor ( self ) : result = 'vi' if 'TOPYDO_EDITOR' in os . environ and os . environ [ 'TOPYDO_EDITOR' ] : result = os . environ [ 'TOPYDO_EDITOR' ] else : try : result = str ( self . cp . get ( 'edit' , 'editor' ) ) except configparser . NoOptionError : if 'EDITOR' in os . environ and os . environ [ 'EDITOR' ] : result = os . environ [ 'EDITOR' ] return shlex . split ( result )
Returns the editor to invoke . It returns a list with the command in the first position and its arguments in the remainder .
55,510
def execute ( self ) : if not super ( ) . execute ( ) : return False self . printer . add_filter ( PrettyPrinterNumbers ( self . todolist ) ) self . _process_flags ( ) if self . from_file : try : new_todos = self . get_todos_from_file ( ) for todo in new_todos : self . _add_todo ( todo ) except ( IOError , OSError ) : self . error ( 'File not found: ' + self . from_file ) else : if self . text : self . _add_todo ( self . text ) else : self . error ( self . usage ( ) )
Adds a todo item to the list .
55,511
def advance_recurring_todo ( p_todo , p_offset = None , p_strict = False ) : todo = Todo ( p_todo . source ( ) ) pattern = todo . tag_value ( 'rec' ) if not pattern : raise NoRecurrenceException ( ) elif pattern . startswith ( '+' ) : p_strict = True pattern = pattern [ 1 : ] if p_strict : offset = p_todo . due_date ( ) or p_offset or date . today ( ) else : offset = p_offset or date . today ( ) length = todo . length ( ) new_due = relative_date_to_date ( pattern , offset ) if not new_due : raise NoRecurrenceException ( ) todo . set_tag ( config ( ) . tag_due ( ) , new_due . isoformat ( ) ) if todo . start_date ( ) : new_start = new_due - timedelta ( length ) todo . set_tag ( config ( ) . tag_start ( ) , new_start . isoformat ( ) ) todo . set_creation_date ( date . today ( ) ) return todo
Given a Todo item return a new instance of a Todo item with the dates shifted according to the recurrence rule .
55,512
def _get_table_size ( p_alphabet , p_num ) : try : for width , size in sorted ( _TABLE_SIZES [ len ( p_alphabet ) ] . items ( ) ) : if p_num < size * 0.01 : return width , size except KeyError : pass raise _TableSizeException ( 'Could not find appropriate table size for given alphabet' )
Returns a prime number that is suitable for the hash table size . The size is dependent on the alphabet used and the number of items that need to be hashed . The table size is at least 100 times larger than the number of items to be hashed to avoid collisions .
55,513
def hash_list_values ( p_list , p_key = lambda i : i ) : def to_base ( p_alphabet , p_value ) : result = '' while p_value : p_value , i = divmod ( p_value , len ( p_alphabet ) ) result = p_alphabet [ i ] + result return result or p_alphabet [ 0 ] result = [ ] used = set ( ) alphabet = config ( ) . identifier_alphabet ( ) try : _ , size = _get_table_size ( alphabet , len ( p_list ) ) except _TableSizeException : alphabet = _DEFAULT_ALPHABET _ , size = _get_table_size ( alphabet , len ( p_list ) ) for item in p_list : raw_value = p_key ( item ) hasher = sha1 ( ) hasher . update ( raw_value . encode ( 'utf-8' ) ) hash_value = int ( hasher . hexdigest ( ) , 16 ) % size while hash_value in used : hash_value = ( hash_value + 1 ) % size used . add ( hash_value ) result . append ( ( item , to_base ( alphabet , hash_value ) ) ) return result
Calculates a unique value for each item in the list these can be used as identifiers .
55,514
def max_id_length ( p_num ) : try : alphabet = config ( ) . identifier_alphabet ( ) length , _ = _get_table_size ( alphabet , p_num ) except _TableSizeException : length , _ = _get_table_size ( _DEFAULT_ALPHABET , p_num ) return length
Returns the length of the IDs used given the number of items that are assigned an ID . Used for padding in lists .
55,515
def filter ( self , p_todo_str , p_todo ) : if config ( ) . colors ( ) : p_todo_str = TopydoString ( p_todo_str , p_todo ) priority_color = config ( ) . priority_color ( p_todo . priority ( ) ) colors = [ ( r'\B@(\S*\w)' , AbstractColor . CONTEXT ) , ( r'\B\+(\S*\w)' , AbstractColor . PROJECT ) , ( r'\b\S+:[^/\s]\S*\b' , AbstractColor . META ) , ( r'(^|\s)(\w+:){1}(//\S+)' , AbstractColor . LINK ) , ] p_todo_str . set_color ( 0 , priority_color ) for pattern , color in colors : for match in re . finditer ( pattern , p_todo_str . data ) : p_todo_str . set_color ( match . start ( ) , color ) p_todo_str . set_color ( match . end ( ) , priority_color ) p_todo_str . append ( '' , AbstractColor . NEUTRAL ) return p_todo_str
Applies the colors .
55,516
def get_filter_list ( p_expression ) : result = [ ] for arg in p_expression : is_negated = len ( arg ) > 1 and arg [ 0 ] == '-' arg = arg [ 1 : ] if is_negated else arg argfilter = None for match , _filter in MATCHES : if re . match ( match , arg ) : argfilter = _filter ( arg ) break if not argfilter : argfilter = GrepFilter ( arg ) if is_negated : argfilter = NegationFilter ( argfilter ) result . append ( argfilter ) return result
Returns a list of GrepFilters OrdinalTagFilters or NegationFilters based on the given filter expression .
55,517
def match ( self , p_todo ) : children = self . todolist . children ( p_todo ) uncompleted = [ todo for todo in children if not todo . is_completed ( ) ] return not uncompleted
Returns True when there are no children that are uncompleted yet .
55,518
def match ( self , p_todo ) : try : self . todos . index ( p_todo ) return True except ValueError : return False
Returns True when p_todo appears in the list of given todos .
55,519
def match ( self , p_todo ) : for my_tag in config ( ) . hidden_item_tags ( ) : my_values = p_todo . tag_values ( my_tag ) for my_value in my_values : if not my_value in ( 0 , '0' , False , 'False' ) : return False return True
Returns True when p_todo doesn t have a tag to mark it as hidden .
55,520
def compare_operands ( self , p_operand1 , p_operand2 ) : if self . operator == '<' : return p_operand1 < p_operand2 elif self . operator == '<=' : return p_operand1 <= p_operand2 elif self . operator == '=' : return p_operand1 == p_operand2 elif self . operator == '>=' : return p_operand1 >= p_operand2 elif self . operator == '>' : return p_operand1 > p_operand2 elif self . operator == '!' : return p_operand1 != p_operand2 return False
Returns True if conditional constructed from both operands and self . operator is valid . Returns False otherwise .
55,521
def match ( self , p_todo ) : operand1 = self . value operand2 = p_todo . priority ( ) or 'ZZ' return self . compare_operands ( operand1 , operand2 )
Performs a match on a priority in the todo .
55,522
def date_suggestions ( ) : days_of_week = { 0 : "Monday" , 1 : "Tuesday" , 2 : "Wednesday" , 3 : "Thursday" , 4 : "Friday" , 5 : "Saturday" , 6 : "Sunday" } dates = [ 'today' , 'tomorrow' , ] dow = datetime . date . today ( ) . weekday ( ) for i in range ( dow + 2 % 7 , dow + 7 ) : dates . append ( days_of_week [ i % 7 ] ) dates += [ "1w" , "2w" , "1m" , "2m" , "3m" , "1y" ] return dates
Returns a list of relative date that is presented to the user as auto complete suggestions .
55,523
def write ( p_file , p_string ) : if not config ( ) . colors ( p_file . isatty ( ) ) : p_string = escape_ansi ( p_string ) if p_string : p_file . write ( p_string + "\n" )
Write p_string to file p_file trailed by a newline character .
55,524
def lookup_color ( p_color ) : if not lookup_color . colors : lookup_color . colors [ AbstractColor . NEUTRAL ] = Color ( 'NEUTRAL' ) lookup_color . colors [ AbstractColor . PROJECT ] = config ( ) . project_color ( ) lookup_color . colors [ AbstractColor . CONTEXT ] = config ( ) . context_color ( ) lookup_color . colors [ AbstractColor . META ] = config ( ) . metadata_color ( ) lookup_color . colors [ AbstractColor . LINK ] = config ( ) . link_color ( ) try : return lookup_color . colors [ p_color ] except KeyError : return p_color
Converts an AbstractColor to a normal Color . Returns the Color itself when a normal color is passed .
55,525
def insert_ansi ( p_string ) : result = p_string . data for pos , color in sorted ( p_string . colors . items ( ) , reverse = True ) : color = lookup_color ( color ) result = result [ : pos ] + color . as_ansi ( ) + result [ pos : ] return result
Returns a string with color information at the right positions .
55,526
def version ( ) : from topydo . lib . Version import VERSION , LICENSE print ( "topydo {}\n" . format ( VERSION ) ) print ( LICENSE ) sys . exit ( 0 )
Print the current version and exit .
55,527
def _archive ( self ) : archive , archive_file = _retrieve_archive ( ) if self . backup : self . backup . add_archive ( archive ) if archive : from topydo . commands . ArchiveCommand import ArchiveCommand command = ArchiveCommand ( self . todolist , archive ) command . execute ( ) if archive . dirty : archive_file . write ( archive . print_todos ( ) )
Performs an archive action on the todolist .
55,528
def is_read_only ( p_command ) : read_only_commands = tuple ( cmd for cmd in ( 'revert' , ) + READ_ONLY_COMMANDS ) return p_command . name ( ) in read_only_commands
Returns True when the given command class is read - only .
55,529
def _post_execute ( self ) : if self . todolist . dirty : if self . do_archive and config ( ) . archive ( ) : self . _archive ( ) elif config ( ) . archive ( ) and self . backup : archive = _retrieve_archive ( ) [ 0 ] self . backup . add_archive ( archive ) self . _post_archive_action ( ) if config ( ) . keep_sorted ( ) : from topydo . commands . SortCommand import SortCommand self . _execute ( SortCommand , [ ] ) if self . backup : self . backup . save ( self . todolist ) self . todofile . write ( self . todolist . print_todos ( ) ) self . todolist . dirty = False self . backup = None
Should be called when executing the user requested command has been completed . It will do some maintenance and write out the final result to the todo . txt file .
55,530
def get_date ( self , p_tag ) : string = self . tag_value ( p_tag ) result = None try : result = date_string_to_date ( string ) if string else None except ValueError : pass return result
Given a date tag return a date object .
55,531
def is_active ( self ) : start = self . start_date ( ) return not self . is_completed ( ) and ( not start or start <= date . today ( ) )
Returns True when the start date is today or in the past and the task has not yet been completed .
55,532
def days_till_due ( self ) : due = self . due_date ( ) if due : diff = due - date . today ( ) return diff . days return 0
Returns the number of days till the due date . Returns a negative number of days when the due date is in the past . Returns 0 when the task has no due date .
55,533
def _handle_ls ( self ) : try : arg1 = self . argument ( 1 ) arg2 = self . argument ( 2 ) todos = [ ] if arg2 == 'to' or arg1 == 'before' : number = arg1 if arg2 == 'to' else arg2 todo = self . todolist . todo ( number ) todos = self . todolist . children ( todo ) elif arg1 in { 'to' , 'after' } : number = arg2 todo = self . todolist . todo ( number ) todos = self . todolist . parents ( todo ) else : raise InvalidCommandArgument sorter = Sorter ( config ( ) . sort_string ( ) ) instance_filter = Filter . InstanceFilter ( todos ) view = View ( sorter , [ instance_filter ] , self . todolist ) self . out ( self . printer . print_list ( view . todos ) ) except InvalidTodoException : self . error ( "Invalid todo number given." ) except InvalidCommandArgument : self . error ( self . usage ( ) )
Handles the ls subsubcommand .
55,534
def _handle_dot ( self ) : self . printer = DotPrinter ( self . todolist ) try : arg = self . argument ( 1 ) todo = self . todolist . todo ( arg ) arg = self . argument ( 1 ) todos = set ( [ self . todolist . todo ( arg ) ] ) todos |= set ( self . todolist . children ( todo ) ) todos |= set ( self . todolist . parents ( todo ) ) todos = sorted ( todos , key = lambda t : t . text ( ) ) self . out ( self . printer . print_list ( todos ) ) except InvalidTodoException : self . error ( "Invalid todo number given." ) except InvalidCommandArgument : self . error ( self . usage ( ) )
Handles the dot subsubcommand .
55,535
def todo ( self , p_identifier ) : result = None def todo_by_uid ( p_identifier ) : result = None if config ( ) . identifiers ( ) == 'text' : try : result = self . _id_todo_map [ p_identifier ] except KeyError : pass return result def todo_by_linenumber ( p_identifier ) : result = None if config ( ) . identifiers ( ) != 'text' : try : if re . match ( '[1-9]\d*' , p_identifier ) : raise TypeError except TypeError as te : try : result = self . _todos [ int ( p_identifier ) - 1 ] except ( ValueError , IndexError ) : raise InvalidTodoException from te return result def todo_by_regexp ( p_identifier ) : result = None candidates = Filter . GrepFilter ( p_identifier ) . filter ( self . _todos ) if len ( candidates ) == 1 : result = candidates [ 0 ] else : raise InvalidTodoException return result result = todo_by_uid ( p_identifier ) if not result : result = todo_by_linenumber ( p_identifier ) if not result : result = todo_by_regexp ( str ( p_identifier ) ) return result
The _todos list has the same order as in the backend store ( usually a todo . txt file . The user refers to the first task as number 1 so use index 0 etc .
55,536
def add ( self , p_src ) : todos = self . add_list ( [ p_src ] ) return todos [ 0 ] if len ( todos ) else None
Given a todo string parse it and put it to the end of the list .
55,537
def replace ( self , p_todos ) : self . erase ( ) self . add_todos ( p_todos ) self . dirty = True
Replaces whole todolist with todo objects supplied as p_todos .
55,538
def append ( self , p_todo , p_string ) : if len ( p_string ) > 0 : new_text = p_todo . source ( ) + ' ' + p_string p_todo . set_source_text ( new_text ) self . _update_todo_ids ( ) self . dirty = True
Appends a text to the todo specified by its number . The todo will be parsed again such that tags and projects in de appended string are processed .
55,539
def projects ( self ) : result = set ( ) for todo in self . _todos : projects = todo . projects ( ) result = result . union ( projects ) return result
Returns a set of all projects in this list .
55,540
def contexts ( self ) : result = set ( ) for todo in self . _todos : contexts = todo . contexts ( ) result = result . union ( contexts ) return result
Returns a set of all contexts in this list .
55,541
def linenumber ( self , p_todo ) : try : return self . _todos . index ( p_todo ) + 1 except ValueError as ex : raise InvalidTodoException from ex
Returns the line number of the todo item .
55,542
def uid ( self , p_todo ) : try : return self . _todo_id_map [ p_todo ] except KeyError as ex : raise InvalidTodoException from ex
Returns the unique text - based ID for a todo item .
55,543
def number ( self , p_todo ) : if config ( ) . identifiers ( ) == "text" : return self . uid ( p_todo ) else : return self . linenumber ( p_todo )
Returns the line number or text ID of a todo ( depends on the configuration .
55,544
def max_id_length ( self ) : if config ( ) . identifiers ( ) == "text" : return max_id_length ( len ( self . _todos ) ) else : try : return math . ceil ( math . log ( len ( self . _todos ) , 10 ) ) except ValueError : return 0
Returns the maximum length of a todo ID used for formatting purposes .
55,545
def ids ( self ) : if config ( ) . identifiers ( ) == 'text' : ids = self . _id_todo_map . keys ( ) else : ids = [ str ( i + 1 ) for i in range ( self . count ( ) ) ] return set ( ids )
Returns set with all todo IDs .
55,546
def prepare ( self , p_args ) : if self . _todo_ids : id_position = p_args . index ( '{}' ) if self . _multi : p_args [ id_position : id_position + 1 ] = self . _todo_ids self . _operations . append ( p_args ) else : for todo_id in self . _todo_ids : operation_args = p_args [ : ] operation_args [ id_position ] = todo_id self . _operations . append ( operation_args ) else : self . _operations . append ( p_args ) self . _create_label ( )
Prepares list of operations to execute based on p_args list of todo items contained in _todo_ids attribute and _subcommand attribute .
55,547
def execute ( self ) : last_operation = len ( self . _operations ) - 1 for i , operation in enumerate ( self . _operations ) : command = self . _cmd ( operation ) if command . execute ( ) is False : return False else : action = command . execute_post_archive_actions self . _post_archive_actions . append ( action ) if i == last_operation : return True
Executes each operation from _operations attribute .
55,548
def _add_months ( p_sourcedate , p_months ) : month = p_sourcedate . month - 1 + p_months year = p_sourcedate . year + month // 12 month = month % 12 + 1 day = min ( p_sourcedate . day , calendar . monthrange ( year , month ) [ 1 ] ) return date ( year , month , day )
Adds a number of months to the source date .
55,549
def _add_business_days ( p_sourcedate , p_bdays ) : result = p_sourcedate delta = 1 if p_bdays > 0 else - 1 while abs ( p_bdays ) > 0 : result += timedelta ( delta ) weekday = result . weekday ( ) if weekday >= 5 : continue p_bdays = p_bdays - 1 if delta > 0 else p_bdays + 1 return result
Adds a number of business days to the source date .
55,550
def _convert_weekday_pattern ( p_weekday ) : day_value = { 'mo' : 0 , 'tu' : 1 , 'we' : 2 , 'th' : 3 , 'fr' : 4 , 'sa' : 5 , 'su' : 6 } target_day_string = p_weekday [ : 2 ] . lower ( ) target_day = day_value [ target_day_string ] day = date . today ( ) . weekday ( ) shift = 7 - ( day - target_day ) % 7 return date . today ( ) + timedelta ( shift )
Converts a weekday name to an absolute date .
55,551
def relative_date_to_date ( p_date , p_offset = None ) : result = None p_date = p_date . lower ( ) p_offset = p_offset or date . today ( ) relative = re . match ( '(?P<length>-?[0-9]+)(?P<period>[dwmyb])$' , p_date , re . I ) monday = 'mo(n(day)?)?$' tuesday = 'tu(e(sday)?)?$' wednesday = 'we(d(nesday)?)?$' thursday = 'th(u(rsday)?)?$' friday = 'fr(i(day)?)?$' saturday = 'sa(t(urday)?)?$' sunday = 'su(n(day)?)?$' weekday = re . match ( '|' . join ( [ monday , tuesday , wednesday , thursday , friday , saturday , sunday ] ) , p_date ) if relative : length = relative . group ( 'length' ) period = relative . group ( 'period' ) result = _convert_pattern ( length , period , p_offset ) elif weekday : result = _convert_weekday_pattern ( weekday . group ( 0 ) ) elif re . match ( 'tod(ay)?$' , p_date ) : result = _convert_pattern ( '0' , 'd' ) elif re . match ( 'tom(orrow)?$' , p_date ) : result = _convert_pattern ( '1' , 'd' ) elif re . match ( 'yes(terday)?$' , p_date ) : result = _convert_pattern ( '-1' , 'd' ) return result
Transforms a relative date into a date object .
55,552
def filter ( self , p_todo_str , p_todo ) : return "|{:>3}| {}" . format ( self . todolist . number ( p_todo ) , p_todo_str )
Prepends the number to the todo string .
55,553
def postprocess_input_todo ( self , p_todo ) : def convert_date ( p_tag ) : value = p_todo . tag_value ( p_tag ) if value : dateobj = relative_date_to_date ( value ) if dateobj : p_todo . set_tag ( p_tag , dateobj . isoformat ( ) ) def add_dependencies ( p_tag ) : for value in p_todo . tag_values ( p_tag ) : try : dep = self . todolist . todo ( value ) if p_tag == 'after' : self . todolist . add_dependency ( p_todo , dep ) elif p_tag == 'before' or p_tag == 'partof' : self . todolist . add_dependency ( dep , p_todo ) elif p_tag . startswith ( 'parent' ) : for parent in self . todolist . parents ( dep ) : self . todolist . add_dependency ( parent , p_todo ) elif p_tag . startswith ( 'child' ) : for child in self . todolist . children ( dep ) : self . todolist . add_dependency ( p_todo , child ) except InvalidTodoException : pass p_todo . remove_tag ( p_tag , value ) convert_date ( config ( ) . tag_start ( ) ) convert_date ( config ( ) . tag_due ( ) ) keywords = [ 'after' , 'before' , 'child-of' , 'childof' , 'children-of' , 'childrenof' , 'parent-of' , 'parentof' , 'parents-of' , 'parentsof' , 'partof' , ] for keyword in keywords : add_dependencies ( keyword )
Post - processes a parsed todo when adding it to the list .
55,554
def columns ( p_alt_layout_path = None ) : def _get_column_dict ( p_cp , p_column ) : column_dict = dict ( ) filterexpr = p_cp . get ( p_column , 'filterexpr' ) try : title = p_cp . get ( p_column , 'title' ) except NoOptionError : title = filterexpr column_dict [ 'title' ] = title or 'Yet another column' column_dict [ 'filterexpr' ] = filterexpr column_dict [ 'sortexpr' ] = p_cp . get ( p_column , 'sortexpr' ) column_dict [ 'groupexpr' ] = p_cp . get ( p_column , 'groupexpr' ) column_dict [ 'show_all' ] = p_cp . getboolean ( p_column , 'show_all' ) return column_dict defaults = { 'filterexpr' : '' , 'sortexpr' : config ( ) . sort_string ( ) , 'groupexpr' : config ( ) . group_string ( ) , 'show_all' : '0' , } cp = RawConfigParser ( defaults , strict = False ) files = [ "topydo_columns.ini" , "topydo_columns.conf" , ".topydo_columns" , home_config_path ( '.topydo_columns' ) , home_config_path ( '.config/topydo/columns' ) , "/etc/topydo_columns.conf" , ] if p_alt_layout_path is not None : files . insert ( 0 , expanduser ( p_alt_layout_path ) ) for filename in files : if cp . read ( filename ) : break column_list = [ ] for column in cp . sections ( ) : column_list . append ( _get_column_dict ( cp , column ) ) return column_list
Returns list with complete column configuration dicts .
55,555
def _active_todos ( self ) : return [ todo for todo in self . todolist . todos ( ) if not self . _uncompleted_children ( todo ) and todo . is_active ( ) ]
Returns a list of active todos taking uncompleted subtodos into account .
55,556
def _decompress_into_buffer ( self , out_buffer ) : zresult = lib . ZSTD_decompressStream ( self . _decompressor . _dctx , out_buffer , self . _in_buffer ) if self . _in_buffer . pos == self . _in_buffer . size : self . _in_buffer . src = ffi . NULL self . _in_buffer . pos = 0 self . _in_buffer . size = 0 self . _source_buffer = None if not hasattr ( self . _source , 'read' ) : self . _finished_input = True if lib . ZSTD_isError ( zresult ) : raise ZstdError ( 'zstd decompress error: %s' % _zstd_error ( zresult ) ) return ( out_buffer . pos and ( out_buffer . pos == out_buffer . size or zresult == 0 and not self . _read_across_frames ) )
Decompress available input into an output buffer .
55,557
def get_c_extension ( support_legacy = False , system_zstd = False , name = 'zstd' , warnings_as_errors = False , root = None ) : actual_root = os . path . abspath ( os . path . dirname ( __file__ ) ) root = root or actual_root sources = set ( [ os . path . join ( actual_root , p ) for p in ext_sources ] ) if not system_zstd : sources . update ( [ os . path . join ( actual_root , p ) for p in zstd_sources ] ) if support_legacy : sources . update ( [ os . path . join ( actual_root , p ) for p in zstd_sources_legacy ] ) sources = list ( sources ) include_dirs = set ( [ os . path . join ( actual_root , d ) for d in ext_includes ] ) if not system_zstd : include_dirs . update ( [ os . path . join ( actual_root , d ) for d in zstd_includes ] ) if support_legacy : include_dirs . update ( [ os . path . join ( actual_root , d ) for d in zstd_includes_legacy ] ) include_dirs = list ( include_dirs ) depends = [ os . path . join ( actual_root , p ) for p in zstd_depends ] compiler = distutils . ccompiler . new_compiler ( ) if hasattr ( compiler , 'initialize' ) : compiler . initialize ( ) if compiler . compiler_type == 'unix' : compiler_type = 'unix' elif compiler . compiler_type == 'msvc' : compiler_type = 'msvc' elif compiler . compiler_type == 'mingw32' : compiler_type = 'mingw32' else : raise Exception ( 'unhandled compiler type: %s' % compiler . compiler_type ) extra_args = [ '-DZSTD_MULTITHREAD' ] if not system_zstd : extra_args . append ( '-DZSTDLIB_VISIBILITY=' ) extra_args . append ( '-DZDICTLIB_VISIBILITY=' ) extra_args . append ( '-DZSTDERRORLIB_VISIBILITY=' ) if compiler_type == 'unix' : extra_args . append ( '-fvisibility=hidden' ) if not system_zstd and support_legacy : extra_args . append ( '-DZSTD_LEGACY_SUPPORT=1' ) if warnings_as_errors : if compiler_type in ( 'unix' , 'mingw32' ) : extra_args . append ( '-Werror' ) elif compiler_type == 'msvc' : extra_args . append ( '/WX' ) else : assert False libraries = [ 'zstd' ] if system_zstd else [ ] sources = [ os . path . relpath ( p , root ) for p in sources ] include_dirs = [ os . path . relpath ( p , root ) for p in include_dirs ] depends = [ os . path . relpath ( p , root ) for p in depends ] return Extension ( name , sources , include_dirs = include_dirs , depends = depends , extra_compile_args = extra_args , libraries = libraries )
Obtain a distutils . extension . Extension for the C extension .
55,558
def timezone ( self ) : if not self . _timezone_group and not self . _timezone_location : return None if self . _timezone_location != "" : return "%s/%s" % ( self . _timezone_group , self . _timezone_location ) else : return self . _timezone_group
The name of the time zone for the location .
55,559
def tz ( self ) : if self . timezone is None : return None try : tz = pytz . timezone ( self . timezone ) return tz except pytz . UnknownTimeZoneError : raise AstralError ( "Unknown timezone '%s'" % self . timezone )
Time zone information .
55,560
def sun ( self , date = None , local = True , use_elevation = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) elevation = self . elevation if use_elevation else 0 sun = self . astral . sun_utc ( date , self . latitude , self . longitude , observer_elevation = elevation ) if local : for key , dt in sun . items ( ) : sun [ key ] = dt . astimezone ( self . tz ) return sun
Returns dawn sunrise noon sunset and dusk as a dictionary .
55,561
def sunrise ( self , date = None , local = True , use_elevation = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) elevation = self . elevation if use_elevation else 0 sunrise = self . astral . sunrise_utc ( date , self . latitude , self . longitude , elevation ) if local : return sunrise . astimezone ( self . tz ) else : return sunrise
Return sunrise time .
55,562
def time_at_elevation ( self , elevation , direction = SUN_RISING , date = None , local = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) if elevation > 90.0 : elevation = 180.0 - elevation direction = SUN_SETTING time_ = self . astral . time_at_elevation_utc ( elevation , direction , date , self . latitude , self . longitude ) if local : return time_ . astimezone ( self . tz ) else : return time_
Calculate the time when the sun is at the specified elevation .
55,563
def blue_hour ( self , direction = SUN_RISING , date = None , local = True , use_elevation = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) elevation = self . elevation if use_elevation else 0 start , end = self . astral . blue_hour_utc ( direction , date , self . latitude , self . longitude , elevation ) if local : start = start . astimezone ( self . tz ) end = end . astimezone ( self . tz ) return start , end
Returns the start and end times of the Blue Hour when the sun is traversing in the specified direction .
55,564
def moon_phase ( self , date = None , rtype = int ) : if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) return self . astral . moon_phase ( date , rtype )
Calculates the moon phase for a specific date .
55,565
def add_locations ( self , locations ) : if isinstance ( locations , ( str , ustr ) ) : self . _add_from_str ( locations ) elif isinstance ( locations , ( list , tuple ) ) : self . _add_from_list ( locations )
Add extra locations to AstralGeocoder .
55,566
def _add_from_str ( self , s ) : if sys . version_info [ 0 ] < 3 and isinstance ( s , str ) : s = s . decode ( 'utf-8' ) for line in s . split ( "\n" ) : self . _parse_line ( line )
Add locations from a string
55,567
def _add_from_list ( self , l ) : for item in l : if isinstance ( item , ( str , ustr ) ) : self . _add_from_str ( item ) elif isinstance ( item , ( list , tuple ) ) : location = Location ( item ) self . _add_location ( location )
Add locations from a list of either strings or lists or tuples .
55,568
def _get_geocoding ( self , key , location ) : url = self . _location_query_base % quote_plus ( key ) if self . api_key : url += "&key=%s" % self . api_key data = self . _read_from_url ( url ) response = json . loads ( data ) if response [ "status" ] == "OK" : formatted_address = response [ "results" ] [ 0 ] [ "formatted_address" ] pos = formatted_address . find ( "," ) if pos == - 1 : location . name = formatted_address location . region = "" else : location . name = formatted_address [ : pos ] . strip ( ) location . region = formatted_address [ pos + 1 : ] . strip ( ) geo_location = response [ "results" ] [ 0 ] [ "geometry" ] [ "location" ] location . latitude = float ( geo_location [ "lat" ] ) location . longitude = float ( geo_location [ "lng" ] ) else : raise AstralError ( "GoogleGeocoder: Unable to locate %s. Server Response=%s" % ( key , response [ "status" ] ) )
Lookup the Google geocoding API information for key
55,569
def _get_timezone ( self , location ) : url = self . _timezone_query_base % ( location . latitude , location . longitude , int ( time ( ) ) , ) if self . api_key != "" : url += "&key=%s" % self . api_key data = self . _read_from_url ( url ) response = json . loads ( data ) if response [ "status" ] == "OK" : location . timezone = response [ "timeZoneId" ] else : location . timezone = "UTC"
Query the timezone information with the latitude and longitude of the specified location .
55,570
def _get_elevation ( self , location ) : url = self . _elevation_query_base % ( location . latitude , location . longitude ) if self . api_key != "" : url += "&key=%s" % self . api_key data = self . _read_from_url ( url ) response = json . loads ( data ) if response [ "status" ] == "OK" : location . elevation = int ( float ( response [ "results" ] [ 0 ] [ "elevation" ] ) ) else : location . elevation = 0
Query the elevation information with the latitude and longitude of the specified location .
55,571
def sun_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : dawn = self . dawn_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) sunrise = self . sunrise_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) noon = self . solar_noon_utc ( date , longitude ) sunset = self . sunset_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) dusk = self . dusk_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) return { "dawn" : dawn , "sunrise" : sunrise , "noon" : noon , "sunset" : sunset , "dusk" : dusk , }
Calculate all the info for the sun at once . All times are returned in the UTC timezone .
55,572
def dawn_utc ( self , date , latitude , longitude , depression = 0 , observer_elevation = 0 ) : if depression == 0 : depression = self . _depression depression += 90 try : return self . _calc_time ( depression , SUN_RISING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches %d degrees below the horizon, " "at this location." ) % ( depression - 90 ) ) else : raise
Calculate dawn time in the UTC timezone .
55,573
def sunrise_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : try : return self . _calc_time ( 90 + 0.833 , SUN_RISING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches the horizon on this day, " "at this location." ) ) else : raise
Calculate sunrise time in the UTC timezone .
55,574
def solar_noon_utc ( self , date , longitude ) : jc = self . _jday_to_jcentury ( self . _julianday ( date ) ) eqtime = self . _eq_of_time ( jc ) timeUTC = ( 720.0 - ( 4 * longitude ) - eqtime ) / 60.0 hour = int ( timeUTC ) minute = int ( ( timeUTC - hour ) * 60 ) second = int ( ( ( ( timeUTC - hour ) * 60 ) - minute ) * 60 ) if second > 59 : second -= 60 minute += 1 elif second < 0 : second += 60 minute -= 1 if minute > 59 : minute -= 60 hour += 1 elif minute < 0 : minute += 60 hour -= 1 if hour > 23 : hour -= 24 date += datetime . timedelta ( days = 1 ) elif hour < 0 : hour += 24 date -= datetime . timedelta ( days = 1 ) noon = datetime . datetime ( date . year , date . month , date . day , hour , minute , second ) noon = pytz . UTC . localize ( noon ) return noon
Calculate solar noon time in the UTC timezone .
55,575
def sunset_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : try : return self . _calc_time ( 90 + 0.833 , SUN_SETTING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches the horizon on this day, " "at this location." ) ) else : raise
Calculate sunset time in the UTC timezone .
55,576
def dusk_utc ( self , date , latitude , longitude , depression = 0 , observer_elevation = 0 ) : if depression == 0 : depression = self . _depression depression += 90 try : return self . _calc_time ( depression , SUN_SETTING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches %d degrees below the horizon, " "at this location." ) % ( depression - 90 ) ) else : raise
Calculate dusk time in the UTC timezone .
55,577
def solar_midnight_utc ( self , date , longitude ) : julianday = self . _julianday ( date ) newt = self . _jday_to_jcentury ( julianday + 0.5 + - longitude / 360.0 ) eqtime = self . _eq_of_time ( newt ) timeUTC = ( - longitude * 4.0 ) - eqtime timeUTC = timeUTC / 60.0 hour = int ( timeUTC ) minute = int ( ( timeUTC - hour ) * 60 ) second = int ( ( ( ( timeUTC - hour ) * 60 ) - minute ) * 60 ) if second > 59 : second -= 60 minute += 1 elif second < 0 : second += 60 minute -= 1 if minute > 59 : minute -= 60 hour += 1 elif minute < 0 : minute += 60 hour -= 1 if hour < 0 : hour += 24 date -= datetime . timedelta ( days = 1 ) midnight = datetime . datetime ( date . year , date . month , date . day , hour , minute , second ) midnight = pytz . UTC . localize ( midnight ) return midnight
Calculate solar midnight time in the UTC timezone .
55,578
def daylight_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : start = self . sunrise_utc ( date , latitude , longitude , observer_elevation ) end = self . sunset_utc ( date , latitude , longitude , observer_elevation ) return start , end
Calculate daylight start and end times in the UTC timezone .
55,579
def night_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : start = self . dusk_utc ( date , latitude , longitude , 18 , observer_elevation ) tomorrow = date + datetime . timedelta ( days = 1 ) end = self . dawn_utc ( tomorrow , latitude , longitude , 18 , observer_elevation ) return start , end
Calculate night start and end times in the UTC timezone .
55,580
def blue_hour_utc ( self , direction , date , latitude , longitude , observer_elevation = 0 ) : if date is None : date = datetime . date . today ( ) start = self . time_at_elevation_utc ( - 6 , direction , date , latitude , longitude , observer_elevation ) end = self . time_at_elevation_utc ( - 4 , direction , date , latitude , longitude , observer_elevation ) if direction == SUN_RISING : return start , end else : return end , start
Returns the start and end times of the Blue Hour in the UTC timezone when the sun is traversing in the specified direction .
55,581
def time_at_elevation_utc ( self , elevation , direction , date , latitude , longitude , observer_elevation = 0 ) : if elevation > 90.0 : elevation = 180.0 - elevation direction = SUN_SETTING depression = 90 - elevation try : return self . _calc_time ( depression , direction , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches an elevation of %d degrees" "at this location." ) % elevation ) else : raise
Calculate the time in the UTC timezone when the sun is at the specified elevation on the specified date .
55,582
def solar_azimuth ( self , dateandtime , latitude , longitude ) : if latitude > 89.8 : latitude = 89.8 if latitude < - 89.8 : latitude = - 89.8 if dateandtime . tzinfo is None : zone = 0 utc_datetime = dateandtime else : zone = - dateandtime . utcoffset ( ) . total_seconds ( ) / 3600.0 utc_datetime = dateandtime . astimezone ( pytz . utc ) timenow = ( utc_datetime . hour + ( utc_datetime . minute / 60.0 ) + ( utc_datetime . second / 3600.0 ) ) JD = self . _julianday ( dateandtime ) t = self . _jday_to_jcentury ( JD + timenow / 24.0 ) theta = self . _sun_declination ( t ) eqtime = self . _eq_of_time ( t ) solarDec = theta solarTimeFix = eqtime - ( 4.0 * - longitude ) + ( 60 * zone ) trueSolarTime = ( dateandtime . hour * 60.0 + dateandtime . minute + dateandtime . second / 60.0 + solarTimeFix ) while trueSolarTime > 1440 : trueSolarTime = trueSolarTime - 1440 hourangle = trueSolarTime / 4.0 - 180.0 if hourangle < - 180 : hourangle = hourangle + 360.0 harad = radians ( hourangle ) csz = sin ( radians ( latitude ) ) * sin ( radians ( solarDec ) ) + cos ( radians ( latitude ) ) * cos ( radians ( solarDec ) ) * cos ( harad ) if csz > 1.0 : csz = 1.0 elif csz < - 1.0 : csz = - 1.0 zenith = degrees ( acos ( csz ) ) azDenom = cos ( radians ( latitude ) ) * sin ( radians ( zenith ) ) if abs ( azDenom ) > 0.001 : azRad = ( ( sin ( radians ( latitude ) ) * cos ( radians ( zenith ) ) ) - sin ( radians ( solarDec ) ) ) / azDenom if abs ( azRad ) > 1.0 : if azRad < 0 : azRad = - 1.0 else : azRad = 1.0 azimuth = 180.0 - degrees ( acos ( azRad ) ) if hourangle > 0.0 : azimuth = - azimuth else : if latitude > 0.0 : azimuth = 180.0 else : azimuth = 0.0 if azimuth < 0.0 : azimuth = azimuth + 360.0 return azimuth
Calculate the azimuth angle of the sun .
55,583
def solar_zenith ( self , dateandtime , latitude , longitude ) : return 90.0 - self . solar_elevation ( dateandtime , latitude , longitude )
Calculates the solar zenith angle .
55,584
def moon_phase ( self , date , rtype = int ) : if rtype != float and rtype != int : rtype = int moon = self . _moon_phase_asfloat ( date ) if moon >= 28.0 : moon -= 28.0 moon = rtype ( moon ) return moon
Calculates the phase of the moon on the specified date .
55,585
def rahukaalam_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : if date is None : date = datetime . date . today ( ) sunrise = self . sunrise_utc ( date , latitude , longitude , observer_elevation ) sunset = self . sunset_utc ( date , latitude , longitude , observer_elevation ) octant_duration = datetime . timedelta ( seconds = ( sunset - sunrise ) . seconds / 8 ) octant_index = [ 1 , 6 , 4 , 5 , 3 , 2 , 7 ] weekday = date . weekday ( ) octant = octant_index [ weekday ] start = sunrise + ( octant_duration * octant ) end = start + octant_duration return start , end
Calculate ruhakaalam times in the UTC timezone .
55,586
def _depression_adjustment ( self , elevation ) : if elevation <= 0 : return 0 r = 6356900 a1 = r h1 = r + elevation theta1 = acos ( a1 / h1 ) a2 = r * sin ( theta1 ) b2 = r - ( r * cos ( theta1 ) ) h2 = sqrt ( pow ( a2 , 2 ) + pow ( b2 , 2 ) ) alpha = acos ( a2 / h2 ) return degrees ( alpha )
Calculate the extra degrees of depression due to the increase in elevation .
55,587
def callback ( status , message , job , result , exception , stacktrace ) : assert status in [ 'invalid' , 'success' , 'timeout' , 'failure' ] assert isinstance ( message , Message ) if status == 'invalid' : assert job is None assert result is None assert exception is None assert stacktrace is None if status == 'success' : assert isinstance ( job , Job ) assert exception is None assert stacktrace is None elif status == 'timeout' : assert isinstance ( job , Job ) assert result is None assert exception is None assert stacktrace is None elif status == 'failure' : assert isinstance ( job , Job ) assert result is None assert exception is not None assert stacktrace is not None
Example callback function .
55,588
def _execute_callback ( self , status , message , job , res , err , stacktrace ) : if self . _callback is not None : try : self . _logger . info ( 'Executing callback ...' ) self . _callback ( status , message , job , res , err , stacktrace ) except Exception as e : self . _logger . exception ( 'Callback raised an exception: {}' . format ( e ) )
Execute the callback .
55,589
def _process_message ( self , msg ) : self . _logger . info ( 'Processing Message(topic={}, partition={}, offset={}) ...' . format ( msg . topic , msg . partition , msg . offset ) ) try : job = self . _deserializer ( msg . value ) job_repr = get_call_repr ( job . func , * job . args , ** job . kwargs ) except Exception as err : self . _logger . exception ( 'Job was invalid: {}' . format ( err ) ) self . _execute_callback ( 'invalid' , msg , None , None , None , None ) else : self . _logger . info ( 'Executing job {}: {}' . format ( job . id , job_repr ) ) if job . timeout : timer = threading . Timer ( job . timeout , _thread . interrupt_main ) timer . start ( ) else : timer = None try : res = job . func ( * job . args , ** job . kwargs ) except KeyboardInterrupt : self . _logger . error ( 'Job {} timed out or was interrupted' . format ( job . id ) ) self . _execute_callback ( 'timeout' , msg , job , None , None , None ) except Exception as err : self . _logger . exception ( 'Job {} raised an exception:' . format ( job . id ) ) tb = traceback . format_exc ( ) self . _execute_callback ( 'failure' , msg , job , None , err , tb ) else : self . _logger . info ( 'Job {} returned: {}' . format ( job . id , res ) ) self . _execute_callback ( 'success' , msg , job , res , None , None ) finally : if timer is not None : timer . cancel ( )
De - serialize the message and execute the job .
55,590
def start ( self , max_messages = math . inf , commit_offsets = True ) : self . _logger . info ( 'Starting {} ...' . format ( self ) ) self . _consumer . unsubscribe ( ) self . _consumer . subscribe ( [ self . topic ] ) messages_processed = 0 while messages_processed < max_messages : record = next ( self . _consumer ) message = Message ( topic = record . topic , partition = record . partition , offset = record . offset , key = record . key , value = record . value ) self . _process_message ( message ) if commit_offsets : self . _consumer . commit ( ) messages_processed += 1 return messages_processed
Start processing Kafka messages and executing jobs .
55,591
def get_call_repr ( func , * args , ** kwargs ) : if ismethod ( func ) or isfunction ( func ) or isbuiltin ( func ) : func_repr = '{}.{}' . format ( func . __module__ , func . __qualname__ ) elif not isclass ( func ) and hasattr ( func , '__call__' ) : func_repr = '{}.{}' . format ( func . __module__ , func . __class__ . __name__ ) else : func_repr = repr ( func ) args_reprs = [ repr ( arg ) for arg in args ] kwargs_reprs = [ k + '=' + repr ( v ) for k , v in sorted ( kwargs . items ( ) ) ] return '{}({})' . format ( func_repr , ', ' . join ( args_reprs + kwargs_reprs ) )
Return the string representation of the function call .
55,592
def using ( self , timeout = None , key = None , partition = None ) : return EnqueueSpec ( topic = self . _topic , producer = self . _producer , serializer = self . _serializer , logger = self . _logger , timeout = timeout or self . _timeout , key = key , partition = partition )
Set enqueue specifications such as timeout key and partition .
55,593
def send ( instructions , printer_identifier = None , backend_identifier = None , blocking = True ) : status = { 'instructions_sent' : True , 'outcome' : 'unknown' , 'printer_state' : None , 'did_print' : False , 'ready_for_next_job' : False , } selected_backend = None if backend_identifier : selected_backend = backend_identifier else : try : selected_backend = guess_backend ( printer_identifier ) except : logger . info ( "No backend stated. Selecting the default linux_kernel backend." ) selected_backend = 'linux_kernel' be = backend_factory ( selected_backend ) list_available_devices = be [ 'list_available_devices' ] BrotherQLBackend = be [ 'backend_class' ] printer = BrotherQLBackend ( printer_identifier ) start = time . time ( ) logger . info ( 'Sending instructions to the printer. Total: %d bytes.' , len ( instructions ) ) printer . write ( instructions ) status [ 'outcome' ] = 'sent' if not blocking : return status if selected_backend == 'network' : return status while time . time ( ) - start < 10 : data = printer . read ( ) if not data : time . sleep ( 0.005 ) continue try : result = interpret_response ( data ) except ValueError : logger . error ( "TIME %.3f - Couln't understand response: %s" , time . time ( ) - start , data ) continue status [ 'printer_state' ] = result logger . debug ( 'TIME %.3f - result: %s' , time . time ( ) - start , result ) if result [ 'errors' ] : logger . error ( 'Errors occured: %s' , result [ 'errors' ] ) status [ 'outcome' ] = 'error' break if result [ 'status_type' ] == 'Printing completed' : status [ 'did_print' ] = True status [ 'outcome' ] = 'printed' if result [ 'status_type' ] == 'Phase change' and result [ 'phase_type' ] == 'Waiting to receive' : status [ 'ready_for_next_job' ] = True if status [ 'did_print' ] and status [ 'ready_for_next_job' ] : break if not status [ 'did_print' ] : logger . warning ( "'printing completed' status not received." ) if not status [ 'ready_for_next_job' ] : logger . warning ( "'waiting to receive' status not received." ) if ( not status [ 'did_print' ] ) or ( not status [ 'ready_for_next_job' ] ) : logger . warning ( 'Printing potentially not successful?' ) if status [ 'did_print' ] and status [ 'ready_for_next_job' ] : logger . info ( "Printing was successful. Waiting for the next job." ) return status
Send instruction bytes to a printer .
55,594
def merge_specific_instructions ( chunks , join_preamble = True , join_raster = True ) : new_instructions = [ ] last_opcode = None instruction_buffer = b'' for instruction in chunks : opcode = match_opcode ( instruction ) if join_preamble and OPCODES [ opcode ] [ 0 ] == 'preamble' and last_opcode == 'preamble' : instruction_buffer += instruction elif join_raster and 'raster' in OPCODES [ opcode ] [ 0 ] and 'raster' in last_opcode : instruction_buffer += instruction else : if instruction_buffer : new_instructions . append ( instruction_buffer ) instruction_buffer = instruction last_opcode = OPCODES [ opcode ] [ 0 ] if instruction_buffer : new_instructions . append ( instruction_buffer ) return new_instructions
Process a list of instructions by merging subsequent instuctions with identical opcodes into large instructions .
55,595
def cli ( ctx , * args , ** kwargs ) : backend = kwargs . get ( 'backend' , None ) model = kwargs . get ( 'model' , None ) printer = kwargs . get ( 'printer' , None ) debug = kwargs . get ( 'debug' ) ctx . meta [ 'MODEL' ] = model ctx . meta [ 'BACKEND' ] = backend ctx . meta [ 'PRINTER' ] = printer logging . basicConfig ( level = 'DEBUG' if debug else 'INFO' )
Command line interface for the brother_ql Python package .
55,596
def env ( ctx , * args , ** kwargs ) : import sys , platform , os , shutil from pkg_resources import get_distribution , working_set print ( "\n##################\n" ) print ( "Information about the running environment of brother_ql." ) print ( "(Please provide this information when reporting any issue.)\n" ) print ( "About the computer:" ) for attr in ( 'platform' , 'processor' , 'release' , 'system' , 'machine' , 'architecture' ) : print ( ' * ' + attr . title ( ) + ':' , getattr ( platform , attr ) ( ) ) print ( "About the installed Python version:" ) py_version = str ( sys . version ) . replace ( '\n' , ' ' ) print ( " *" , py_version ) print ( "About the brother_ql package:" ) pkg = get_distribution ( 'brother_ql' ) print ( " * package location:" , pkg . location ) print ( " * package version: " , pkg . version ) try : cli_loc = shutil . which ( 'brother_ql' ) except : cli_loc = 'unknown' print ( " * brother_ql CLI path:" , cli_loc ) print ( "About the requirements of brother_ql:" ) fmt = " {req:14s} | {spec:10s} | {ins_vers:17s}" print ( fmt . format ( req = 'requirement' , spec = 'requested' , ins_vers = 'installed version' ) ) print ( fmt . format ( req = '-' * 14 , spec = '-' * 10 , ins_vers = '-' * 17 ) ) requirements = list ( pkg . requires ( ) ) requirements . sort ( key = lambda x : x . project_name ) for req in requirements : proj = req . project_name req_pkg = get_distribution ( proj ) spec = ' ' . join ( req . specs [ 0 ] ) if req . specs else 'any' print ( fmt . format ( req = proj , spec = spec , ins_vers = req_pkg . version ) ) print ( "\n##################\n" )
print debug info about running environment
55,597
def print_cmd ( ctx , * args , ** kwargs ) : backend = ctx . meta . get ( 'BACKEND' , 'pyusb' ) model = ctx . meta . get ( 'MODEL' ) printer = ctx . meta . get ( 'PRINTER' ) from brother_ql . conversion import convert from brother_ql . backends . helpers import send from brother_ql . raster import BrotherQLRaster qlr = BrotherQLRaster ( model ) qlr . exception_on_warning = True kwargs [ 'cut' ] = not kwargs [ 'no_cut' ] del kwargs [ 'no_cut' ] instructions = convert ( qlr = qlr , ** kwargs ) send ( instructions = instructions , printer_identifier = printer , backend_identifier = backend , blocking = True )
Print a label of the provided IMAGE .
55,598
def list_available_devices ( ) : class find_class ( object ) : def __init__ ( self , class_ ) : self . _class = class_ def __call__ ( self , device ) : if device . bDeviceClass == self . _class : return True for cfg in device : intf = usb . util . find_descriptor ( cfg , bInterfaceClass = self . _class ) if intf is not None : return True return False printers = usb . core . find ( find_all = 1 , custom_match = find_class ( 7 ) , idVendor = 0x04f9 ) def identifier ( dev ) : try : serial = usb . util . get_string ( dev , 256 , dev . iSerialNumber ) return 'usb://0x{:04x}:0x{:04x}_{}' . format ( dev . idVendor , dev . idProduct , serial ) except : return 'usb://0x{:04x}:0x{:04x}' . format ( dev . idVendor , dev . idProduct ) return [ { 'identifier' : identifier ( printer ) , 'instance' : printer } for printer in printers ]
List all available devices for the respective backend
55,599
def _populate_label_legacy_structures ( ) : global DIE_CUT_LABEL , ENDLESS_LABEL , ROUND_DIE_CUT_LABEL global label_sizes , label_type_specs from brother_ql . labels import FormFactor DIE_CUT_LABEL = FormFactor . DIE_CUT ENDLESS_LABEL = FormFactor . ENDLESS ROUND_DIE_CUT_LABEL = FormFactor . ROUND_DIE_CUT from brother_ql . labels import LabelsManager lm = LabelsManager ( ) label_sizes = list ( lm . iter_identifiers ( ) ) for label in lm . iter_elements ( ) : l = { } l [ 'name' ] = label . name l [ 'kind' ] = label . form_factor l [ 'color' ] = label . color l [ 'tape_size' ] = label . tape_size l [ 'dots_total' ] = label . dots_total l [ 'dots_printable' ] = label . dots_printable l [ 'right_margin_dots' ] = label . offset_r l [ 'feed_margin' ] = label . feed_margin l [ 'restrict_printers' ] = label . restricted_to_models label_type_specs [ label . identifier ] = l
We contain this code inside a function so that the imports we do in here are not visible at the module level .