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 . append ( '--secret-keyring %s' % self . secring ) if passphrase : cmd . append ( '--batch --passphrase-fd 0' ) if self . use_agent is True : cmd . append ( '--use-agent' ) elif self . use_agent is False : cmd . append ( '--no-use-agent' ) if self . verbose : cmd . append ( '--debug-all' ) if ( isinstance ( self . verbose , str ) or ( isinstance ( self . verbose , int ) and ( self . verbose >= 1 ) ) ) : if self . binary_version and ( self . binary_version <= '1.4.18' ) : cmd . append ( '--debug-level=%s' % self . verbose ) else : cmd . append ( '--debug-level %s' % self . verbose ) if self . options : [ cmd . append ( opt ) for opt in iter ( _sanitise_list ( self . options ) ) ] if args : [ cmd . append ( arg ) for arg in iter ( _sanitise_list ( args ) ) ] return 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 environment = { 'LANGUAGE' : os . environ . get ( 'LANGUAGE' ) or 'en' , 'GPG_TTY' : os . environ . get ( 'GPG_TTY' ) or '' , 'DISPLAY' : os . environ . get ( 'DISPLAY' ) or '' , 'GPG_AGENT_INFO' : os . environ . get ( 'GPG_AGENT_INFO' ) or '' , 'GPG_TTY' : os . environ . get ( 'GPG_TTY' ) or '' , 'GPG_PINENTRY_PATH' : os . environ . get ( 'GPG_PINENTRY_PATH' ) or '' , } return subprocess . Popen ( cmd , shell = expand_shell , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , env = environment ) | 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 ( chunks ) log . debug ( "Finishing reading from stream %r..." % stream . __repr__ ( ) ) log . debug ( "Read %4d bytes total" % len ( result . data ) ) | 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 . _encoding ) writer = _util . _threaded_copy_data ( file , stdin ) self . _collect_output ( p , result , writer , stdin ) return result | 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-armoured signature for file %s" % file ) args = [ '--sign --armor' ] if clearsign : args . append ( "--clearsign" ) if detach : log . warn ( "Cannot use both --clearsign and --detach-sign." ) log . warn ( "Using default GPG behaviour: --clearsign only." ) elif detach and not clearsign : args . append ( "--detach-sign" ) if default_key : args . append ( str ( "--default-key %s" % default_key ) ) args . append ( str ( "--digest-algo %s" % digest_algo ) ) result = self . _result_map [ 'sign' ] ( self ) if _util . _is_string ( passphrase ) : passphrase = passphrase if len ( passphrase ) > 0 else None elif _util . _is_bytes ( passphrase ) : passphrase = s ( passphrase ) if len ( passphrase ) > 0 else None else : passphrase = None proc = self . _open_subprocess ( args , passphrase is not None ) try : if passphrase : _util . _write_passphrase ( proc . stdin , passphrase , self . _encoding ) writer = _util . _threaded_copy_data ( file , proc . stdin ) except IOError as ioe : log . exception ( "Error writing message: %s" % str ( ioe ) ) writer = None self . _collect_output ( proc , result , writer , proc . stdin ) return result | 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_encoding ( enc ) codecs . register ( encodings . search_function ) coder = codecs . lookup ( codec_alias ) return coder | 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 ) if ( ( _py3k and isinstance ( data , str ) ) or ( not _py3k and isinstance ( data , basestring ) ) ) : encoded = binary ( data ) else : encoded = data log . debug ( "Sending %d bytes of data..." % sent ) log . debug ( "Encoded data (type %s):\n%s" % ( type ( encoded ) , encoded ) ) if not _py3k : try : outstream . write ( encoded ) except IOError as ioe : if 'Broken pipe' in str ( ioe ) : log . error ( 'Error sending data: Broken pipe' ) else : log . exception ( ioe ) break else : log . debug ( "Wrote data type <type 'str'> to outstream." ) else : try : outstream . write ( bytes ( encoded ) ) except TypeError as te : if not "convert 'bytes' object to str implicitly" in str ( te ) : log . error ( str ( te ) ) try : outstream . write ( encoded . decode ( ) ) except TypeError as yate : if not "does not support the buffer interface" in str ( yate ) : log . error ( str ( yate ) ) except IOError as ioe : if 'Broken pipe' in str ( ioe ) : log . error ( 'Error sending data: Broken pipe' ) else : log . exception ( ioe ) break else : log . debug ( "Wrote data type <class 'str'> outstream." ) except IOError as ioe : if 'Broken pipe' in str ( ioe ) : log . error ( 'Error sending data: Broken pipe' ) else : log . exception ( ioe ) break else : log . debug ( "Wrote data type <class 'bytes'> to outstream." ) try : outstream . close ( ) except IOError as ioe : log . error ( "Unable to close outstream %s:\r\t%s" % ( outstream , ioe ) ) else : log . debug ( "Closed outstream: %d bytes sent." % sent ) | 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 ) except OSError as ose : log . error ( ose , exc_info = 1 ) return False else : log . debug ( "Created directory." ) return True | 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 ( ' ' , '_' ) , hostname ) else : username = username . replace ( ' ' , '_' ) if ( not hostname ) and ( username . find ( '@' ) == 0 ) : uid = "%s@%s" % ( username , gethostname ( ) ) elif hostname : uid = "%s@%s" % ( username , hostname ) else : uid = username return uid | 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 : callback ( newline ) except Exception as exc : log . exception ( exc ) return newline | 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 ] ) ) found = found [ 0 ] except IndexError as ie : log . info ( "Could not determine absolute path of binary: '%s'" % binary ) elif os . access ( binary , os . X_OK ) : found = binary if found is None : try : found = _which ( 'gpg' , abspath_only = True , disallow_symlinks = True ) [ 0 ] except IndexError as ie : log . error ( "Could not find binary for 'gpg'." ) try : found = _which ( 'gpg2' ) [ 0 ] except IndexError as ie : log . error ( "Could not find binary for 'gpg2'." ) if found is None : raise RuntimeError ( "GnuPG is not installed!" ) return 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 . path . join ( _repo , filename ) with open ( file , 'a' ) as fh : fh . write ( passphrase ) fh . flush ( ) fh . close ( ) os . chmod ( file , stat . S_IRUSR | stat . S_IWUSR ) os . chown ( file , ruid , gid ) log . warn ( "Generated passphrase saved to %s" % file ) return passphrase | 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 GnuPG version from: %r" % version ) return ( major , minor , micro ) | 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 not _is_stream ( data ) : stream = _make_binary_stream ( data , self . _encoding ) result = self . _sign_file ( stream , ** kwargs ) stream . close ( ) else : log . warn ( "Unable to sign message '%s' with type %s" % ( data , type ( data ) ) ) result = None return result | 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 . _collect_output ( proc , result , writer , stdin = proc . stdin ) else : if not _util . _is_file ( sig_file ) : log . debug ( "verify_file(): '%r' is not a file" % sig_file ) return result log . debug ( 'verify_file(): Handling detached verification' ) sig_fh = None try : sig_fh = open ( sig_file , 'rb' ) args = [ "--verify %s -" % sig_fh . name ] proc = self . _open_subprocess ( args ) writer = _util . _threaded_copy_data ( file , proc . stdin ) self . _collect_output ( proc , result , writer , stdin = proc . stdin ) finally : if sig_fh and not sig_fh . closed : sig_fh . close ( ) return result | 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 ( which , fingerprints ) ) result = self . _result_map [ 'delete' ] ( self ) p = self . _open_subprocess ( args ) self . _collect_output ( p , result , stdin = p . stdin ) return result | 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 , keyids ) ) p = self . _open_subprocess ( args ) result = self . _result_map [ 'export' ] ( self ) self . _collect_output ( p , result , stdin = p . stdin ) log . debug ( 'Exported:%s%r' % ( os . linesep , result . fingerprints ) ) return result . data . decode ( self . _encoding , self . _decode_errors ) | 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 . _open_subprocess ( args ) result = self . _result_map [ 'list' ] ( self ) self . _collect_output ( p , result , stdin = p . stdin ) lines = result . data . decode ( self . _encoding , self . _decode_errors ) . splitlines ( ) self . _parse_keys ( result ) return result | 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 [ 'crypt' ] ( self ) self . _handle_io ( args , filename , result , passphrase , binary = True ) log . debug ( 'decrypt result: %r' , result . data ) return result | 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 , binary = True ) log . debug ( 'send_keys result: %r' , result . __dict__ ) data . close ( ) return result | 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 . matchTemplate ( i_bgr [ i ] , s_bgr [ i ] , method ) res = resbgr [ 0 ] * weight [ 0 ] + resbgr [ 1 ] * weight [ 1 ] + resbgr [ 2 ] * weight [ 2 ] else : s_gray = cv2 . cvtColor ( im_search , cv2 . COLOR_BGR2GRAY ) i_gray = cv2 . cvtColor ( im_source , cv2 . COLOR_BGR2GRAY ) if bgremove : s_gray = cv2 . Canny ( s_gray , 100 , 200 ) i_gray = cv2 . Canny ( i_gray , 100 , 200 ) res = cv2 . matchTemplate ( i_gray , s_gray , method ) w , h = im_search . shape [ 1 ] , im_search . shape [ 0 ] result = [ ] while True : min_val , max_val , min_loc , max_loc = cv2 . minMaxLoc ( res ) if method in [ cv2 . TM_SQDIFF , cv2 . TM_SQDIFF_NORMED ] : top_left = min_loc else : top_left = max_loc if DEBUG : print ( 'templmatch_value(thresh:%.1f) = %.3f' % ( threshold , max_val ) ) if max_val < threshold : break middle_point = ( top_left [ 0 ] + w / 2 , top_left [ 1 ] + h / 2 ) result . append ( dict ( result = middle_point , rectangle = ( top_left , ( top_left [ 0 ] , top_left [ 1 ] + h ) , ( top_left [ 0 ] + w , top_left [ 1 ] ) , ( top_left [ 0 ] + w , top_left [ 1 ] + h ) ) , confidence = max_val ) ) if maxcnt and len ( result ) >= maxcnt : break cv2 . floodFill ( res , None , max_loc , ( - 1000 , ) , max_val - threshold + 0.1 , 1 , flags = cv2 . FLOODFILL_FIXED_RANGE ) return result | 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_cb = pa_server_info_cb_t ( self . server_info_cb ) _mainloop = pa_threaded_mainloop_new ( ) _mainloop_api = pa_threaded_mainloop_get_api ( _mainloop ) context = pa_context_new ( _mainloop_api , "i3pystatus_pulseaudio" . encode ( "ascii" ) ) pa_context_set_state_callback ( context , self . _context_notify_cb , None ) pa_context_connect ( context , None , 0 , None ) pa_threaded_mainloop_start ( _mainloop ) self . colors = self . get_hex_color_range ( self . color_muted , self . color_unmuted , 100 ) self . sinks = [ ] | 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_subscribe ( context , PA_SUBSCRIPTION_EVENT_CHANGE | PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SERVER , self . _success_cb , None ) ) | 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 == float ( '-Infinity' ) : volume_db = "-β" else : volume_db = int ( volume_db ) muted = self . muted if sink_info . mute else self . unmuted if self . multi_colors and not sink_info . mute : color = self . get_gradient ( volume_percent , self . colors ) else : color = self . color_muted if sink_info . mute else self . color_unmuted if muted and self . format_muted is not None : output_format = self . format_muted else : output_format = self . format if self . bar_type == 'vertical' : volume_bar = make_vertical_bar ( volume_percent , self . vertical_bar_width ) elif self . bar_type == 'horizontal' : volume_bar = make_bar ( volume_percent ) else : raise Exception ( "bar_type must be 'vertical' or 'horizontal'" ) selected = "" dump = subprocess . check_output ( "pacmd dump" . split ( ) , universal_newlines = True ) for line in dump . split ( "\n" ) : if line . startswith ( "set-default-sink" ) : default_sink = line . split ( ) [ 1 ] if default_sink == self . current_sink : selected = self . format_selected self . output = { "color" : color , "full_text" : output_format . format ( muted = muted , volume = volume_percent , db = volume_db , volume_bar = volume_bar , selected = selected ) , } self . send_output ( ) | 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 ( interfaces ) > 0 : self . interface = interfaces [ 0 ] if self . network_traffic : self . network_traffic . clear_counters ( ) self . kbs_arr = [ 0.0 ] * self . graph_width | 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 ( ) self . async_refresh ( ) | 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 and not self . urgent_acknowledged return urgent | 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_stations' ] nearest = stations [ station_type ] [ 'station' ] [ 0 ] except ( KeyError , IndexError ) : raise Exception ( 'No locations matched location_code %s' % self . location_code ) self . logger . error ( 'nearest = %s' , nearest ) if self . use_pws : nearest_pws = nearest . get ( 'id' , '' ) if not nearest_pws : raise Exception ( 'No id entry for nearest PWS' ) self . station_id = 'pws:%s' % nearest_pws else : nearest_airport = nearest . get ( 'icao' , '' ) if not nearest_airport : raise Exception ( 'No icao entry for nearest airport' ) self . station_id = 'icao:%s' % nearest_airport | 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 = pytz . utc . localize ( datetime . utcnow ( ) ) eastern = pytz . timezone ( 'US/Eastern' ) api_date = eastern . normalize ( utc_time . astimezone ( eastern ) ) if api_date . hour < 10 : api_date -= timedelta ( days = 1 ) self . date = api_date | 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 != - 1 : self . logger . debug ( 'Located window.__data' ) end = content . find ( '};' , begin ) if end == - 1 : self . logger . debug ( 'Failed to locate end of javascript statement' ) else : json_data = self . load_json ( content [ begin : end + 1 ] . split ( '=' , 1 ) [ 1 ] . lstrip ( ) ) if json_data is not None : def _find_weather_data ( data ) : if isinstance ( data , dict ) : if 'Observation' in data and 'DailyForecast' in data : return data else : for key in data : ret = _find_weather_data ( data [ key ] ) if ret is not None : return ret return None weather_data = _find_weather_data ( json_data ) if weather_data is None : self . logger . debug ( 'Failed to locate weather data in the ' 'following data structure: %s' , json_data ) else : self . weather_data = weather_data return for line in content . splitlines ( ) : line = line . strip ( ) . rstrip ( ';' ) if line . startswith ( 'var adaptorParams' ) : weather_data = self . load_json ( line . split ( '=' , 1 ) [ 1 ] . lstrip ( ) ) if weather_data is not None : self . weather_data = weather_data return | 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_features ( ) : if feature . type == sensors . FEATURE_TEMP : try : name = chip . get_label ( feature ) max = get_subfeature_value ( feature , sensors . SUBFEATURE_TEMP_MAX ) current = get_subfeature_value ( feature , sensors . SUBFEATURE_TEMP_INPUT ) critical = get_subfeature_value ( feature , sensors . SUBFEATURE_TEMP_CRIT ) if critical : found_sensors . append ( Sensor ( name = name , current = current , maximum = max , critical = critical ) ) except sensors . SensorsException : continue return found_sensors | 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 < self . alert_temp else self . alert_color return { "full_text" : self . format . format ( temp = temp ) , "color" : color , } | 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 ( ) : return True return False | 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 : color = self . color_unread urgent = "true" format = self . format if unread > 1 : format = self . format_plural account_name = getattr ( self . backends [ self . current_backend ] , "account" , "No name" ) self . output = { "full_text" : format . format ( unread = unread , current_unread = current_unread , account = account_name ) , "urgent" : urgent , "color" : color , } | 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" : location = [ ] for x in value . split ( ", " ) : v , d = x . split ( " " ) location . append ( float ( v ) * ( 1 if d in "NE" else - 1 ) ) self . _location = ( location ) | 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 isinstance ( command , str ) : command = shlex . split ( command ) try : subprocess . Popen ( command , stdin = subprocess . DEVNULL , stdout = subprocess . DEVNULL , stderr = subprocess . DEVNULL ) except OSError : logging . getLogger ( "i3pystatus.core.command" ) . exception ( "" ) except subprocess . CalledProcessError : logging . getLogger ( "i3pystatus.core.command" ) . exception ( "" ) | 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 ( fixed_color ) else : colors . append ( color ) return colors | 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 return False | 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_click with m_click . lock : double = m_click . check_double ( button ) double_action = 'double%s' % action if double : action = double_action cb = getattr ( self , 'on_%s' % action , None ) double_handler = getattr ( self , 'on_%s' % double_action , None ) delay_execution = ( not double and double_handler ) if delay_execution : m_click . set_timer ( button , cb , ** kwargs ) else : self . __button_callback_handler ( button , cb , ** kwargs ) | 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 += "&" + s [ i + 1 ] return out if "full_text" in self . output . keys ( ) : self . output [ "full_text" ] = replace ( self . output [ "full_text" ] ) if "short_text" in self . output . keys ( ) : self . output [ "short_text" ] = replace ( self . output [ "short_text" ] ) | Replaces all ampersands in full_text and short_text attributes of self . output with & ; . |
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 hasattr ( self , 'required' ) and setting_name in getattr ( self , 'required' ) : setting = self . get_setting_from_keyring ( identifier , user_backend ) elif hasattr ( self , setting_name ) : setting = self . get_setting_from_keyring ( identifier , user_backend ) if setting : found_settings . update ( { setting_name : setting } ) return found_settings | 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 , * args , ** kwargs ) except Exception as e : log . exception ( e ) return self . modules . append ( Text ( color = "#FF0000" , text = "{i3py_mod}: Fatal Error - {ex}({msg})" . format ( i3py_mod = module , ex = e . __class__ . __name__ , msg = e ) ) ) | 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 = { "full_text" : answer [ "error" ] , "color" : "#FF0000" } return queue = answer [ "queue" ] self . status = queue [ "status" ] if self . is_paused ( ) : color = self . color_paused elif self . is_downloading ( ) : color = self . color_downloading else : color = self . color if self . is_downloading ( ) : full_text = self . format . format ( ** queue ) else : full_text = self . format_paused . format ( ** queue ) self . output = { "full_text" : full_text , "color" : color } | 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 . strerror ) except pytz . UnknownTimeZoneError : self . logger . error ( '/etc/localtime contains unrecognized tzinfo' ) return None def _etc_timezone ( ) : try : with open ( '/etc/timezone' , 'r' ) as fp : tzname = fp . read ( ) . strip ( ) return pytz . timezone ( tzname ) except OSError as exc : if exc . errno != errno . ENOENT : self . logger . error ( 'Unable to read from /etc/localtime: %s' , exc . strerror ) except pytz . UnknownTimeZoneError : self . logger . error ( '/etc/timezone contains unrecognized timezone \'%s\'' , tzname ) return None return _etc_localtime ( ) or _etc_timezone ( ) | 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' elif 'thunder' in condition_lc or 't-storm' in condition_lc : condition = 'Thunderstorm' elif 'snow' in condition_lc : condition = 'Snow' elif 'rain' in condition_lc or 'showers' in condition_lc : condition = 'Rainy' elif 'sunny' in condition_lc : condition = 'Sunny' elif 'clear' in condition_lc or 'fair' in condition_lc : condition = 'Fair' elif 'fog' in condition_lc : condition = 'Fog' return self . color_icons [ 'default' ] if condition not in self . color_icons else self . color_icons [ condition ] | 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 , usage = usage ) core_strings . append ( string ) core_strings = sorted ( core_strings ) return format_string . join ( core_strings ) | 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' , timeZone = 'utc' ) . execute ( ) self . events . clear ( ) for event in events_result . get ( 'items' , [ ] ) : self . events . append ( GoogleCalendarEvent ( event ) ) except HttpError as e : if e . resp . status in ( 500 , 503 ) : self . logger . warn ( "GoogleCalendar received %s while retrieving events" % e . resp . status ) else : raise | 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 = 0 prev = "" char = "" level = 0 while next < len ( string ) : prev = char char = string [ next ] next += 1 if prev != "\\" and char in TOKENS : token = TOKENS [ char ] ( ) token . index = next if char == "]" : level -= 1 token . level = level if char == "[" : level += 1 stack . append ( token ) else : if stack and isinstance ( stack [ - 1 ] , String ) : stack [ - 1 ] . string += char else : token = String ( char ) token . level = level stack . append ( token ) return stack def build_tree ( items , level = 0 ) : subtree = [ ] while items : nested = [ ] while items [ 0 ] . level > level : nested . append ( items . pop ( 0 ) ) if nested : subtree . append ( build_tree ( nested , level + 1 ) ) item = items . pop ( 0 ) if item . string : string = item . string if level == 0 : subtree . append ( string . format ( ** kwargs ) ) else : fields = re . findall ( r"({(\w+)[^}]*})" , string ) successful_fields = 0 for fieldspec , fieldname in fields : if kwargs . get ( fieldname , False ) : successful_fields += 1 if successful_fields == len ( fields ) : subtree . append ( string . format ( ** kwargs ) ) else : return [ ] return subtree def merge_tree ( items ) : return "" . join ( flatten ( items ) ) . replace ( r"\]" , "]" ) . replace ( r"\[" , "[" ) stack = build_stack ( string ) tree = build_tree ( stack , 0 ) return merge_tree ( tree ) | 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 = mx - mn if style == 'blocks' : bar = '_βββββ
βββ' bar_count = len ( bar ) - 1 if extent == 0 : graph = '_' * len ( values ) else : graph = '' . join ( bar [ int ( ( n - mn ) / extent * bar_count ) ] for n in values ) elif style in [ 'braille-fill' , 'braille-peak' , 'braille-snake' ] : vpad = values if len ( values ) % 2 == 0 else values + [ mn ] vscale = [ round ( 4 * ( vp - mn ) / extent ) for vp in vpad ] l = len ( vscale ) // 2 if 'fill' in style : vbits = [ [ 0 , 0x40 , 0x44 , 0x46 , 0x47 ] [ vs ] for vs in vscale ] elif 'peak' in style : vbits = [ [ 0 , 0x40 , 0x04 , 0x02 , 0x01 ] [ vs ] for vs in vscale ] else : assert ( 'snake' in style ) vb2 = [ vscale [ 0 ] ] + vscale + [ 0 ] vbits = [ ] for i in range ( 1 , l + 1 ) : c = 0 for j in range ( min ( vb2 [ i - 1 ] , vb2 [ i ] , vb2 [ i + 1 ] ) , vb2 [ i ] + 1 ) : c |= [ 0 , 0x40 , 0x04 , 0x02 , 0x01 ] [ j ] vbits . append ( c ) graph = '' for i in range ( 0 , l , 2 ) : b1 = vbits [ i ] b2 = vbits [ i + 1 ] if b2 & 0x40 : b2 = b2 - 0x30 b2 = b2 << 3 graph += chr ( 0x2800 + b1 + b2 ) else : raise NotImplementedError ( "Graph drawing style '%s' unimplemented." % style ) return graph | 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 ) return obj | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.