idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
244,400
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 ( ) !...
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 .
244,401
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 .
244,402
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 .
244,403
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 .
244,404
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 .
244,405
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 .
244,406
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 .
244,407
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 .
244,408
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 .
244,409
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 .
244,410
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 .
244,411
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_i...
Prepares list of operations to execute based on p_args list of todo items contained in _todo_ids attribute and _subcommand attribute .
244,412
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...
Executes each operation from _operations attribute .
244,413
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 .
244,414
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 .
244,415
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 . t...
Converts a weekday name to an absolute date .
244,416
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 = ...
Transforms a relative date into a date object .
244,417
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 .
244,418
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 ...
Post - processes a parsed todo when adding it to the list .
244,419
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 [...
Returns list with complete column configuration dicts .
244,420
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 .
244,421
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 . _sourc...
Decompress available input into an output buffer .
244,422
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 syste...
Obtain a distutils . extension . Extension for the C extension .
244,423
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 .
244,424
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 .
244,425
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 . elevat...
Returns dawn sunrise noon sunset and dusk as a dictionary .
244,426
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 . el...
Return sunrise time .
244,427
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 (...
Calculate the time when the sun is at the specified elevation .
244,428
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 . toda...
Returns the start and end times of the Blue Hour when the sun is traversing in the specified direction .
244,429
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 .
244,430
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 .
244,431
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
244,432
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 .
244,433
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 ] [ "formatt...
Lookup the Google geocoding API information for key
244,434
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 . ...
Query the timezone information with the latitude and longitude of the specified location .
244,435
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 ( f...
Query the elevation information with the latitude and longitude of the specified location .
244,436
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 , long...
Calculate all the info for the sun at once . All times are returned in the UTC timezone .
244,437
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...
Calculate dawn time in the UTC timezone .
244,438
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 ...
Calculate sunrise time in the UTC timezone .
244,439
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 )...
Calculate solar noon time in the UTC timezone .
244,440
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 ...
Calculate sunset time in the UTC timezone .
244,441
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 [ ...
Calculate dusk time in the UTC timezone .
244,442
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 - h...
Calculate solar midnight time in the UTC timezone .
244,443
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 .
244,444
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 .
244,445
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 , l...
Returns the start and end times of the Blue Hour in the UTC timezone when the sun is traversing in the specified direction .
244,446
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_ele...
Calculate the time in the UTC timezone when the sun is at the specified elevation on the specified date .
244,447
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 . asti...
Calculate the azimuth angle of the sun .
244,448
def solar_zenith ( self , dateandtime , latitude , longitude ) : return 90.0 - self . solar_elevation ( dateandtime , latitude , longitude )
Calculates the solar zenith angle .
244,449
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 .
244,450
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 = da...
Calculate ruhakaalam times in the UTC timezone .
244,451
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 .
244,452
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 == 'succes...
Example callback function .
244,453
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 exce...
Execute the callback .
244,454
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...
De - serialize the message and execute the job .
244,455
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 ) ...
Start processing Kafka messages and executing jobs .
244,456
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__...
Return the string representation of the function call .
244,457
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 .
244,458
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...
Send instruction bytes to a printer .
244,459
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' : instru...
Process a list of instructions by merging subsequent instuctions with identical opcodes into large instructions .
244,460
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 . basicConf...
Command line interface for the brother_ql Python package .
244,461
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 ( "A...
print debug info about running environment
244,462
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 =...
Print a label of the provided IMAGE .
244,463
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...
List all available devices for the respective backend
244,464
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_...
We contain this code inside a function so that the imports we do in here are not visible at the module level .
244,465
def guess_backend ( identifier ) : if identifier . startswith ( 'usb://' ) or identifier . startswith ( '0x' ) : return 'pyusb' elif identifier . startswith ( 'file://' ) or identifier . startswith ( '/dev/usb/' ) or identifier . startswith ( 'lp' ) : return 'linux_kernel' elif identifier . startswith ( 'tcp://' ) : re...
guess the backend from a given identifier string for the device
244,466
def featured_event_query ( self , ** kwargs ) : if not kwargs . get ( 'location' ) and ( not kwargs . get ( 'latitude' ) or not kwargs . get ( 'longitude' ) ) : raise ValueError ( 'A valid location (parameter "location") or latitude/longitude combination ' '(parameters "latitude" and "longitude") must be provided.' ) r...
Query the Yelp Featured Event API .
244,467
def _get_clean_parameters ( kwargs ) : return dict ( ( k , v ) for k , v in kwargs . items ( ) if v is not None )
Clean the parameters by filtering out any parameters that have a None value .
244,468
def _query ( self , url , ** kwargs ) : parameters = YelpAPI . _get_clean_parameters ( kwargs ) response = self . _yelp_session . get ( url , headers = self . _headers , params = parameters , timeout = self . _timeout_s , ) response_json = response . json ( ) if 'error' in response_json : raise YelpAPI . YelpAPIError (...
All query methods have the same logic so don t repeat it! Query the URL parse the response as JSON and check for errors . If all goes well return the parsed JSON .
244,469
def url_join ( base , * args ) : scheme , netloc , path , query , fragment = urlsplit ( base ) path = path if len ( path ) else "/" path = posixpath . join ( path , * [ ( '%s' % x ) for x in args ] ) return urlunsplit ( [ scheme , netloc , path , query , fragment ] )
Helper function to join an arbitrary number of url segments together .
244,470
def probe_to_graphsrv ( probe ) : config = probe . config if "group" in config : source , group = config [ "group" ] . split ( "." ) group_field = config . get ( "group_field" , "host" ) group_value = config [ group_field ] graphsrv . group . add ( source , group , { group_value : { group_field : group_value } } , ** c...
takes a probe instance and generates a graphsrv data group for it using the probe s config
244,471
def new_message ( self ) : msg = { } msg [ 'data' ] = [ ] msg [ 'type' ] = self . plugin_type msg [ 'source' ] = self . name msg [ 'ts' ] = ( datetime . datetime . utcnow ( ) - datetime . datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return msg
creates a new message setting type source ts data - data is initialized to an empty array
244,472
def popen ( self , args , ** kwargs ) : self . log . debug ( "popen %s" , ' ' . join ( args ) ) return vaping . io . subprocess . Popen ( args , ** kwargs )
creates a subprocess with passed args
244,473
def queue_emission ( self , msg ) : if not msg : return for _emitter in self . _emit : if not hasattr ( _emitter , 'emit' ) : continue def emit ( emitter = _emitter ) : self . log . debug ( "emit to {}" . format ( emitter . name ) ) emitter . emit ( msg ) self . log . debug ( "queue emission to {} ({})" . format ( _emi...
queue an emission of a message for all output plugins
244,474
def send_emission ( self ) : if self . _emit_queue . empty ( ) : return emit = self . _emit_queue . get ( ) emit ( )
emit and remove the first emission in the queue
244,475
def validate_file_handler ( self ) : if self . fh . closed : try : self . fh = open ( self . path , "r" ) self . fh . seek ( 0 , 2 ) except OSError as err : logging . error ( "Could not reopen file: {}" . format ( err ) ) return False open_stat = os . fstat ( self . fh . fileno ( ) ) try : file_stat = os . stat ( self ...
Here we validate that our filehandler is pointing to an existing file .
244,476
def probe ( self ) : if not self . validate_file_handler ( ) : return [ ] messages = [ ] for line in self . fh . readlines ( self . max_lines ) : data = { "path" : self . path } msg = self . new_message ( ) parsed = self . process_line ( line , data ) if not parsed : continue data . update ( parsed ) data = self . proc...
Probe the file for new lines
244,477
def filename_formatters ( self , data , row ) : r = { "source" : data . get ( "source" ) , "field" : self . field , "type" : data . get ( "type" ) } r . update ( ** row ) return r
Returns a dict containing the various filename formatter values
244,478
def format_filename ( self , data , row ) : return self . filename . format ( ** self . filename_formatters ( data , row ) )
Returns a formatted filename using the template stored in self . filename
244,479
def emit ( self , message ) : if isinstance ( message . get ( "data" ) , list ) : for row in message . get ( "data" ) : filename = self . format_filename ( message , row ) if not os . path . exists ( filename ) : self . create ( filename ) self . log . debug ( "storing time:%d, %s:%.5f in %s" % ( message . get ( "ts" )...
emit to database
244,480
def parse_interval ( val ) : re_intv = re . compile ( r"([\d\.]+)([a-zA-Z]+)" ) val = val . strip ( ) total = 0.0 for match in re_intv . findall ( val ) : unit = match [ 1 ] count = float ( match [ 0 ] ) if unit == 's' : total += count elif unit == 'm' : total += count * 60 elif unit == 'ms' : total += count / 1000 eli...
converts a string to float of seconds . 5 = 500ms 90 = 1m30s
244,481
def hosts_args ( self ) : host_args = [ ] for row in self . hosts : if isinstance ( row , dict ) : host_args . append ( row [ "host" ] ) else : host_args . append ( row ) dedupe = list ( ) for each in host_args : if each not in dedupe : dedupe . append ( each ) return dedupe
hosts list can contain strings specifying a host directly or dicts containing a host key to specify the host
244,482
def parse_verbose ( self , line ) : try : logging . debug ( line ) ( host , pings ) = line . split ( ' : ' ) cnt = 0 lost = 0 times = [ ] pings = pings . strip ( ) . split ( ' ' ) cnt = len ( pings ) for latency in pings : if latency == '-' : continue times . append ( float ( latency ) ) lost = cnt - len ( times ) if l...
parse output from verbose format
244,483
def start ( ctx , ** kwargs ) : update_context ( ctx , kwargs ) daemon = mk_daemon ( ctx ) if ctx . debug or kwargs [ 'no_fork' ] : daemon . run ( ) else : daemon . start ( )
start a vaping process
244,484
def stop ( ctx , ** kwargs ) : update_context ( ctx , kwargs ) daemon = mk_daemon ( ctx ) daemon . stop ( )
stop a vaping process
244,485
def restart ( ctx , ** kwargs ) : update_context ( ctx , kwargs ) daemon = mk_daemon ( ctx ) daemon . stop ( ) daemon . start ( )
restart a vaping process
244,486
def render_content ( self , request ) : context = self . data . copy ( ) context . update ( self . render_vars ( request ) ) return render ( self . template , request . app , context , request = request )
Return a string containing the HTML to be rendered for the panel .
244,487
def inject ( self , request , response ) : if not isinstance ( response , Response ) : return settings = request . app [ APP_KEY ] [ 'settings' ] response_html = response . body route = request . app . router [ 'debugtoolbar.request' ] toolbar_url = route . url_for ( request_id = request [ 'id' ] ) button_style = setti...
Inject the debug toolbar iframe into an HTML response .
244,488
def common_segment_count ( path , value ) : i = 0 if len ( path ) <= len ( value ) : for x1 , x2 in zip ( path , value ) : if x1 == x2 : i += 1 else : return 0 return i
Return the number of path segments common to both
244,489
def timing ( self , stat , delta , rate = 1 ) : if isinstance ( delta , timedelta ) : delta = delta . total_seconds ( ) * 1000. self . _send_stat ( stat , '%0.6f|ms' % delta , rate )
Send new timing information .
244,490
def decr ( self , stat , count = 1 , rate = 1 ) : self . incr ( stat , - count , rate )
Decrement a stat by count .
244,491
def gauge ( self , stat , value , rate = 1 , delta = False ) : if value < 0 and not delta : if rate < 1 : if random . random ( ) > rate : return with self . pipeline ( ) as pipe : pipe . _send_stat ( stat , '0|g' , 1 ) pipe . _send_stat ( stat , '%s|g' % value , 1 ) else : prefix = '+' if delta and value >= 0 else '' s...
Set a gauge value .
244,492
def set ( self , stat , value , rate = 1 ) : self . _send_stat ( stat , '%s|s' % value , rate )
Set a set value .
244,493
def safe_wraps ( wrapper , * args , ** kwargs ) : while isinstance ( wrapper , functools . partial ) : wrapper = wrapper . func return functools . wraps ( wrapper , * args , ** kwargs )
Safely wraps partial functions .
244,494
def find_rule_classes ( extra_path ) : files = [ ] modules = [ ] if os . path . isfile ( extra_path ) : files = [ os . path . basename ( extra_path ) ] directory = os . path . dirname ( extra_path ) elif os . path . isdir ( extra_path ) : files = os . listdir ( extra_path ) directory = extra_path else : raise UserRuleE...
Searches a given directory or python module for rule classes . This is done by adding the directory path to the python path importing the modules and then finding any Rule class in those modules .
244,495
def ustr ( obj ) : if sys . version_info [ 0 ] == 2 : if type ( obj ) in [ str , basestring ] : return unicode ( obj , DEFAULT_ENCODING ) else : return unicode ( obj ) else : if type ( obj ) in [ bytes ] : return obj . decode ( DEFAULT_ENCODING ) else : return str ( obj )
Python 2 and 3 utility method that converts an obj to unicode in python 2 and to a str object in python 3
244,496
def get_rule_option ( self , rule_name_or_id , option_name ) : option = self . _get_option ( rule_name_or_id , option_name ) return option . value
Returns the value of a given option for a given rule . LintConfigErrors will be raised if the rule or option don t exist .
244,497
def set_rule_option ( self , rule_name_or_id , option_name , option_value ) : option = self . _get_option ( rule_name_or_id , option_name ) try : option . set ( option_value ) except options . RuleOptionError as e : msg = u"'{0}' is not a valid value for option '{1}.{2}'. {3}." raise LintConfigError ( msg . format ( op...
Attempts to set a given value for a given option for a given rule . LintConfigErrors will be raised if the rule or option don t exist or if the value is invalid .
244,498
def set_from_config_file ( self , filename ) : if not os . path . exists ( filename ) : raise LintConfigError ( u"Invalid file path: {0}" . format ( filename ) ) self . _config_path = os . path . abspath ( filename ) try : parser = ConfigParser ( ) parser . read ( filename ) for section_name in parser . sections ( ) : ...
Loads lint config from a ini - style config file
244,499
def build ( self , config = None ) : if not config : config = LintConfig ( ) config . _config_path = self . _config_path general_section = self . _config_blueprint . get ( 'general' ) if general_section : for option_name , option_value in general_section . items ( ) : config . set_general_option ( option_name , option_...
Build a real LintConfig object by normalizing and validating the options that were previously set on this factory .