idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
14,800
def _make_args ( self , args , passphrase = False ) : cmd = [ self . binary , '--no-options --no-emit-version --no-tty --status-fd 2' ] if self . homedir : cmd . append ( '--homedir "%s"' % self . homedir ) if self . keyring : cmd . append ( '--no-default-keyring --keyring %s' % self . keyring ) if self . secring : cmd...
Make a list of command line elements for GPG .
14,801
def _open_subprocess ( self , args = None , passphrase = False ) : cmd = shlex . split ( ' ' . join ( self . _make_args ( args , passphrase ) ) ) log . debug ( "Sending command to GnuPG process:%s%s" % ( os . linesep , cmd ) ) if platform . system ( ) == "Windows" : expand_shell = True else : expand_shell = False envir...
Open a pipe to a GPG subprocess and return the file objects for communicating with it .
14,802
def _read_data ( self , stream , result ) : chunks = [ ] log . debug ( "Reading data from stream %r..." % stream . __repr__ ( ) ) while True : data = stream . read ( 1024 ) if len ( data ) == 0 : break chunks . append ( data ) log . debug ( "Read %4d bytes" % len ( data ) ) result . data = type ( data ) ( ) . join ( ch...
Incrementally read from stream and store read data .
14,803
def _handle_io ( self , args , file , result , passphrase = False , binary = False ) : p = self . _open_subprocess ( args , passphrase ) if not binary : stdin = codecs . getwriter ( self . _encoding ) ( p . stdin ) else : stdin = p . stdin if passphrase : _util . _write_passphrase ( stdin , passphrase , self . _encodin...
Handle a call to GPG - pass input data collect output data .
14,804
def _sign_file ( self , file , default_key = None , passphrase = None , clearsign = True , detach = False , binary = False , digest_algo = 'SHA512' ) : log . debug ( "_sign_file():" ) if binary : log . info ( "Creating binary signature for file %s" % file ) args = [ '--sign' ] else : log . info ( "Creating ascii-armour...
Create a signature for a file .
14,805
def find_encodings ( enc = None , system = False ) : if not enc : enc = 'utf-8' if system : if getattr ( sys . stdin , 'encoding' , None ) is None : enc = sys . stdin . encoding log . debug ( "Obtained encoding from stdin: %s" % enc ) else : enc = 'ascii' enc = enc . lower ( ) codec_alias = encodings . normalize_encodi...
Find functions for encoding translations for a specific codec .
14,806
def author_info ( name , contact = None , public_key = None ) : return Storage ( name = name , contact = contact , public_key = public_key )
Easy object - oriented representation of contributor info .
14,807
def _copy_data ( instream , outstream ) : sent = 0 while True : if ( ( _py3k and isinstance ( instream , str ) ) or ( not _py3k and isinstance ( instream , basestring ) ) ) : data = instream [ : 1024 ] instream = instream [ 1024 : ] else : data = instream . read ( 1024 ) if len ( data ) == 0 : break sent += len ( data ...
Copy data from one stream to another .
14,808
def _create_if_necessary ( directory ) : if not os . path . isabs ( directory ) : log . debug ( "Got non-absolute path: %s" % directory ) directory = os . path . abspath ( directory ) if not os . path . isdir ( directory ) : log . info ( "Creating directory: %s" % directory ) try : os . makedirs ( directory , 0x1C0 ) e...
Create the specified directory if necessary .
14,809
def create_uid_email ( username = None , hostname = None ) : if hostname : hostname = hostname . replace ( ' ' , '_' ) if not username : try : username = os . environ [ 'LOGNAME' ] except KeyError : username = os . environ [ 'USERNAME' ] if not hostname : hostname = gethostname ( ) uid = "%s@%s" % ( username . replace ...
Create an email address suitable for a UID on a GnuPG key .
14,810
def _deprefix ( line , prefix , callback = None ) : try : assert line . upper ( ) . startswith ( u'' . join ( prefix ) . upper ( ) ) except AssertionError : log . debug ( "Line doesn't start with prefix '%s':\n%s" % ( prefix , line ) ) return line else : newline = line [ len ( prefix ) : ] if callback is not None : try...
Remove the prefix string from the beginning of line if it exists .
14,811
def _find_binary ( binary = None ) : found = None if binary is not None : if os . path . isabs ( binary ) and os . path . isfile ( binary ) : return binary if not os . path . isabs ( binary ) : try : found = _which ( binary ) log . debug ( "Found potential binary paths: %s" % '\n' . join ( [ path for path in found ] ) ...
Find the absolute path to the GnuPG binary .
14,812
def _is_gpg1 ( version ) : ( major , minor , micro ) = _match_version_string ( version ) if major == 1 : return True return False
Returns True if using GnuPG version 1 . x .
14,813
def _is_gpg2 ( version ) : ( major , minor , micro ) = _match_version_string ( version ) if major == 2 : return True return False
Returns True if using GnuPG version 2 . x .
14,814
def _make_passphrase ( length = None , save = False , file = None ) : if not length : length = 40 passphrase = _make_random_string ( length ) if save : ruid , euid , suid = os . getresuid ( ) gid = os . getgid ( ) now = mktime ( localtime ( ) ) if not file : filename = str ( 'passphrase-%s-%s' % uid , now ) file = os ....
Create a passphrase and write it to a file that only the user can read .
14,815
def _make_random_string ( length ) : chars = string . ascii_lowercase + string . ascii_uppercase + string . digits return '' . join ( random . choice ( chars ) for x in range ( length ) )
Returns a random lowercase uppercase alphanumerical string .
14,816
def _match_version_string ( version ) : matched = _VERSION_STRING_REGEX . match ( version ) g = matched . groups ( ) major , minor , micro = g [ 0 ] , g [ 2 ] , g [ 4 ] if major and minor and micro : major , minor , micro = int ( major ) , int ( minor ) , int ( micro ) else : raise GnuPGVersionError ( "Could not parse ...
Sort a binary version string into major minor and micro integers .
14,817
def _next_year ( ) : now = datetime . now ( ) . __str__ ( ) date = now . split ( ' ' , 1 ) [ 0 ] year , month , day = date . split ( '-' , 2 ) next_year = str ( int ( year ) + 1 ) return '-' . join ( ( next_year , month , day ) )
Get the date of today plus one year .
14,818
def _threaded_copy_data ( instream , outstream ) : copy_thread = threading . Thread ( target = _copy_data , args = ( instream , outstream ) ) copy_thread . setDaemon ( True ) log . debug ( '%r, %r, %r' , copy_thread , instream , outstream ) copy_thread . start ( ) return copy_thread
Copy data from one stream to another in a separate thread .
14,819
def _write_passphrase ( stream , passphrase , encoding ) : passphrase = '%s\n' % passphrase passphrase = passphrase . encode ( encoding ) stream . write ( passphrase ) log . debug ( "Wrote passphrase on stdin." )
Write the passphrase from memory to the GnuPG process stdin .
14,820
def sign ( self , data , ** kwargs ) : if 'default_key' in kwargs : log . info ( "Signing message '%r' with keyid: %s" % ( data , kwargs [ 'default_key' ] ) ) else : log . warn ( "No 'default_key' given! Using first key on secring." ) if hasattr ( data , 'read' ) : result = self . _sign_file ( data , ** kwargs ) elif n...
Create a signature for a message string or file .
14,821
def verify ( self , data ) : f = _make_binary_stream ( data , self . _encoding ) result = self . verify_file ( f ) f . close ( ) return result
Verify the signature on the contents of the string data .
14,822
def verify_file ( self , file , sig_file = None ) : result = self . _result_map [ 'verify' ] ( self ) if sig_file is None : log . debug ( "verify_file(): Handling embedded signature" ) args = [ "--verify" ] proc = self . _open_subprocess ( args ) writer = _util . _threaded_copy_data ( file , proc . stdin ) self . _coll...
Verify the signature on the contents of a file or file - like object . Can handle embedded signatures as well as detached signatures . If using detached signatures the file containing the detached signature should be specified as the sig_file .
14,823
def import_keys ( self , key_data ) : result = self . _result_map [ 'import' ] ( self ) log . info ( 'Importing: %r' , key_data [ : 256 ] ) data = _make_binary_stream ( key_data , self . _encoding ) self . _handle_io ( [ '--import' ] , data , result , binary = True ) data . close ( ) return result
Import the key_data into our keyring .
14,824
def delete_keys ( self , fingerprints , secret = False , subkeys = False ) : which = 'keys' if secret : which = 'secret-keys' if subkeys : which = 'secret-and-public-keys' if _is_list_or_tuple ( fingerprints ) : fingerprints = ' ' . join ( fingerprints ) args = [ '--batch' ] args . append ( "--delete-{0} {1}" . format ...
Delete a key or list of keys from the current keyring .
14,825
def export_keys ( self , keyids , secret = False , subkeys = False ) : which = '' if subkeys : which = '-secret-subkeys' elif secret : which = '-secret-keys' if _is_list_or_tuple ( keyids ) : keyids = ' ' . join ( [ '%s' % k for k in keyids ] ) args = [ "--armor" ] args . append ( "--export{0} {1}" . format ( which , k...
Export the indicated keyids .
14,826
def list_keys ( self , secret = False ) : which = 'public-keys' if secret : which = 'secret-keys' args = [ ] args . append ( "--fixed-list-mode" ) args . append ( "--fingerprint" ) args . append ( "--with-colons" ) args . append ( "--list-options no-show-photos" ) args . append ( "--list-%s" % ( which ) ) p = self . _o...
List the keys currently in the keyring .
14,827
def list_packets ( self , raw_data ) : args = [ "--list-packets" ] result = self . _result_map [ 'packets' ] ( self ) self . _handle_io ( args , _make_binary_stream ( raw_data , self . _encoding ) , result ) return result
List the packet contents of a file .
14,828
def encrypt ( self , data , * recipients , ** kwargs ) : if _is_stream ( data ) : stream = data else : stream = _make_binary_stream ( data , self . _encoding ) result = self . _encrypt ( stream , recipients , ** kwargs ) stream . close ( ) return result
Encrypt the message contained in data to recipients .
14,829
def decrypt ( self , message , ** kwargs ) : stream = _make_binary_stream ( message , self . _encoding ) result = self . decrypt_file ( stream , ** kwargs ) stream . close ( ) return result
Decrypt the contents of a string or file - like object message .
14,830
def decrypt_file ( self , filename , always_trust = False , passphrase = None , output = None ) : args = [ "--decrypt" ] if output : if os . path . exists ( output ) : os . remove ( output ) args . append ( '--output %s' % output ) if always_trust : args . append ( "--always-trust" ) result = self . _result_map [ 'cryp...
Decrypt the contents of a file - like object filename .
14,831
def find_key_by_email ( self , email , secret = False ) : for key in self . list_keys ( secret = secret ) : for uid in key [ 'uids' ] : if re . search ( email , uid ) : return key raise LookupError ( "GnuPG public key for email %s not found!" % email )
Find user s key based on their email address .
14,832
def find_key_by_subkey ( self , subkey ) : for key in self . list_keys ( ) : for sub in key [ 'subkeys' ] : if sub [ 0 ] == subkey : return key raise LookupError ( "GnuPG public key for subkey %s not found!" % subkey )
Find a key by a fingerprint of one of its subkeys .
14,833
def send_keys ( self , keyserver , * keyids ) : result = self . _result_map [ 'list' ] ( self ) log . debug ( 'send_keys: %r' , keyids ) data = _util . _make_binary_stream ( "" , self . _encoding ) args = [ '--keyserver' , keyserver , '--send-keys' ] args . extend ( keyids ) self . _handle_io ( args , data , result , b...
Send keys to a keyserver .
14,834
def encrypted_to ( self , raw_data ) : result = self . _gpg . list_packets ( raw_data ) if not result . key : raise LookupError ( "Content is not encrypted to a GnuPG key!" ) try : return self . find_key_by_keyid ( result . key ) except : return self . find_key_by_subkey ( result . key )
Return the key to which raw_data is encrypted to .
14,835
def imread ( filename ) : im = cv2 . imread ( filename ) if im is None : raise RuntimeError ( "file: '%s' not exists" % filename ) return im
Like cv2 . imread This function will make sure filename exists
14,836
def find_all_template ( im_source , im_search , threshold = 0.5 , maxcnt = 0 , rgb = False , bgremove = False ) : method = cv2 . TM_CCOEFF_NORMED if rgb : s_bgr = cv2 . split ( im_search ) i_bgr = cv2 . split ( im_source ) weight = ( 0.3 , 0.3 , 0.4 ) resbgr = [ 0 , 0 , 0 ] for i in range ( 3 ) : resbgr [ i ] = cv2 . m...
Locate image position with cv2 . templateFind
14,837
def find ( im_source , im_search ) : r = find_all ( im_source , im_search , maxcnt = 1 ) return r [ 0 ] if r else None
Only find maximum one object
14,838
def init ( self ) : self . _context_notify_cb = pa_context_notify_cb_t ( self . context_notify_cb ) self . _sink_info_cb = pa_sink_info_cb_t ( self . sink_info_cb ) self . _update_cb = pa_context_subscribe_cb_t ( self . update_cb ) self . _success_cb = pa_context_success_cb_t ( self . success_cb ) self . _server_info_c...
Creates context when context is ready context_notify_cb is called
14,839
def server_info_cb ( self , context , server_info_p , userdata ) : server_info = server_info_p . contents self . request_update ( context )
Retrieves the default sink and calls request_update
14,840
def context_notify_cb ( self , context , _ ) : state = pa_context_get_state ( context ) if state == PA_CONTEXT_READY : pa_operation_unref ( pa_context_get_server_info ( context , self . _server_info_cb , None ) ) pa_context_set_subscribe_callback ( context , self . _update_cb , None ) pa_operation_unref ( pa_context_su...
Checks wether the context is ready
14,841
def update_cb ( self , context , t , idx , userdata ) : if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER : pa_operation_unref ( pa_context_get_server_info ( context , self . _server_info_cb , None ) ) self . request_update ( context )
A sink property changed calls request_update
14,842
def sink_info_cb ( self , context , sink_info_p , _ , __ ) : if sink_info_p : sink_info = sink_info_p . contents volume_percent = round ( 100 * sink_info . volume . values [ 0 ] / 0x10000 ) volume_db = pa_sw_volume_to_dB ( sink_info . volume . values [ 0 ] ) self . currently_muted = sink_info . mute if volume_db == flo...
Updates self . output
14,843
def cycle_interface ( self , increment = 1 ) : interfaces = [ i for i in netifaces . interfaces ( ) if i not in self . ignore_interfaces ] if self . interface in interfaces : next_index = ( interfaces . index ( self . interface ) + increment ) % len ( interfaces ) self . interface = interfaces [ next_index ] elif len (...
Cycle through available interfaces in increment steps . Sign indicates direction .
14,844
def start ( self , seconds = 300 ) : if self . state is TimerState . stopped : self . compare = time . time ( ) + abs ( seconds ) self . state = TimerState . running elif self . state is TimerState . running : self . increase ( seconds )
Starts timer . If timer is already running it will increase remaining time instead .
14,845
def increase ( self , seconds ) : if self . state is TimerState . running : new_compare = self . compare + seconds if new_compare > time . time ( ) : self . compare = new_compare
Change remainig time value .
14,846
def reset ( self ) : if self . state is not TimerState . stopped : if self . on_reset and self . state is TimerState . overflow : if callable ( self . on_reset ) : self . on_reset ( ) else : execute ( self . on_reset ) self . state = TimerState . stopped
Stop timer and execute on_reset if overflow occured .
14,847
def write_line ( self , message ) : self . out . write ( message + "\n" ) self . out . flush ( )
Unbuffered printing to stdout .
14,848
def read_line ( self ) : try : line = self . inp . readline ( ) . strip ( ) except KeyboardInterrupt : raise EOFError ( ) if not line : raise EOFError ( ) return line
Interrupted respecting reader for stdin .
14,849
def compute_treshold_interval ( self ) : intervals = [ m . interval for m in self . modules if hasattr ( m , "interval" ) ] if len ( intervals ) > 0 : self . treshold_interval = round ( sum ( intervals ) / len ( intervals ) )
Current method is to compute average from all intervals .
14,850
def refresh_signal_handler ( self , signo , frame ) : if signo != signal . SIGUSR1 : return for module in self . modules : if hasattr ( module , "interval" ) : if module . interval > self . treshold_interval : thread = Thread ( target = module . run ) thread . start ( ) else : module . run ( ) else : module . run ( ) s...
This callback is called when SIGUSR1 signal is received .
14,851
def parse_line ( self , line ) : prefix = "" if line . startswith ( "," ) : line , prefix = line [ 1 : ] , "," j = json . loads ( line ) yield j self . io . write_line ( prefix + json . dumps ( j ) )
Parse a single line of JSON and write modified JSON back .
14,852
def on_click ( self , event ) : DesktopNotification ( title = event . title , body = "{} until {}!" . format ( event . time_remaining , event . title ) , icon = 'dialog-information' , urgency = 1 , timeout = 0 , ) . display ( )
Override this method to do more interesting things with the event .
14,853
def is_urgent ( self ) : if not self . current_event : return False now = datetime . now ( tz = self . current_event . start . tzinfo ) alert_time = now + timedelta ( seconds = self . urgent_seconds ) urgent = alert_time > self . current_event . start if urgent and self . urgent_blink : urgent = now . second % 2 == 0 a...
Determine whether or not to set the urgent flag . If urgent_blink is set toggles urgent flag on and off every second .
14,854
def init ( self ) : try : for no_lookup in ( 'pws' , 'icao' ) : sid = self . location_code . partition ( no_lookup + ':' ) [ - 1 ] if sid : self . station_id = self . location_code return except AttributeError : pass self . get_station_id ( )
Use the location_code to perform a geolookup and find the closest station . If the location is a pws or icao station ID no lookup will be peformed .
14,855
def get_station_id ( self ) : extra_opts = '/pws:0' if not self . use_pws else '' api_url = GEOLOOKUP_URL % ( self . api_key , extra_opts , self . location_code ) response = self . api_request ( api_url ) station_type = 'pws' if self . use_pws else 'airport' try : stations = response [ 'location' ] [ 'nearby_weather_st...
Use geolocation to get the station ID
14,856
def get_api_date ( self ) : api_date = None if self . date is not None and not isinstance ( self . date , datetime ) : try : api_date = datetime . strptime ( self . date , '%Y-%m-%d' ) except ( TypeError , ValueError ) : self . logger . warning ( 'Invalid date \'%s\'' , self . date ) if api_date is None : utc_time = py...
Figure out the date to use for API requests . Assumes yesterday s date if between midnight and 10am Eastern time . Override this function in a subclass to change how the API date is calculated .
14,857
def handle_data ( self , content ) : if self . weather_data is not None : return content = content . strip ( ) . rstrip ( ';' ) try : tag_text = self . get_starttag_text ( ) . lower ( ) except AttributeError : tag_text = '' if tag_text . startswith ( '<script' ) : begin = content . find ( 'window.__data' ) if begin != ...
Sometimes the weather data is set under an attribute of the window DOM object . Sometimes it appears as part of a javascript function . Catch either possibility .
14,858
def main_loop ( self ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) port = int ( getattr ( self , 'port' , 1738 ) ) sock . bind ( ( '127.0.0.1' , port ) ) while True : data , addr = sock . recvfrom ( 512 ) color = data . decode ( ) . strip ( ) self . color = self . colors . get ( color , color )
Mainloop blocks so we thread it .
14,859
def should_execute ( self , workload ) : if not self . _suspended . is_set ( ) : return True workload = unwrap_workload ( workload ) return hasattr ( workload , 'keep_alive' ) and getattr ( workload , 'keep_alive' )
If we have been suspended by i3bar only execute those modules that set the keep_alive flag to a truthy value . See the docs on the suspend_signal_handler method of the io module for more information .
14,860
def get_sensors ( ) : import sensors found_sensors = list ( ) def get_subfeature_value ( feature , subfeature_type ) : subfeature = chip . get_subfeature ( feature , subfeature_type ) if subfeature : return chip . get_value ( subfeature . number ) for chip in sensors . get_detected_chips ( ) : for feature in chip . get...
Detect and return a list of Sensor objects
14,861
def get_output_original ( self ) : with open ( self . file , "r" ) as f : temp = float ( f . read ( ) . strip ( ) ) / 1000 if self . dynamic_color : perc = int ( self . percentage ( int ( temp ) , self . alert_temp ) ) if ( perc > 99 ) : perc = 99 color = self . colors [ perc ] else : color = self . color if temp < sel...
Build the output the original way . Requires no third party libraries .
14,862
def get_urgent ( self , sensors ) : if self . urgent_on not in ( 'warning' , 'critical' ) : raise Exception ( "urgent_on must be one of (warning, critical)" ) for sensor in sensors : if self . urgent_on == 'warning' and sensor . is_warning ( ) : return True elif self . urgent_on == 'critical' and sensor . is_critical (...
Determine if any sensors should set the urgent flag .
14,863
def format_sensor ( self , sensor ) : current_val = sensor . current if self . pango_enabled : percentage = self . percentage ( sensor . current , sensor . critical ) if self . dynamic_color : color = self . colors [ int ( percentage ) ] return self . format_pango ( color , current_val ) return current_val
Format a sensor value . If pango is enabled color is per sensor .
14,864
def format_sensor_bar ( self , sensor ) : percentage = self . percentage ( sensor . current , sensor . critical ) bar = make_vertical_bar ( int ( percentage ) ) if self . pango_enabled : if self . dynamic_color : color = self . colors [ int ( percentage ) ] return self . format_pango ( color , bar ) return bar
Build and format a sensor bar . If pango is enabled bar color is per sensor .
14,865
def run ( self ) : unread = 0 current_unread = 0 for id , backend in enumerate ( self . backends ) : temp = backend . unread or 0 unread = unread + temp if id == self . current_backend : current_unread = temp if not unread : color = self . color urgent = "false" if self . hide_if_null : self . output = None return else...
Returns the sum of unread messages across all registered backends
14,866
def parse_output ( self , line ) : try : key , value = line . split ( ":" ) self . update_value ( key . strip ( ) , value . strip ( ) ) except ValueError : pass
Convert output to key value pairs
14,867
def update_value ( self , key , value ) : if key == "Status" : self . _inhibited = value != "Enabled" elif key == "Color temperature" : self . _temperature = int ( value . rstrip ( "K" ) , 10 ) elif key == "Period" : self . _period = value elif key == "Brightness" : self . _brightness = value elif key == "Location" : l...
Parse key value pairs to update their values
14,868
def set_inhibit ( self , inhibit ) : if self . _pid and inhibit != self . _inhibited : os . kill ( self . _pid , signal . SIGUSR1 ) self . _inhibited = inhibit
Set inhibition state
14,869
def execute ( command , detach = False ) : if detach : if not isinstance ( command , str ) : msg = "Detached mode expects a string as command, not {}" . format ( command ) logging . getLogger ( "i3pystatus.core.command" ) . error ( msg ) raise AttributeError ( msg ) command = [ "i3-msg" , "exec" , command ] else : if i...
Runs a command in background . No output is retrieved . Useful for running GUI applications that would block click events .
14,870
def get_hex_color_range ( start_color , end_color , quantity ) : raw_colors = [ c . hex for c in list ( Color ( start_color ) . range_to ( Color ( end_color ) , quantity ) ) ] colors = [ ] for color in raw_colors : if len ( color ) == 4 : fixed_color = "#" for c in color [ 1 : ] : fixed_color += c * 2 colors . append (...
Generates a list of quantity Hex colors from start_color to end_color .
14,871
def is_method_of ( method , object ) : if not callable ( method ) or not hasattr ( method , "__name__" ) : return False if inspect . ismethod ( method ) : return method . __self__ is object for cls in inspect . getmro ( object . __class__ ) : if cls . __dict__ . get ( method . __name__ , None ) is method : return True ...
Decide whether method is contained within the MRO of object .
14,872
def on_click ( self , button , ** kwargs ) : actions = [ 'leftclick' , 'middleclick' , 'rightclick' , 'upscroll' , 'downscroll' ] try : action = actions [ button - 1 ] except ( TypeError , IndexError ) : self . __log_button_event ( button , None , None , "Other button" ) action = "otherclick" m_click = self . __multi_c...
Maps a click event with its associated callback .
14,873
def text_to_pango ( self ) : def replace ( s ) : s = s . split ( "&" ) out = s [ 0 ] for i in range ( len ( s ) - 1 ) : if s [ i + 1 ] . startswith ( "amp;" ) : out += "&" + s [ i + 1 ] else : out += "&amp;" + s [ i + 1 ] return out if "full_text" in self . output . keys ( ) : self . output [ "full_text" ] = replace ( ...
Replaces all ampersands in full_text and short_text attributes of self . output with &amp ; .
14,874
def get_protected_settings ( self , settings_source ) : user_backend = settings_source . get ( 'keyring_backend' ) found_settings = dict ( ) for setting_name in self . __PROTECTED_SETTINGS : if settings_source . get ( setting_name ) : continue setting = None identifier = "%s.%s" % ( self . __name__ , setting_name ) if ...
Attempt to retrieve protected settings from keyring if they are not already set .
14,875
def register ( self , module , * args , ** kwargs ) : from i3pystatus . text import Text if not module : return hints = self . default_hints . copy ( ) if self . default_hints else { } hints . update ( kwargs . get ( 'hints' , { } ) ) if hints : kwargs [ 'hints' ] = hints try : return self . modules . append ( module ,...
Register a new module .
14,876
def run ( self ) : if self . click_events : self . command_endpoint . start ( ) for j in io . JSONIO ( self . io ) . read ( ) : for module in self . modules : module . inject ( j )
Run main loop .
14,877
def init ( self ) : self . url = self . url . format ( host = self . host , port = self . port , api_key = self . api_key )
Initialize the URL used to connect to SABnzbd .
14,878
def run ( self ) : try : answer = urlopen ( self . url + "&mode=queue" ) . read ( ) . decode ( ) except ( HTTPError , URLError ) as error : self . output = { "full_text" : str ( error . reason ) , "color" : "#FF0000" } return answer = json . loads ( answer ) if not answer . get ( "status" , True ) : self . output = { "...
Connect to SABnzbd and get the data .
14,879
def pause_resume ( self ) : if self . is_paused ( ) : urlopen ( self . url + "&mode=resume" ) else : urlopen ( self . url + "&mode=pause" )
Toggle between pausing or resuming downloading .
14,880
def open_browser ( self ) : webbrowser . open ( "http://{host}:{port}/" . format ( host = self . host , port = self . port ) )
Open the URL of SABnzbd inside a browser .
14,881
def on_click ( self , button , ** kwargs ) : if button in ( 4 , 5 ) : return super ( ) . on_click ( button , ** kwargs ) else : activemodule = self . get_active_module ( ) if not activemodule : return return activemodule . on_click ( button , ** kwargs )
Capture scrollup and scorlldown to move in groups Pass everthing else to the module itself
14,882
def _get_system_tz ( self ) : if not HAS_PYTZ : return None def _etc_localtime ( ) : try : with open ( '/etc/localtime' , 'rb' ) as fp : return pytz . tzfile . build_tzinfo ( 'system' , fp ) except OSError as exc : if exc . errno != errno . ENOENT : self . logger . error ( 'Unable to read from /etc/localtime: %s' , exc...
Get the system timezone for use when no timezone is explicitly provided
14,883
def check_weather ( self ) : self . output [ 'full_text' ] = self . refresh_icon + self . output . get ( 'full_text' , '' ) self . backend . check_weather ( ) self . refresh_display ( )
Check the weather using the configured backend
14,884
def get_color_data ( self , condition ) : if condition not in self . color_icons : condition_lc = condition . lower ( ) if 'cloudy' in condition_lc or 'clouds' in condition_lc : if 'partly' in condition_lc : condition = 'Partly Cloudy' else : condition = 'Cloudy' elif condition_lc == 'overcast' : condition = 'Cloudy' e...
Disambiguate similarly - named weather conditions and return the icon and color that match .
14,885
def gen_format_all ( self , usage ) : format_string = " " core_strings = [ ] for core , usage in usage . items ( ) : if core == 'usage_cpu' and self . exclude_average : continue elif core == 'usage' : continue core = core . replace ( 'usage_' , '' ) string = self . formatter . format ( self . format_all , core = core ,...
generates string for format all
14,886
def refresh_events ( self ) : now = datetime . datetime . now ( tz = pytz . UTC ) try : now , later = self . get_timerange_formatted ( now ) events_result = self . service . events ( ) . list ( calendarId = 'primary' , timeMin = now , timeMax = later , maxResults = 10 , singleEvents = True , orderBy = 'startTime' , tim...
Retrieve the next N events from Google .
14,887
def lchop ( string , prefix ) : if string . startswith ( prefix ) : return string [ len ( prefix ) : ] return string
Removes a prefix from string
14,888
def popwhile ( predicate , iterable ) : while iterable : item = iterable . pop ( ) if predicate ( item ) : yield item else : break
Generator function yielding items of iterable while predicate holds for each item
14,889
def round_dict ( dic , places ) : if places is None : for key , value in dic . items ( ) : dic [ key ] = round ( value ) else : for key , value in dic . items ( ) : dic [ key ] = round ( value , places )
Rounds all values in a dict containing only numeric types to places decimal places . If places is None round to INT .
14,890
def flatten ( l ) : l = list ( l ) i = 0 while i < len ( l ) : while isinstance ( l [ i ] , list ) : if not l [ i ] : l . pop ( i ) i -= 1 break else : l [ i : i + 1 ] = l [ i ] i += 1 return l
Flattens a hierarchy of nested lists into a single list containing all elements in order
14,891
def formatp ( string , ** kwargs ) : def build_stack ( string ) : class Token : string = "" class OpeningBracket ( Token ) : pass class ClosingBracket ( Token ) : pass class String ( Token ) : def __init__ ( self , str ) : self . string = str TOKENS = { "[" : OpeningBracket , "]" : ClosingBracket , } stack = [ ] next =...
Function for advanced format strings with partial formatting
14,892
def require ( predicate ) : def decorator ( method ) : @ functools . wraps ( method ) def wrapper ( * args , ** kwargs ) : if predicate ( ) : return method ( * args , ** kwargs ) return None return wrapper return decorator
Decorator factory for methods requiring a predicate . If the predicate is not fulfilled during a method call the method call is skipped and None is returned .
14,893
def make_graph ( values , lower_limit = 0.0 , upper_limit = 100.0 , style = "blocks" ) : values = [ float ( n ) for n in values ] mn , mx = min ( values ) , max ( values ) mn = mn if lower_limit is None else min ( mn , float ( lower_limit ) ) mx = mx if upper_limit is None else max ( mx , float ( upper_limit ) ) extent...
Draws a graph made of unicode characters .
14,894
def make_vertical_bar ( percentage , width = 1 ) : bar = ' _β–β–‚β–ƒβ–„β–…β–†β–‡β–ˆ' percentage //= 10 percentage = int ( percentage ) if percentage < 0 : output = bar [ 0 ] elif percentage >= len ( bar ) : output = bar [ - 1 ] else : output = bar [ percentage ] return output * width
Draws a vertical bar made of unicode characters .
14,895
def get_module ( function ) : @ functools . wraps ( function ) def call_wrapper ( * args , ** kwargs ) : stack = inspect . stack ( ) caller_frame_info = stack [ 1 ] self = caller_frame_info [ 0 ] . f_locals [ "self" ] del stack function ( self , * args , ** kwargs ) return call_wrapper
Function decorator for retrieving the self argument from the stack .
14,896
def init_fundamental_types ( self ) : for _id in range ( 2 , 25 ) : setattr ( self , TypeKind . from_id ( _id ) . name , self . _handle_fundamental_types )
Registers all fundamental typekind handlers
14,897
def _handle_fundamental_types ( self , typ ) : ctypesname = self . get_ctypes_name ( typ . kind ) if typ . kind == TypeKind . VOID : size = align = 1 else : size = typ . get_size ( ) align = typ . get_align ( ) return typedesc . FundamentalType ( ctypesname , size , align )
Handles POD types nodes . see init_fundamental_types for the registration .
14,898
def TYPEDEF ( self , _cursor_type ) : _decl = _cursor_type . get_declaration ( ) name = self . get_unique_name ( _decl ) if self . is_registered ( name ) : obj = self . get_registered ( name ) else : log . debug ( 'Was in TYPEDEF but had to parse record declaration for %s' , name ) obj = self . parse_cursor ( _decl ) r...
Handles TYPEDEF statement .
14,899
def ENUM ( self , _cursor_type ) : _decl = _cursor_type . get_declaration ( ) name = self . get_unique_name ( _decl ) if self . is_registered ( name ) : obj = self . get_registered ( name ) else : log . warning ( 'Was in ENUM but had to parse record declaration ' ) obj = self . parse_cursor ( _decl ) return obj
Handles ENUM typedef .