idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
51,500 | async def get ( self ) : shepherd = self . request . app . vmshepherd data = { 'presets' : { } , 'config' : shepherd . config } presets = await shepherd . preset_manager . list_presets ( ) runtime = shepherd . runtime_manager for name in presets : preset = shepherd . preset_manager . get_preset ( name ) data [ 'presets' ] [ name ] = { 'preset' : preset , 'vms' : preset . vms , 'runtime' : await runtime . get_preset_data ( name ) , 'vmshepherd_id' : shepherd . instance_id , 'now' : time . time ( ) } return data | Inject all preset data to Panel and Render a Home Page |
51,501 | def serialize ( dictionary ) : data = [ ] for key , value in dictionary . items ( ) : data . append ( '{0}="{1}"' . format ( key , value ) ) return ', ' . join ( data ) | Turn dictionary into argument like string . |
51,502 | def getAmountOfHostsConnected ( self , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getAmountOfHostsConnected" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetHostNumberOfEntries" , timeout = timeout ) return int ( results [ "NewHostNumberOfEntries" ] ) | Execute NewHostNumberOfEntries action to get the amount of known hosts . |
51,503 | def getHostDetailsByIndex ( self , index , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getHostDetailsByIndex" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetGenericHostEntry" , timeout = timeout , NewIndex = index ) return HostDetails ( results ) | Execute GetGenericHostEntry action to get detailed information s of a connected host . |
51,504 | def getHostDetailsByMACAddress ( self , macAddress , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getHostDetailsByMACAddress" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetSpecificHostEntry" , timeout = timeout , NewMACAddress = macAddress ) return HostDetails ( results , macAddress = macAddress ) | Get host details for a host specified by its MAC address . |
51,505 | def getEthernetInfo ( self , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getEthernetInfo" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetInfo" , timeout = timeout ) return EthernetInfo ( results ) | Execute GetInfo action to get information s about the Ethernet interface . |
51,506 | def getEthernetStatistic ( self , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "getEthernetStatistic" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetStatistics" , timeout = timeout ) return EthernetStatistic ( results ) | Execute GetStatistics action to get statistics of the Ethernet interface . |
51,507 | def setEnable ( self , status , lanInterfaceId = 1 , timeout = 1 ) : namespace = Lan . getServiceType ( "setEnable" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) if status : setStatus = 1 else : setStatus = 0 self . execute ( uri , namespace , "SetEnable" , timeout = timeout , NewEnable = setStatus ) | Set enable status for a LAN interface be careful you don t cut yourself off . |
51,508 | def authenticate ( self ) : if not hasattr ( self , 'client' ) : self . client = uservoice . Client ( self . subdomain , self . api_key , self . api_secret ) | authenticate with uservoice by creating a client . |
51,509 | def post_ticket ( self , title , body ) : ticket = { 'subject' : title , 'message' : body } response = self . client . post ( "/api/v1/tickets.json" , { 'email' : self . email , 'ticket' : ticket } ) [ 'ticket' ] bot . info ( response [ 'url' ] ) | post_ticket will post a ticket to the uservoice helpdesk |
51,510 | def _metadata ( image , datapath ) : metadata = { 'series_number' : 0 , 'datadir' : datapath } spacing = image . GetSpacing ( ) metadata [ 'voxelsize_mm' ] = [ spacing [ 2 ] , spacing [ 0 ] , spacing [ 1 ] , ] return metadata | Function which returns metadata dict . |
51,511 | def Get3DData ( self , datapath , qt_app = None , dataplus_format = True , gui = False , start = 0 , stop = None , step = 1 , convert_to_gray = True , series_number = None , use_economic_dtype = True , dicom_expected = None , ** kwargs ) : self . orig_datapath = datapath datapath = os . path . expanduser ( datapath ) if series_number is not None and type ( series_number ) != int : series_number = int ( series_number ) if not os . path . exists ( datapath ) : logger . error ( "Path '" + datapath + "' does not exist" ) return if qt_app is None and gui is True : from PyQt4 . QtGui import QApplication qt_app = QApplication ( sys . argv ) if type ( datapath ) is not str : datapath = str ( datapath ) datapath = os . path . normpath ( datapath ) self . start = start self . stop = stop self . step = step self . convert_to_gray = convert_to_gray self . series_number = series_number self . kwargs = kwargs self . qt_app = qt_app self . gui = gui if os . path . isfile ( datapath ) : logger . debug ( 'file read recognized' ) data3d , metadata = self . __ReadFromFile ( datapath ) elif os . path . exists ( datapath ) : logger . debug ( 'directory read recognized' ) data3d , metadata = self . __ReadFromDirectory ( datapath = datapath , dicom_expected = dicom_expected ) else : logger . error ( 'Data path {} not found' . format ( datapath ) ) if convert_to_gray : if len ( data3d . shape ) > 3 : data3d = data3d [ : , : , : , 0 ] if use_economic_dtype : data3d = self . __use_economic_dtype ( data3d ) if dataplus_format : logger . debug ( 'dataplus format' ) datap = metadata datap [ 'data3d' ] = data3d logger . debug ( 'datap keys () : ' + str ( datap . keys ( ) ) ) return datap else : return data3d , metadata | Returns 3D data and its metadata . |
51,512 | def __ReadFromDirectory ( self , datapath , dicom_expected = None ) : start = self . start stop = self . stop step = self . step kwargs = self . kwargs gui = self . gui if ( dicom_expected is not False ) and ( dcmr . is_dicom_dir ( datapath ) ) : logger . debug ( 'Dir - DICOM' ) logger . debug ( "dicom_expected " + str ( dicom_expected ) ) reader = dcmr . DicomReader ( datapath , series_number = self . series_number , gui = gui , ** kwargs ) data3d = reader . get_3Ddata ( start , stop , step ) metadata = reader . get_metaData ( ) metadata [ 'series_number' ] = reader . series_number metadata [ 'datadir' ] = datapath self . overlay_fcn = reader . get_overlay else : logger . debug ( 'Dir - Image sequence' ) logger . debug ( 'Getting list of readable files...' ) flist = [ ] try : import SimpleITK as Sitk except ImportError as e : logger . error ( "Unable to import SimpleITK. On Windows try version 1.0.1" ) for f in os . listdir ( datapath ) : try : Sitk . ReadImage ( os . path . join ( datapath , f ) ) except Exception as e : logger . warning ( "Cant load file: " + str ( f ) ) logger . warning ( e ) continue flist . append ( os . path . join ( datapath , f ) ) flist . sort ( ) logger . debug ( 'Reading image data...' ) image = Sitk . ReadImage ( flist ) logger . debug ( 'Getting numpy array from image data...' ) data3d = Sitk . GetArrayFromImage ( image ) metadata = _metadata ( image , datapath ) return data3d , metadata | This function is actually the ONE which reads 3D data from file |
51,513 | def _fix_sitk_bug ( path , metadata ) : ds = dicom . read_file ( path ) try : metadata [ "voxelsize_mm" ] [ 0 ] = ds . SpacingBetweenSlices except Exception as e : logger . warning ( "Read dicom 'SpacingBetweenSlices' failed: " , e ) return metadata | There is a bug in simple ITK for Z axis in 3D images . This is a fix . |
51,514 | def get_pid ( pid = None ) : if pid == None : if os . environ . get ( "PID" , None ) != None : pid = int ( os . environ . get ( "PID" ) ) else : pid = os . getpid ( ) print ( "pid is %s" % pid ) return pid | get_pid will return a pid of interest . First we use given variable then environmental variable PID and then PID of running process |
51,515 | def load_stored_routine ( self ) : try : self . _routine_name = os . path . splitext ( os . path . basename ( self . _source_filename ) ) [ 0 ] if os . path . exists ( self . _source_filename ) : if os . path . isfile ( self . _source_filename ) : self . _m_time = int ( os . path . getmtime ( self . _source_filename ) ) else : raise LoaderException ( "Unable to get mtime of file '{}'" . format ( self . _source_filename ) ) else : raise LoaderException ( "Source file '{}' does not exist" . format ( self . _source_filename ) ) if self . _pystratum_old_metadata : self . _pystratum_metadata = self . _pystratum_old_metadata load = self . _must_reload ( ) if load : self . __read_source_file ( ) self . __get_placeholders ( ) self . _get_designation_type ( ) self . _get_name ( ) self . __substitute_replace_pairs ( ) self . _load_routine_file ( ) if self . _designation_type == 'bulk_insert' : self . _get_bulk_insert_table_columns_info ( ) self . _get_routine_parameters_info ( ) self . __get_doc_block_parts_wrapper ( ) self . __save_shadow_copy ( ) self . _update_metadata ( ) return self . _pystratum_metadata except Exception as exception : self . _log_exception ( exception ) return False | Loads the stored routine into the instance of MySQL . |
51,516 | def __read_source_file ( self ) : with open ( self . _source_filename , 'r' , encoding = self . _routine_file_encoding ) as file : self . _routine_source_code = file . read ( ) self . _routine_source_code_lines = self . _routine_source_code . split ( "\n" ) | Reads the file with the source of the stored routine . |
51,517 | def __substitute_replace_pairs ( self ) : self . _set_magic_constants ( ) routine_source = [ ] i = 0 for line in self . _routine_source_code_lines : self . _replace [ '__LINE__' ] = "'%d'" % ( i + 1 ) for search , replace in self . _replace . items ( ) : tmp = re . findall ( search , line , re . IGNORECASE ) if tmp : line = line . replace ( tmp [ 0 ] , replace ) routine_source . append ( line ) i += 1 self . _routine_source_code = "\n" . join ( routine_source ) | Substitutes all replace pairs in the source of the stored routine . |
51,518 | def _log_exception ( self , exception ) : self . _io . error ( str ( exception ) . strip ( ) . split ( os . linesep ) ) | Logs an exception . |
51,519 | def __get_placeholders ( self ) : ret = True pattern = re . compile ( '(@[A-Za-z0-9_.]+(%(max-)?type)?@)' ) matches = pattern . findall ( self . _routine_source_code ) placeholders = [ ] if len ( matches ) != 0 : for tmp in matches : placeholder = tmp [ 0 ] if placeholder . lower ( ) not in self . _replace_pairs : raise LoaderException ( "Unknown placeholder '{0}' in file {1}" . format ( placeholder , self . _source_filename ) ) if placeholder not in placeholders : placeholders . append ( placeholder ) for placeholder in placeholders : if placeholder not in self . _replace : self . _replace [ placeholder ] = self . _replace_pairs [ placeholder . lower ( ) ] return ret | Extracts the placeholders from the stored routine source . |
51,520 | def _get_designation_type ( self ) : positions = self . _get_specification_positions ( ) if positions [ 0 ] != - 1 and positions [ 1 ] != - 1 : pattern = re . compile ( r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*' , re . IGNORECASE ) for line_number in range ( positions [ 0 ] , positions [ 1 ] + 1 ) : matches = pattern . findall ( self . _routine_source_code_lines [ line_number ] ) if matches : self . _designation_type = matches [ 0 ] [ 0 ] . lower ( ) tmp = str ( matches [ 0 ] [ 1 ] ) if self . _designation_type == 'bulk_insert' : n = re . compile ( r'([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_,]+)' , re . IGNORECASE ) info = n . findall ( tmp ) if not info : raise LoaderException ( 'Expected: -- type: bulk_insert <table_name> <columns> in file {0}' . format ( self . _source_filename ) ) self . _table_name = info [ 0 ] [ 0 ] self . _columns = str ( info [ 0 ] [ 1 ] ) . split ( ',' ) elif self . _designation_type == 'rows_with_key' or self . _designation_type == 'rows_with_index' : self . _columns = str ( matches [ 0 ] [ 1 ] ) . split ( ',' ) else : if matches [ 0 ] [ 1 ] : raise LoaderException ( 'Expected: -- type: {}' . format ( self . _designation_type ) ) if not self . _designation_type : raise LoaderException ( "Unable to find the designation type of the stored routine in file {0}" . format ( self . _source_filename ) ) | Extracts the designation type of the stored routine . |
51,521 | def _get_specification_positions ( self ) : start = - 1 for ( i , line ) in enumerate ( self . _routine_source_code_lines ) : if self . _is_start_of_stored_routine ( line ) : start = i end = - 1 for ( i , line ) in enumerate ( self . _routine_source_code_lines ) : if self . _is_start_of_stored_routine_body ( line ) : end = i - 1 return start , end | Returns a tuple with the start and end line numbers of the stored routine specification . |
51,522 | def __get_doc_block_lines ( self ) : line1 = None line2 = None i = 0 for line in self . _routine_source_code_lines : if re . match ( r'\s*/\*\*' , line ) : line1 = i if re . match ( r'\s*\*/' , line ) : line2 = i if self . _is_start_of_stored_routine ( line ) : break i += 1 return line1 , line2 | Returns the start and end line of the DOcBlock of the stored routine code . |
51,523 | def __get_doc_block_parts_wrapper ( self ) : self . __get_doc_block_parts_source ( ) helper = self . _get_data_type_helper ( ) parameters = list ( ) for parameter_info in self . _parameters : parameters . append ( { 'parameter_name' : parameter_info [ 'name' ] , 'python_type' : helper . column_type_to_python_type ( parameter_info ) , 'data_type_descriptor' : parameter_info [ 'data_type_descriptor' ] , 'description' : self . __get_parameter_doc_description ( parameter_info [ 'name' ] ) } ) self . _doc_block_parts_wrapper [ 'description' ] = self . _doc_block_parts_source [ 'description' ] self . _doc_block_parts_wrapper [ 'parameters' ] = parameters | Generates the DocBlock parts to be used by the wrapper generator . |
51,524 | def _update_metadata ( self ) : self . _pystratum_metadata [ 'routine_name' ] = self . _routine_name self . _pystratum_metadata [ 'designation' ] = self . _designation_type self . _pystratum_metadata [ 'table_name' ] = self . _table_name self . _pystratum_metadata [ 'parameters' ] = self . _parameters self . _pystratum_metadata [ 'columns' ] = self . _columns self . _pystratum_metadata [ 'fields' ] = self . _fields self . _pystratum_metadata [ 'column_types' ] = self . _columns_types self . _pystratum_metadata [ 'timestamp' ] = self . _m_time self . _pystratum_metadata [ 'replace' ] = self . _replace self . _pystratum_metadata [ 'pydoc' ] = self . _doc_block_parts_wrapper | Updates the metadata of the stored routine . |
51,525 | def _set_magic_constants ( self ) : real_path = os . path . realpath ( self . _source_filename ) self . _replace [ '__FILE__' ] = "'%s'" % real_path self . _replace [ '__ROUTINE__' ] = "'%s'" % self . _routine_name self . _replace [ '__DIR__' ] = "'%s'" % os . path . dirname ( real_path ) | Adds magic constants to replace list . |
51,526 | def _unset_magic_constants ( self ) : if '__FILE__' in self . _replace : del self . _replace [ '__FILE__' ] if '__ROUTINE__' in self . _replace : del self . _replace [ '__ROUTINE__' ] if '__DIR__' in self . _replace : del self . _replace [ '__DIR__' ] if '__LINE__' in self . _replace : del self . _replace [ '__LINE__' ] | Removes magic constants from current replace list . |
51,527 | def _print_sql_with_error ( self , sql , error_line ) : if os . linesep in sql : lines = sql . split ( os . linesep ) digits = math . ceil ( math . log ( len ( lines ) + 1 , 10 ) ) i = 1 for line in lines : if i == error_line : self . _io . text ( '<error>{0:{width}} {1}</error>' . format ( i , line , width = digits , ) ) else : self . _io . text ( '{0:{width}} {1}' . format ( i , line , width = digits , ) ) i += 1 else : self . _io . text ( sql ) | Writes a SQL statement with an syntax error to the output . The line where the error occurs is highlighted . |
51,528 | def list_filter ( lst , startswith = None , notstartswith = None , contain = None , notcontain = None ) : keeped = [ ] for item in lst : keep = False if startswith is not None : if item . startswith ( startswith ) : keep = True if notstartswith is not None : if not item . startswith ( notstartswith ) : keep = True if contain is not None : if contain in item : keep = True if notcontain is not None : if not notcontain in item : keep = True if keep : keeped . append ( item ) return keeped | Keep in list items according to filter parameters . |
51,529 | def split_dict ( dct , keys ) : if type ( dct ) == collections . OrderedDict : dict_in = collections . OrderedDict ( ) dict_out = collections . OrderedDict ( ) else : dict_in = { } dict_out = { } for key , value in dct . items : if key in keys : dict_in [ key ] = value else : dict_out [ key ] = value return dict_in , dict_out | Split dict into two subdicts based on keys . |
51,530 | def recursive_update ( d , u ) : for k , v in u . iteritems ( ) : if isinstance ( v , collections . Mapping ) : r = recursive_update ( d . get ( k , { } ) , v ) d [ k ] = r else : d [ k ] = u [ k ] return d | Dict recursive update . |
51,531 | def flatten_dict_join_keys ( dct , join_symbol = " " ) : return dict ( flatten_dict ( dct , join = lambda a , b : a + join_symbol + b ) ) | Flatten dict with defined key join symbol . |
51,532 | def list_contains ( list_of_strings , substring , return_true_false_array = False ) : key_tf = [ keyi . find ( substring ) != - 1 for keyi in list_of_strings ] if return_true_false_array : return key_tf keys_to_remove = list_of_strings [ key_tf ] return keys_to_remove | Get strings in list which contains substring . |
51,533 | def df_drop_duplicates ( df , ignore_key_pattern = "time" ) : keys_to_remove = list_contains ( df . keys ( ) , ignore_key_pattern ) ks = copy . copy ( list ( df . keys ( ) ) ) for key in keys_to_remove : ks . remove ( key ) df = df . drop_duplicates ( ks ) return df | Drop duplicates from dataframe ignore columns with keys containing defined pattern . |
51,534 | def ndarray_to_list_in_structure ( item , squeeze = True ) : tp = type ( item ) if tp == np . ndarray : if squeeze : item = item . squeeze ( ) item = item . tolist ( ) elif tp == list : for i in range ( len ( item ) ) : item [ i ] = ndarray_to_list_in_structure ( item [ i ] ) elif tp == dict : for lab in item : item [ lab ] = ndarray_to_list_in_structure ( item [ lab ] ) return item | Change ndarray in structure of lists and dicts into lists . |
51,535 | def dict_find_key ( dd , value ) : key = next ( key for key , val in dd . items ( ) if val == value ) return key | Find first suitable key in dict . |
51,536 | def sort_list_of_dicts ( lst_of_dct , keys , reverse = False , ** sort_args ) : if type ( keys ) != list : keys = [ keys ] lst_of_dct . sort ( key = lambda x : [ ( ( False , x [ key ] ) if key in x else ( True , 0 ) ) for key in keys ] , reverse = reverse , ** sort_args ) return lst_of_dct | Sort list of dicts by one or multiple keys . |
51,537 | def ordered_dict_to_dict ( config ) : if type ( config ) == collections . OrderedDict : config = dict ( config ) if type ( config ) == list : for i in range ( 0 , len ( config ) ) : config [ i ] = ordered_dict_to_dict ( config [ i ] ) elif type ( config ) == dict : for key in config : config [ key ] = ordered_dict_to_dict ( config [ key ] ) return config | Use dict instead of ordered dict in structure . |
51,538 | def _get_option ( config , supplement , section , option , fallback = None ) : if supplement : return_value = supplement . get ( section , option , fallback = config . get ( section , option , fallback = fallback ) ) else : return_value = config . get ( section , option , fallback = fallback ) if fallback is None and return_value is None : raise KeyError ( "Option '{0!s}' is not found in section '{1!s}'." . format ( option , section ) ) return return_value | Reads an option for a configuration file . |
51,539 | def _read_configuration ( config_filename ) : config = ConfigParser ( ) config . read ( config_filename ) if 'supplement' in config [ 'database' ] : path = os . path . dirname ( config_filename ) + '/' + config . get ( 'database' , 'supplement' ) config_supplement = ConfigParser ( ) config_supplement . read ( path ) else : config_supplement = None return config , config_supplement | Checks the supplement file . |
51,540 | def record_asciinema ( ) : import asciinema . config as aconfig from asciinema . api import Api cfg = aconfig . load ( ) api = Api ( cfg . api_url , os . environ . get ( "USER" ) , cfg . install_id ) recorder = HelpMeRecord ( api ) code = recorder . execute ( ) if code == 0 and os . path . exists ( recorder . filename ) : return recorder . filename print ( 'Problem generating %s, return code %s' % ( recorder . filename , code ) ) | a wrapper around generation of an asciinema . api . Api and a custom recorder to pull out the input arguments to the Record from argparse . The function generates a filename in advance and a return code so we can check the final status . |
51,541 | def sendWakeOnLan ( self , macAddress , lanInterfaceId = 1 , timeout = 1 ) : namespace = Fritz . getServiceType ( "sendWakeOnLan" ) + str ( lanInterfaceId ) uri = self . getControlURL ( namespace ) self . execute ( uri , namespace , "X_AVM-DE_WakeOnLANByMACAddress" , timeout = timeout , NewMACAddress = macAddress ) | Send a wake up package to a device specified by its MAC address . |
51,542 | def doUpdate ( self , timeout = 1 ) : namespace = Fritz . getServiceType ( "doUpdate" ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "X_AVM-DE_DoUpdate" , timeout = timeout ) return results [ "NewUpgradeAvailable" ] , results [ "NewX_AVM-DE_UpdateState" ] | Do a software update of the Fritz Box if available . |
51,543 | def isOptimizedForIPTV ( self , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Fritz . getServiceType ( "isOptimizedForIPTV" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "X_AVM-DE_GetIPTVOptimized" , timeout = timeout ) return bool ( int ( results [ "NewX_AVM-DE_IPTVoptimize" ] ) ) | Return if the Wifi interface is optimized for IP TV |
51,544 | def setOptimizedForIPTV ( self , status , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Fritz . getServiceType ( "setOptimizedForIPTV" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) if status : setStatus = 1 else : setStatus = 0 arguments = { "timeout" : timeout , "NewX_AVM-DE_IPTVoptimize" : setStatus } self . execute ( uri , namespace , "X_AVM-DE_SetIPTVOptimized" , ** arguments ) | Set if the Wifi interface is optimized for IP TV |
51,545 | def getCallList ( self , timeout = 1 ) : namespace = Fritz . getServiceType ( "getCallList" ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetCallList" ) proxies = { } if self . httpProxy : proxies = { "https" : self . httpProxy } if self . httpsProxy : proxies = { "http" : self . httpsProxy } request = requests . get ( results [ "NewCallListURL" ] , proxies = proxies , timeout = float ( timeout ) ) if request . status_code != 200 : errorStr = DeviceTR64 . _extractErrorString ( request ) raise ValueError ( 'Could not get CPE definitions "' + results [ "NewCallListURL" ] + '" : ' + str ( request . status_code ) + ' - ' + request . reason + " -- " + errorStr ) try : root = ET . fromstring ( request . text . encode ( 'utf-8' ) ) except Exception as e : raise ValueError ( "Could not parse call list '" + results [ "NewCallListURL" ] + "': " + str ( e ) ) calls = [ ] for child in root . getchildren ( ) : if child . tag . lower ( ) == "call" : callParameters = { } for callChild in child . getchildren ( ) : callParameters [ callChild . tag ] = callChild . text calls . append ( callParameters ) return calls | Get the list of phone calls made |
51,546 | def upload_to_pypi ( ) : x = prompt ( "Are you sure to upload the current version to pypi?" ) if not x or not x . lower ( ) in [ "y" , "yes" ] : return local ( "rm -rf dist" ) local ( "python setup.py sdist" ) version = _get_cur_version ( ) fn = "RPIO-%s.tar.gz" % version put ( "dist/%s" % fn , "/tmp/" ) with cd ( "/tmp" ) : run ( "tar -xf /tmp/%s" % fn ) with cd ( "/tmp/RPIO-%s" % version ) : run ( "python2.6 setup.py bdist_egg upload" ) run ( "python2.7 setup.py bdist_egg upload" ) run ( "python3.2 setup.py bdist_egg upload" ) local ( "python setup.py sdist upload" ) | Upload sdist and bdist_eggs to pypi |
51,547 | def _threaded_callback ( callback , * args ) : t = Thread ( target = callback , args = args ) t . daemon = True t . start ( ) | Internal wrapper to start a callback in threaded mode . Using the daemon mode to not block the main thread from exiting . |
51,548 | def del_interrupt_callback ( self , gpio_id ) : debug ( "- removing interrupts on gpio %s" % gpio_id ) gpio_id = _GPIO . channel_to_gpio ( gpio_id ) fileno = self . _map_gpioid_to_fileno [ gpio_id ] self . _epoll . unregister ( fileno ) f = self . _map_fileno_to_file [ fileno ] del self . _map_fileno_to_file [ fileno ] del self . _map_fileno_to_gpioid [ fileno ] del self . _map_fileno_to_options [ fileno ] del self . _map_gpioid_to_fileno [ gpio_id ] del self . _map_gpioid_to_callbacks [ gpio_id ] f . close ( ) | Delete all interrupt callbacks from a certain gpio |
51,549 | def _handle_interrupt ( self , fileno , val ) : val = int ( val ) edge = self . _map_fileno_to_options [ fileno ] [ "edge" ] if ( edge == 'rising' and val == 0 ) or ( edge == 'falling' and val == 1 ) : return debounce = self . _map_fileno_to_options [ fileno ] [ "debounce_timeout_s" ] if debounce : t = time . time ( ) t_last = self . _map_fileno_to_options [ fileno ] [ "interrupt_last" ] if t - t_last < debounce : debug ( "- don't start interrupt callback due to debouncing" ) return self . _map_fileno_to_options [ fileno ] [ "interrupt_last" ] = t gpio_id = self . _map_fileno_to_gpioid [ fileno ] if gpio_id in self . _map_gpioid_to_callbacks : for cb in self . _map_gpioid_to_callbacks [ gpio_id ] : cb ( gpio_id , val ) | Internally distributes interrupts to all attached callbacks |
51,550 | def cleanup_tcpsockets ( self ) : for fileno in self . _tcp_client_sockets . keys ( ) : self . close_tcp_client ( fileno ) for fileno , items in self . _tcp_server_sockets . items ( ) : socket , cb = items debug ( "- _cleanup server socket connection (fd %s)" % fileno ) self . _epoll . unregister ( fileno ) socket . close ( ) self . _tcp_server_sockets = { } | Closes all TCP connections and then the socket servers |
51,551 | def add_channel_pulse ( dma_channel , gpio , start , width ) : return _PWM . add_channel_pulse ( dma_channel , gpio , start , width ) | Add a pulse for a specific GPIO to a dma channel subcycle . start and width are multiples of the pulse - width increment granularity . |
51,552 | def unique ( _list ) : ret = [ ] for item in _list : if item not in ret : ret . append ( item ) return ret | Makes the list have unique items only and maintains the order |
51,553 | def preprocess_query ( query ) : query = re . sub ( r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`' , r'\1' , query , flags = re . IGNORECASE ) query = re . sub ( r'`([^`]+)`\.`([^`]+)`' , r'\1.\2' , query ) return query | Perform initial query cleanup |
51,554 | def normalize_likes ( sql ) : sql = sql . replace ( '%' , '' ) sql = re . sub ( r"LIKE '[^\']+'" , 'LIKE X' , sql ) matches = re . finditer ( r'(or|and) [^\s]+ LIKE X' , sql , flags = re . IGNORECASE ) matches = [ match . group ( 0 ) for match in matches ] if matches else None if matches : for match in set ( matches ) : sql = re . sub ( r'(\s?' + re . escape ( match ) + ')+' , ' ' + match + ' ...' , sql ) return sql | Normalize and wrap LIKE statements |
51,555 | def generalize_sql ( sql ) : if sql is None : return None sql = re . sub ( r'\s{2,}' , ' ' , sql ) sql = remove_comments_from_sql ( sql ) sql = normalize_likes ( sql ) sql = re . sub ( r"\\\\" , '' , sql ) sql = re . sub ( r"\\'" , '' , sql ) sql = re . sub ( r'\\"' , '' , sql ) sql = re . sub ( r"'[^\']*'" , 'X' , sql ) sql = re . sub ( r'"[^\"]*"' , 'X' , sql ) sql = re . sub ( r'\s+' , ' ' , sql ) sql = re . sub ( r'-?[0-9]+' , 'N' , sql ) sql = re . sub ( r' (IN|VALUES)\s*\([^,]+,[^)]+\)' , ' \\1 (XYZ)' , sql , flags = re . IGNORECASE ) return sql . strip ( ) | Removes most variables from an SQL query and replaces them with X or N for numbers . |
51,556 | def deblur_system_call ( params , input_fp ) : logger = logging . getLogger ( __name__ ) logger . debug ( '[%s] deblur system call params %s, input_fp %s' % ( mp . current_process ( ) . name , params , input_fp ) ) script_name = "deblur" script_subprogram = "workflow" command = [ script_name , script_subprogram , '--seqs-fp' , input_fp , '--is-worker-thread' , '--keep-tmp-files' ] command . extend ( params ) logger . debug ( '[%s] running command %s' % ( mp . current_process ( ) . name , command ) ) return _system_call ( command ) | Build deblur command for subprocess . |
51,557 | def run_functor ( functor , * args , ** kwargs ) : try : return functor ( * args , ** kwargs ) except Exception : raise Exception ( "" . join ( traceback . format_exception ( * sys . exc_info ( ) ) ) ) | Given a functor run it and return its result . We can use this with multiprocessing . map and map it over a list of job functors to do them . |
51,558 | def parallel_deblur ( inputs , params , pos_ref_db_fp , neg_ref_dp_fp , jobs_to_start = 1 ) : logger = logging . getLogger ( __name__ ) logger . info ( 'parallel deblur started for %d inputs' % len ( inputs ) ) remove_param_list = [ '-O' , '--jobs-to-start' , '--seqs-fp' , '--pos-ref-db-fp' , '--neg-ref-db-fp' ] skipnext = False newparams = [ ] for carg in params [ 2 : ] : if skipnext : skipnext = False continue if carg in remove_param_list : skipnext = True continue newparams . append ( carg ) if pos_ref_db_fp : new_pos_ref_db_fp = ',' . join ( pos_ref_db_fp ) newparams . append ( '--pos-ref-db-fp' ) newparams . append ( new_pos_ref_db_fp ) if neg_ref_dp_fp : new_neg_ref_db_fp = ',' . join ( neg_ref_dp_fp ) newparams . append ( '--neg-ref-db-fp' ) newparams . append ( new_neg_ref_db_fp ) logger . debug ( 'ready for functor %s' % newparams ) functor = partial ( run_functor , deblur_system_call , newparams ) logger . debug ( 'ready for pool %d jobs' % jobs_to_start ) pool = mp . Pool ( processes = jobs_to_start ) logger . debug ( 'almost running...' ) for stdout , stderr , es in pool . map ( functor , inputs ) : if es != 0 : raise RuntimeError ( "stdout: %s\nstderr: %s\nexit: %d" % ( stdout , stderr , es ) ) | Dispatch execution over a pool of processors |
51,559 | def trim_seqs ( input_seqs , trim_len , left_trim_len ) : logger = logging . getLogger ( __name__ ) okseqs = 0 totseqs = 0 if trim_len < - 1 : raise ValueError ( "Invalid trim_len: %d" % trim_len ) for label , seq in input_seqs : totseqs += 1 if trim_len == - 1 : okseqs += 1 yield label , seq elif len ( seq ) >= trim_len : okseqs += 1 yield label , seq [ left_trim_len : trim_len ] if okseqs < 0.01 * totseqs : logger = logging . getLogger ( __name__ ) errmsg = 'Vast majority of sequences (%d / %d) are shorter ' 'than the trim length (%d). ' 'Are you using the correct -t trim length?' % ( totseqs - okseqs , totseqs , trim_len ) logger . warn ( errmsg ) warnings . warn ( errmsg , UserWarning ) else : logger . debug ( 'trimmed to length %d (%d / %d remaining)' % ( trim_len , okseqs , totseqs ) ) | Trim FASTA sequences to specified length . |
51,560 | def dereplicate_seqs ( seqs_fp , output_fp , min_size = 2 , use_log = False , threads = 1 ) : logger = logging . getLogger ( __name__ ) logger . info ( 'dereplicate seqs file %s' % seqs_fp ) log_name = "%s.log" % output_fp params = [ 'vsearch' , '--derep_fulllength' , seqs_fp , '--output' , output_fp , '--sizeout' , '--fasta_width' , '0' , '--minuniquesize' , str ( min_size ) , '--quiet' , '--threads' , str ( threads ) ] if use_log : params . extend ( [ '--log' , log_name ] ) sout , serr , res = _system_call ( params ) if not res == 0 : logger . error ( 'Problem running vsearch dereplication on file %s' % seqs_fp ) logger . debug ( 'parameters used:\n%s' % params ) logger . debug ( 'stdout: %s' % sout ) logger . debug ( 'stderr: %s' % serr ) return | Dereplicate FASTA sequences and remove singletons using VSEARCH . |
51,561 | def build_index_sortmerna ( ref_fp , working_dir ) : logger = logging . getLogger ( __name__ ) logger . info ( 'build_index_sortmerna files %s to' ' dir %s' % ( ref_fp , working_dir ) ) all_db = [ ] for db in ref_fp : fasta_dir , fasta_filename = split ( db ) index_basename = splitext ( fasta_filename ) [ 0 ] db_output = join ( working_dir , index_basename ) logger . debug ( 'processing file %s into location %s' % ( db , db_output ) ) params = [ 'indexdb_rna' , '--ref' , '%s,%s' % ( db , db_output ) , '--tmpdir' , working_dir ] sout , serr , res = _system_call ( params ) if not res == 0 : logger . error ( 'Problem running indexdb_rna on file %s to dir %s. ' 'database not indexed' % ( db , db_output ) ) logger . debug ( 'stdout: %s' % sout ) logger . debug ( 'stderr: %s' % serr ) logger . critical ( 'execution halted' ) raise RuntimeError ( 'Cannot index database file %s' % db ) logger . debug ( 'file %s indexed' % db ) all_db . append ( db_output ) return all_db | Build a SortMeRNA index for all reference databases . |
51,562 | def filter_minreads_samples_from_table ( table , minreads = 1 , inplace = True ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'filter_minreads_started. minreads=%d' % minreads ) samp_sum = table . sum ( axis = 'sample' ) samp_ids = table . ids ( axis = 'sample' ) bad_samples = samp_ids [ samp_sum < minreads ] if len ( bad_samples ) > 0 : logger . warn ( 'removed %d samples with reads per sample<%d' % ( len ( bad_samples ) , minreads ) ) table = table . filter ( bad_samples , axis = 'sample' , inplace = inplace , invert = True ) else : logger . debug ( 'all samples contain > %d reads' % minreads ) return table | Filter samples from biom table that have less than minreads reads total |
51,563 | def fasta_from_biom ( table , fasta_file_name ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'saving biom table sequences to fasta file %s' % fasta_file_name ) with open ( fasta_file_name , 'w' ) as f : for cseq in table . ids ( axis = 'observation' ) : f . write ( '>%s\n%s\n' % ( cseq , cseq ) ) logger . info ( 'saved biom table sequences to fasta file %s' % fasta_file_name ) | Save sequences from a biom table to a fasta file |
51,564 | def remove_artifacts_from_biom_table ( table_filename , fasta_filename , ref_fp , biom_table_dir , ref_db_fp , threads = 1 , verbose = False , sim_thresh = None , coverage_thresh = None ) : logger = logging . getLogger ( __name__ ) logger . info ( 'getting 16s sequences from the biom table' ) clean_fp , num_seqs_left , tmp_files = remove_artifacts_seqs ( fasta_filename , ref_fp , working_dir = biom_table_dir , ref_db_fp = ref_db_fp , negate = False , threads = threads , verbose = verbose , sim_thresh = sim_thresh , coverage_thresh = coverage_thresh ) if clean_fp is None : logger . warn ( "No clean sequences in %s" % fasta_filename ) return tmp_files logger . debug ( 'removed artifacts from sequences input %s' ' to output %s' % ( fasta_filename , clean_fp ) ) good_seqs = { s for _ , s in sequence_generator ( clean_fp ) } logger . debug ( 'loaded %d sequences from cleaned biom table' ' fasta file' % len ( good_seqs ) ) logger . debug ( 'loading biom table %s' % table_filename ) table = load_table ( table_filename ) artifact_table = table . filter ( list ( good_seqs ) , axis = 'observation' , inplace = False , invert = True ) filter_minreads_samples_from_table ( artifact_table ) output_nomatch_fp = join ( biom_table_dir , 'reference-non-hit.biom' ) write_biom_table ( artifact_table , output_nomatch_fp ) logger . info ( 'wrote artifact only filtered biom table to %s' % output_nomatch_fp ) output_nomatch_fasta_fp = join ( biom_table_dir , 'reference-non-hit.seqs.fa' ) fasta_from_biom ( artifact_table , output_nomatch_fasta_fp ) table . filter ( list ( good_seqs ) , axis = 'observation' ) filter_minreads_samples_from_table ( table ) output_fp = join ( biom_table_dir , 'reference-hit.biom' ) write_biom_table ( table , output_fp ) logger . info ( 'wrote 16s filtered biom table to %s' % output_fp ) output_match_fasta_fp = join ( biom_table_dir , 'reference-hit.seqs.fa' ) fasta_from_biom ( table , output_match_fasta_fp ) tmp_files . append ( clean_fp ) return tmp_files | Remove artifacts from a biom table using SortMeRNA |
51,565 | def remove_artifacts_seqs ( seqs_fp , ref_fp , working_dir , ref_db_fp , negate = False , threads = 1 , verbose = False , sim_thresh = None , coverage_thresh = None ) : logger = logging . getLogger ( __name__ ) logger . info ( 'remove_artifacts_seqs file %s' % seqs_fp ) if stat ( seqs_fp ) . st_size == 0 : logger . warn ( 'file %s has size 0, continuing' % seqs_fp ) return None , 0 , [ ] if coverage_thresh is None : if negate : coverage_thresh = 0.95 * 100 else : coverage_thresh = 0.5 * 100 if sim_thresh is None : if negate : sim_thresh = 0.95 * 100 else : sim_thresh = 0.65 * 100 bitscore_thresh = 0.65 output_fp = join ( working_dir , "%s.no_artifacts" % basename ( seqs_fp ) ) blast_output = join ( working_dir , '%s.sortmerna' % basename ( seqs_fp ) ) aligned_seq_ids = set ( ) for i , db in enumerate ( ref_fp ) : logger . debug ( 'running on ref_fp %s working dir %s refdb_fp %s seqs %s' % ( db , working_dir , ref_db_fp [ i ] , seqs_fp ) ) params = [ 'sortmerna' , '--reads' , seqs_fp , '--ref' , '%s,%s' % ( db , ref_db_fp [ i ] ) , '--aligned' , blast_output , '--blast' , '3' , '--best' , '1' , '--print_all_reads' , '-v' , '-e' , '100' ] sout , serr , res = _system_call ( params ) if not res == 0 : logger . error ( 'sortmerna error on file %s' % seqs_fp ) logger . error ( 'stdout : %s' % sout ) logger . error ( 'stderr : %s' % serr ) return output_fp , 0 , [ ] blast_output_filename = '%s.blast' % blast_output with open ( blast_output_filename , 'r' ) as bfl : for line in bfl : line = line . strip ( ) . split ( '\t' ) if line [ 1 ] == '*' : continue if ( float ( line [ 2 ] ) >= sim_thresh ) and ( float ( line [ 13 ] ) >= coverage_thresh ) and ( float ( line [ 11 ] ) >= bitscore_thresh * len ( line [ 0 ] ) ) : aligned_seq_ids . add ( line [ 0 ] ) if negate : def op ( x ) : return x not in aligned_seq_ids else : def op ( x ) : return x in aligned_seq_ids totalseqs = 0 okseqs = 0 badseqs = 0 with open ( output_fp , 'w' ) as out_f : for label , seq in sequence_generator ( seqs_fp ) : totalseqs += 1 label = label . split ( ) [ 0 ] if op ( label ) : out_f . write ( ">%s\n%s\n" % ( label , seq ) ) okseqs += 1 else : badseqs += 1 logger . info ( 'total sequences %d, passing sequences %d, ' 'failing sequences %d' % ( totalseqs , okseqs , badseqs ) ) return output_fp , okseqs , [ blast_output_filename ] | Remove artifacts from FASTA file using SortMeRNA . |
51,566 | def multiple_sequence_alignment ( seqs_fp , threads = 1 ) : logger = logging . getLogger ( __name__ ) logger . info ( 'multiple_sequence_alignment seqs file %s' % seqs_fp ) if threads == 0 : threads = - 1 if stat ( seqs_fp ) . st_size == 0 : logger . warning ( 'msa failed. file %s has no reads' % seqs_fp ) return None msa_fp = seqs_fp + '.msa' params = [ 'mafft' , '--quiet' , '--preservecase' , '--parttree' , '--auto' , '--thread' , str ( threads ) , seqs_fp ] sout , serr , res = _system_call ( params , stdoutfilename = msa_fp ) if not res == 0 : logger . info ( 'msa failed for file %s (maybe only 1 read?)' % seqs_fp ) logger . debug ( 'stderr : %s' % serr ) return None return msa_fp | Perform multiple sequence alignment on FASTA file using MAFFT . |
51,567 | def split_sequence_file_on_sample_ids_to_files ( seqs , outdir ) : logger = logging . getLogger ( __name__ ) logger . info ( 'split_sequence_file_on_sample_ids_to_files' ' for file %s into dir %s' % ( seqs , outdir ) ) outputs = { } for bits in sequence_generator ( seqs ) : sample = sample_id_from_read_id ( bits [ 0 ] ) if sample not in outputs : outputs [ sample ] = open ( join ( outdir , sample + '.fasta' ) , 'w' ) outputs [ sample ] . write ( ">%s\n%s\n" % ( bits [ 0 ] , bits [ 1 ] ) ) for sample in outputs : outputs [ sample ] . close ( ) logger . info ( 'split to %d files' % len ( outputs ) ) | Split FASTA file on sample IDs . |
51,568 | def write_biom_table ( table , biom_fp ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'write_biom_table to file %s' % biom_fp ) with biom_open ( biom_fp , 'w' ) as f : table . to_hdf5 ( h5grp = f , generated_by = "deblur" ) logger . debug ( 'wrote to BIOM file %s' % biom_fp ) | Write BIOM table to file . |
51,569 | def get_files_for_table ( input_dir , file_end = '.trim.derep.no_artifacts' '.msa.deblur.no_chimeras' ) : logger = logging . getLogger ( __name__ ) logger . debug ( 'get_files_for_table input dir %s, ' 'file-ending %s' % ( input_dir , file_end ) ) names = [ ] for cfile in glob ( join ( input_dir , "*%s" % file_end ) ) : if not isfile ( cfile ) : continue sample_id = basename ( cfile ) [ : - len ( file_end ) ] sample_id = os . path . splitext ( sample_id ) [ 0 ] names . append ( ( cfile , sample_id ) ) logger . debug ( 'found %d files' % len ( names ) ) return names | Get a list of files to add to the output table |
51,570 | def launch_workflow ( seqs_fp , working_dir , mean_error , error_dist , indel_prob , indel_max , trim_length , left_trim_length , min_size , ref_fp , ref_db_fp , threads_per_sample = 1 , sim_thresh = None , coverage_thresh = None ) : logger = logging . getLogger ( __name__ ) logger . info ( '--------------------------------------------------------' ) logger . info ( 'launch_workflow for file %s' % seqs_fp ) output_trim_fp = join ( working_dir , "%s.trim" % basename ( seqs_fp ) ) with open ( output_trim_fp , 'w' ) as out_f : for label , seq in trim_seqs ( input_seqs = sequence_generator ( seqs_fp ) , trim_len = trim_length , left_trim_len = left_trim_length ) : out_f . write ( ">%s\n%s\n" % ( label , seq ) ) output_derep_fp = join ( working_dir , "%s.derep" % basename ( output_trim_fp ) ) dereplicate_seqs ( seqs_fp = output_trim_fp , output_fp = output_derep_fp , min_size = min_size , threads = threads_per_sample ) output_artif_fp , num_seqs_left , _ = remove_artifacts_seqs ( seqs_fp = output_derep_fp , ref_fp = ref_fp , working_dir = working_dir , ref_db_fp = ref_db_fp , negate = True , threads = threads_per_sample , sim_thresh = sim_thresh ) if not output_artif_fp : warnings . warn ( 'Problem removing artifacts from file %s' % seqs_fp , UserWarning ) logger . warning ( 'remove artifacts failed, aborting' ) return None if num_seqs_left > 1 : output_msa_fp = join ( working_dir , "%s.msa" % basename ( output_artif_fp ) ) alignment = multiple_sequence_alignment ( seqs_fp = output_artif_fp , threads = threads_per_sample ) if not alignment : warnings . warn ( 'Problem performing multiple sequence alignment ' 'on file %s' % seqs_fp , UserWarning ) logger . warning ( 'msa failed. aborting' ) return None elif num_seqs_left == 1 : output_msa_fp = output_artif_fp else : err_msg = ( 'No sequences left after artifact removal in ' 'file %s' % seqs_fp ) warnings . warn ( err_msg , UserWarning ) logger . warning ( err_msg ) return None output_deblur_fp = join ( working_dir , "%s.deblur" % basename ( output_msa_fp ) ) with open ( output_deblur_fp , 'w' ) as f : seqs = deblur ( sequence_generator ( output_msa_fp ) , mean_error , error_dist , indel_prob , indel_max ) if seqs is None : warnings . warn ( 'multiple sequence alignment file %s contains ' 'no sequences' % output_msa_fp , UserWarning ) logger . warn ( 'no sequences returned from deblur for file %s' % output_msa_fp ) return None for s in seqs : s . sequence = s . sequence . replace ( '-' , '' ) f . write ( s . to_fasta ( ) ) output_no_chimeras_fp = remove_chimeras_denovo_from_seqs ( output_deblur_fp , working_dir , threads = threads_per_sample ) logger . info ( 'finished processing file' ) return output_no_chimeras_fp | Launch full deblur workflow for a single post split - libraries fasta file |
51,571 | def start_log ( level = logging . DEBUG , filename = None ) : if filename is None : tstr = time . ctime ( ) tstr = tstr . replace ( ' ' , '.' ) tstr = tstr . replace ( ':' , '.' ) filename = 'deblur.log.%s' % tstr logging . basicConfig ( filename = filename , level = level , format = '%(levelname)s(%(thread)d)' '%(asctime)s:%(message)s' ) logger = logging . getLogger ( __name__ ) logger . info ( '*************************' ) logger . info ( 'deblurring started' ) | start the logger for the run |
51,572 | def get_sequences ( input_seqs ) : try : seqs = [ Sequence ( id , seq ) for id , seq in input_seqs ] except Exception : seqs = [ ] if len ( seqs ) == 0 : logger = logging . getLogger ( __name__ ) logger . warn ( 'No sequences found in fasta file!' ) return None aligned_lengths = set ( s . length for s in seqs ) unaligned_lengths = set ( s . unaligned_length for s in seqs ) if len ( aligned_lengths ) != 1 or len ( unaligned_lengths ) != 1 : raise ValueError ( "Not all sequence have the same length. Aligned lengths: %s, " "sequence lengths: %s" % ( ", " . join ( map ( str , aligned_lengths ) ) , ", " . join ( map ( str , unaligned_lengths ) ) ) ) seqs = sorted ( seqs , key = attrgetter ( 'frequency' ) , reverse = True ) return seqs | Returns a list of Sequences |
51,573 | def deblur ( input_seqs , mean_error = 0.005 , error_dist = None , indel_prob = 0.01 , indel_max = 3 ) : logger = logging . getLogger ( __name__ ) if error_dist is None : error_dist = get_default_error_profile ( ) logger . debug ( 'Using error profile %s' % error_dist ) seqs = get_sequences ( input_seqs ) if seqs is None : logger . warn ( 'no sequences deblurred' ) return None logger . info ( 'deblurring %d sequences' % len ( seqs ) ) mod_factor = pow ( ( 1 - mean_error ) , seqs [ 0 ] . unaligned_length ) error_dist = np . array ( error_dist ) / mod_factor max_h_dist = len ( error_dist ) - 1 for seq_i in seqs : if seq_i . frequency <= 0 : continue num_err = error_dist * seq_i . frequency if num_err [ 1 ] < 0.1 : continue seq_i_len = len ( seq_i . sequence . rstrip ( '-' ) ) for seq_j in seqs : if seq_i == seq_j : continue h_dist = np . count_nonzero ( np . not_equal ( seq_i . np_sequence , seq_j . np_sequence ) ) if h_dist > max_h_dist : continue length = min ( seq_i_len , len ( seq_j . sequence . rstrip ( '-' ) ) ) sub_seq_i = seq_i . np_sequence [ : length ] sub_seq_j = seq_j . np_sequence [ : length ] mask = ( sub_seq_i != sub_seq_j ) mut_is_indel = np . logical_or ( sub_seq_i [ mask ] == 4 , sub_seq_j [ mask ] == 4 ) num_indels = mut_is_indel . sum ( ) if num_indels > 0 : h_dist = np . count_nonzero ( np . not_equal ( seq_i . np_sequence [ : length ] , seq_j . np_sequence [ : length ] ) ) num_substitutions = h_dist - num_indels correction_value = num_err [ num_substitutions ] if num_indels > indel_max : correction_value = 0 elif num_indels > 0 : correction_value = correction_value * indel_prob seq_j . frequency -= correction_value result = [ s for s in seqs if round ( s . frequency ) > 0 ] logger . info ( '%d unique sequences left following deblurring' % len ( result ) ) return result | Deblur the reads |
51,574 | def to_fasta ( self ) : prefix , suffix = re . split ( '(?<=size=)\w+' , self . label , maxsplit = 1 ) new_count = int ( round ( self . frequency ) ) new_label = "%s%d%s" % ( prefix , new_count , suffix ) return ">%s\n%s\n" % ( new_label , self . sequence ) | Returns a string with the sequence in fasta format |
51,575 | def render_select2_options_code ( self , options , id_ ) : output = [ ] for key , value in options . items ( ) : if isinstance ( value , ( dict , list ) ) : value = json . dumps ( value ) output . append ( "data-{name}='{value}'" . format ( name = key , value = mark_safe ( value ) ) ) return mark_safe ( ' ' . join ( output ) ) | Render options for select2 . |
51,576 | def render_js_code ( self , id_ , * args , ** kwargs ) : if id_ : options = self . render_select2_options_code ( dict ( self . get_options ( ) ) , id_ ) return mark_safe ( self . html . format ( id = id_ , options = options ) ) return u'' | Render html container for Select2 widget with options . |
51,577 | def render ( self , name , value , attrs = None , ** kwargs ) : output = super ( Select2Mixin , self ) . render ( name , value , attrs = attrs , ** kwargs ) id_ = attrs [ 'id' ] output += self . render_js_code ( id_ , name , value , attrs = attrs , ** kwargs ) return mark_safe ( output ) | Extend base class s render method by appending javascript inline text to html output . |
51,578 | def select2_modelform ( model , attrs = None , form_class = es2_forms . FixedModelForm ) : classname = '%sForm' % model . _meta . object_name meta = select2_modelform_meta ( model , attrs = attrs ) return type ( classname , ( form_class , ) , { 'Meta' : meta } ) | Return ModelForm class for model with select2 widgets . |
51,579 | def parse ( self , text ) : gen = self . lexer . lex ( text ) next_val_fn = partial ( next , * ( gen , ) ) commands = [ ] token = next_val_fn ( ) while token [ 0 ] is not EOF : command , token = self . rule_svg_transform ( next_val_fn , token ) commands . append ( command ) return commands | Parse a string of SVG transform = data . |
51,580 | def findElementsWithId ( node , elems = None ) : if elems is None : elems = { } id = node . getAttribute ( 'id' ) if id != '' : elems [ id ] = node if node . hasChildNodes ( ) : for child in node . childNodes : if child . nodeType == Node . ELEMENT_NODE : findElementsWithId ( child , elems ) return elems | Returns all elements with id attributes |
51,581 | def findReferencedElements ( node , ids = None ) : global referencingProps if ids is None : ids = { } if node . nodeName == 'style' and node . namespaceURI == NS [ 'SVG' ] : stylesheet = "" . join ( [ child . nodeValue for child in node . childNodes ] ) if stylesheet != '' : cssRules = parseCssString ( stylesheet ) for rule in cssRules : for propname in rule [ 'properties' ] : propval = rule [ 'properties' ] [ propname ] findReferencingProperty ( node , propname , propval , ids ) return ids href = node . getAttributeNS ( NS [ 'XLINK' ] , 'href' ) if href != '' and len ( href ) > 1 and href [ 0 ] == '#' : id = href [ 1 : ] if id in ids : ids [ id ] . append ( node ) else : ids [ id ] = [ node ] styles = node . getAttribute ( 'style' ) . split ( ';' ) for style in styles : propval = style . split ( ':' ) if len ( propval ) == 2 : prop = propval [ 0 ] . strip ( ) val = propval [ 1 ] . strip ( ) findReferencingProperty ( node , prop , val , ids ) for attr in referencingProps : val = node . getAttribute ( attr ) . strip ( ) if not val : continue findReferencingProperty ( node , attr , val , ids ) if node . hasChildNodes ( ) : for child in node . childNodes : if child . nodeType == Node . ELEMENT_NODE : findReferencedElements ( child , ids ) return ids | Returns IDs of all referenced elements - node is the node at which to start the search . - returns a map which has the id as key and each value is is a list of nodes |
51,582 | def shortenIDs ( doc , prefix , unprotectedElements = None ) : num = 0 identifiedElements = findElementsWithId ( doc . documentElement ) if unprotectedElements is None : unprotectedElements = identifiedElements referencedIDs = findReferencedElements ( doc . documentElement ) idList = [ ( len ( referencedIDs [ rid ] ) , rid ) for rid in referencedIDs if rid in unprotectedElements ] idList . sort ( reverse = True ) idList = [ rid for count , rid in idList ] idList . extend ( [ rid for rid in unprotectedElements if rid not in idList ] ) curIdNum = 1 for rid in idList : curId = intToID ( curIdNum , prefix ) if curId != rid : while curId in identifiedElements : curIdNum += 1 curId = intToID ( curIdNum , prefix ) num += renameID ( doc , rid , curId , identifiedElements , referencedIDs ) curIdNum += 1 return num | Shortens ID names used in the document . ID names referenced the most often are assigned the shortest ID names . If the list unprotectedElements is provided only IDs from this list will be shortened . |
51,583 | def intToID ( idnum , prefix ) : rid = '' while idnum > 0 : idnum -= 1 rid = chr ( ( idnum % 26 ) + ord ( 'a' ) ) + rid idnum = int ( idnum / 26 ) return prefix + rid | Returns the ID name for the given ID number spreadsheet - style i . e . from a to z then from aa to az ba to bz etc . until zz . |
51,584 | def renameID ( doc , idFrom , idTo , identifiedElements , referencedIDs ) : num = 0 definingNode = identifiedElements [ idFrom ] definingNode . setAttribute ( "id" , idTo ) del identifiedElements [ idFrom ] identifiedElements [ idTo ] = definingNode num += len ( idFrom ) - len ( idTo ) referringNodes = referencedIDs . get ( idFrom ) if referringNodes is not None : for node in referringNodes : if node . nodeName == 'style' and node . namespaceURI == NS [ 'SVG' ] : if node . firstChild is not None : oldValue = "" . join ( [ child . nodeValue for child in node . childNodes ] ) newValue = oldValue . replace ( 'url(#' + idFrom + ')' , 'url(#' + idTo + ')' ) newValue = newValue . replace ( "url(#'" + idFrom + "')" , 'url(#' + idTo + ')' ) newValue = newValue . replace ( 'url(#"' + idFrom + '")' , 'url(#' + idTo + ')' ) node . childNodes [ : ] = [ node . ownerDocument . createTextNode ( newValue ) ] num += len ( oldValue ) - len ( newValue ) href = node . getAttributeNS ( NS [ 'XLINK' ] , 'href' ) if href == '#' + idFrom : node . setAttributeNS ( NS [ 'XLINK' ] , 'href' , '#' + idTo ) num += len ( idFrom ) - len ( idTo ) styles = node . getAttribute ( 'style' ) if styles != '' : newValue = styles . replace ( 'url(#' + idFrom + ')' , 'url(#' + idTo + ')' ) newValue = newValue . replace ( "url('#" + idFrom + "')" , 'url(#' + idTo + ')' ) newValue = newValue . replace ( 'url("#' + idFrom + '")' , 'url(#' + idTo + ')' ) node . setAttribute ( 'style' , newValue ) num += len ( styles ) - len ( newValue ) for attr in referencingProps : oldValue = node . getAttribute ( attr ) if oldValue != '' : newValue = oldValue . replace ( 'url(#' + idFrom + ')' , 'url(#' + idTo + ')' ) newValue = newValue . replace ( "url('#" + idFrom + "')" , 'url(#' + idTo + ')' ) newValue = newValue . replace ( 'url("#' + idFrom + '")' , 'url(#' + idTo + ')' ) node . setAttribute ( attr , newValue ) num += len ( oldValue ) - len ( newValue ) del referencedIDs [ idFrom ] referencedIDs [ idTo ] = referringNodes return num | Changes the ID name from idFrom to idTo on the declaring element as well as all references in the document doc . |
51,585 | def unprotected_ids ( doc , options ) : u identifiedElements = findElementsWithId ( doc . documentElement ) if not ( options . protect_ids_noninkscape or options . protect_ids_list or options . protect_ids_prefix ) : return identifiedElements if options . protect_ids_list : protect_ids_list = options . protect_ids_list . split ( "," ) if options . protect_ids_prefix : protect_ids_prefixes = options . protect_ids_prefix . split ( "," ) for id in list ( identifiedElements ) : protected = False if options . protect_ids_noninkscape and not id [ - 1 ] . isdigit ( ) : protected = True if options . protect_ids_list and id in protect_ids_list : protected = True if options . protect_ids_prefix : for prefix in protect_ids_prefixes : if id . startswith ( prefix ) : protected = True if protected : del identifiedElements [ id ] return identifiedElements | u Returns a list of unprotected IDs within the document doc . |
51,586 | def removeUnreferencedIDs ( referencedIDs , identifiedElements ) : global _num_ids_removed keepTags = [ 'font' ] num = 0 for id in identifiedElements : node = identifiedElements [ id ] if id not in referencedIDs and node . nodeName not in keepTags : node . removeAttribute ( 'id' ) _num_ids_removed += 1 num += 1 return num | Removes the unreferenced ID attributes . |
51,587 | def moveCommonAttributesToParentGroup ( elem , referencedElements ) : num = 0 childElements = [ ] for child in elem . childNodes : if child . nodeType == Node . ELEMENT_NODE : if not child . getAttribute ( 'id' ) in referencedElements : childElements . append ( child ) num += moveCommonAttributesToParentGroup ( child , referencedElements ) elif child . nodeType == Node . TEXT_NODE and child . nodeValue . strip ( ) : return num if len ( childElements ) <= 1 : return num commonAttrs = { } attrList = childElements [ 0 ] . attributes for index in range ( attrList . length ) : attr = attrList . item ( index ) if attr . nodeName in [ 'clip-rule' , 'display-align' , 'fill' , 'fill-opacity' , 'fill-rule' , 'font' , 'font-family' , 'font-size' , 'font-size-adjust' , 'font-stretch' , 'font-style' , 'font-variant' , 'font-weight' , 'letter-spacing' , 'pointer-events' , 'shape-rendering' , 'stroke' , 'stroke-dasharray' , 'stroke-dashoffset' , 'stroke-linecap' , 'stroke-linejoin' , 'stroke-miterlimit' , 'stroke-opacity' , 'stroke-width' , 'text-anchor' , 'text-decoration' , 'text-rendering' , 'visibility' , 'word-spacing' , 'writing-mode' ] : commonAttrs [ attr . nodeName ] = attr . nodeValue for childNum in range ( len ( childElements ) ) : if childNum == 0 : continue child = childElements [ childNum ] if child . localName in [ 'set' , 'animate' , 'animateColor' , 'animateTransform' , 'animateMotion' ] : continue distinctAttrs = [ ] for name in commonAttrs : if child . getAttribute ( name ) != commonAttrs [ name ] : distinctAttrs . append ( name ) for name in distinctAttrs : del commonAttrs [ name ] for name in commonAttrs : for child in childElements : child . removeAttribute ( name ) elem . setAttribute ( name , commonAttrs [ name ] ) num += ( len ( childElements ) - 1 ) * len ( commonAttrs ) return num | This recursively calls this function on all children of the passed in element and then iterates over all child elements and removes common inheritable attributes from the children and places them in the parent group . But only if the parent contains nothing but element children and whitespace . The attributes are only removed from the children if the children are not referenced by other elements in the document . |
51,588 | def removeUnusedAttributesOnParent ( elem ) : num = 0 childElements = [ ] for child in elem . childNodes : if child . nodeType == Node . ELEMENT_NODE : childElements . append ( child ) num += removeUnusedAttributesOnParent ( child ) if len ( childElements ) <= 1 : return num attrList = elem . attributes unusedAttrs = { } for index in range ( attrList . length ) : attr = attrList . item ( index ) if attr . nodeName in [ 'clip-rule' , 'display-align' , 'fill' , 'fill-opacity' , 'fill-rule' , 'font' , 'font-family' , 'font-size' , 'font-size-adjust' , 'font-stretch' , 'font-style' , 'font-variant' , 'font-weight' , 'letter-spacing' , 'pointer-events' , 'shape-rendering' , 'stroke' , 'stroke-dasharray' , 'stroke-dashoffset' , 'stroke-linecap' , 'stroke-linejoin' , 'stroke-miterlimit' , 'stroke-opacity' , 'stroke-width' , 'text-anchor' , 'text-decoration' , 'text-rendering' , 'visibility' , 'word-spacing' , 'writing-mode' ] : unusedAttrs [ attr . nodeName ] = attr . nodeValue for childNum in range ( len ( childElements ) ) : child = childElements [ childNum ] inheritedAttrs = [ ] for name in unusedAttrs : val = child . getAttribute ( name ) if val == '' or val is None or val == 'inherit' : inheritedAttrs . append ( name ) for a in inheritedAttrs : del unusedAttrs [ a ] for name in unusedAttrs : elem . removeAttribute ( name ) num += 1 return num | This recursively calls this function on all children of the element passed in then removes any unused attributes on this elem if none of the children inherit it |
51,589 | def _getStyle ( node ) : u if node . nodeType == Node . ELEMENT_NODE and len ( node . getAttribute ( 'style' ) ) > 0 : styleMap = { } rawStyles = node . getAttribute ( 'style' ) . split ( ';' ) for style in rawStyles : propval = style . split ( ':' ) if len ( propval ) == 2 : styleMap [ propval [ 0 ] . strip ( ) ] = propval [ 1 ] . strip ( ) return styleMap else : return { } | u Returns the style attribute of a node as a dictionary . |
51,590 | def _setStyle ( node , styleMap ) : u fixedStyle = ';' . join ( [ prop + ':' + styleMap [ prop ] for prop in styleMap ] ) if fixedStyle != '' : node . setAttribute ( 'style' , fixedStyle ) elif node . getAttribute ( 'style' ) : node . removeAttribute ( 'style' ) return node | u Sets the style attribute of a node to the dictionary styleMap . |
51,591 | def styleInheritedFromParent ( node , style ) : parentNode = node . parentNode if parentNode . nodeType == Node . DOCUMENT_NODE : return None styles = _getStyle ( parentNode ) if style in styles : value = styles [ style ] if not value == 'inherit' : return value value = parentNode . getAttribute ( style ) if value not in [ '' , 'inherit' ] : return parentNode . getAttribute ( style ) return styleInheritedFromParent ( parentNode , style ) | Returns the value of style that is inherited from the parents of the passed - in node |
51,592 | def styleInheritedByChild ( node , style , nodeIsChild = False ) : if node . nodeType != Node . ELEMENT_NODE : return False if nodeIsChild : if node . getAttribute ( style ) not in [ '' , 'inherit' ] : return False styles = _getStyle ( node ) if ( style in styles ) and not ( styles [ style ] == 'inherit' ) : return False else : if not node . childNodes : return False if node . childNodes : for child in node . childNodes : if styleInheritedByChild ( child , style , True ) : return True if node . nodeName in [ 'a' , 'defs' , 'glyph' , 'g' , 'marker' , 'mask' , 'missing-glyph' , 'pattern' , 'svg' , 'switch' , 'symbol' ] : return False return True | Returns whether style is inherited by any children of the passed - in node |
51,593 | def mayContainTextNodes ( node ) : try : return node . mayContainTextNodes except AttributeError : pass result = True if node . nodeType != Node . ELEMENT_NODE : result = False elif node . namespaceURI != NS [ 'SVG' ] : result = True elif node . nodeName in [ 'rect' , 'circle' , 'ellipse' , 'line' , 'polygon' , 'polyline' , 'path' , 'image' , 'stop' ] : result = False elif node . nodeName in [ 'g' , 'clipPath' , 'marker' , 'mask' , 'pattern' , 'linearGradient' , 'radialGradient' , 'symbol' ] : result = False for child in node . childNodes : if mayContainTextNodes ( child ) : result = True node . mayContainTextNodes = result return result | Returns True if the passed - in node is probably a text element or at least one of its descendants is probably a text element . |
51,594 | def taint ( taintedSet , taintedAttribute ) : u taintedSet . add ( taintedAttribute ) if taintedAttribute == 'marker' : taintedSet |= set ( [ 'marker-start' , 'marker-mid' , 'marker-end' ] ) if taintedAttribute in [ 'marker-start' , 'marker-mid' , 'marker-end' ] : taintedSet . add ( 'marker' ) return taintedSet | u Adds an attribute to a set of attributes . |
51,595 | def removeDefaultAttributeValue ( node , attribute ) : if not node . hasAttribute ( attribute . name ) : return 0 if isinstance ( attribute . value , str ) : if node . getAttribute ( attribute . name ) == attribute . value : if ( attribute . conditions is None ) or attribute . conditions ( node ) : node . removeAttribute ( attribute . name ) return 1 else : nodeValue = SVGLength ( node . getAttribute ( attribute . name ) ) if ( ( attribute . value is None ) or ( ( nodeValue . value == attribute . value ) and not ( nodeValue . units == Unit . INVALID ) ) ) : if ( ( attribute . units is None ) or ( nodeValue . units == attribute . units ) or ( isinstance ( attribute . units , list ) and nodeValue . units in attribute . units ) ) : if ( attribute . conditions is None ) or attribute . conditions ( node ) : node . removeAttribute ( attribute . name ) return 1 return 0 | Removes the DefaultAttribute attribute from node if specified conditions are fulfilled |
51,596 | def removeDefaultAttributeValues ( node , options , tainted = set ( ) ) : u num = 0 if node . nodeType != Node . ELEMENT_NODE : return 0 for attribute in default_attributes_universal : num += removeDefaultAttributeValue ( node , attribute ) if node . nodeName in default_attributes_per_element : for attribute in default_attributes_per_element [ node . nodeName ] : num += removeDefaultAttributeValue ( node , attribute ) attributes = [ node . attributes . item ( i ) . nodeName for i in range ( node . attributes . length ) ] for attribute in attributes : if attribute not in tainted : if attribute in default_properties : if node . getAttribute ( attribute ) == default_properties [ attribute ] : node . removeAttribute ( attribute ) num += 1 else : tainted = taint ( tainted , attribute ) styles = _getStyle ( node ) for attribute in list ( styles ) : if attribute not in tainted : if attribute in default_properties : if styles [ attribute ] == default_properties [ attribute ] : del styles [ attribute ] num += 1 else : tainted = taint ( tainted , attribute ) _setStyle ( node , styles ) for child in node . childNodes : num += removeDefaultAttributeValues ( child , options , tainted . copy ( ) ) return num | u tainted keeps a set of attributes defined in parent nodes . |
51,597 | def parseListOfPoints ( s ) : i = 0 ws_nums = re . split ( r"\s*[\s,]\s*" , s . strip ( ) ) nums = [ ] for i in range ( len ( ws_nums ) ) : negcoords = ws_nums [ i ] . split ( "-" ) if len ( negcoords ) == 1 : nums . append ( negcoords [ 0 ] ) else : for j in range ( len ( negcoords ) ) : if j == 0 : if negcoords [ 0 ] != '' : nums . append ( negcoords [ 0 ] ) else : prev = "" if len ( nums ) : prev = nums [ len ( nums ) - 1 ] if prev and prev [ len ( prev ) - 1 ] in [ 'e' , 'E' ] : nums [ len ( nums ) - 1 ] = prev + '-' + negcoords [ j ] else : nums . append ( '-' + negcoords [ j ] ) if len ( nums ) % 2 != 0 : return [ ] i = 0 while i < len ( nums ) : try : nums [ i ] = getcontext ( ) . create_decimal ( nums [ i ] ) nums [ i + 1 ] = getcontext ( ) . create_decimal ( nums [ i + 1 ] ) except InvalidOperation : return [ ] i += 2 return nums | Parse string into a list of points . |
51,598 | def cleanPolygon ( elem , options ) : global _num_points_removed_from_polygon pts = parseListOfPoints ( elem . getAttribute ( 'points' ) ) N = len ( pts ) / 2 if N >= 2 : ( startx , starty ) = pts [ : 2 ] ( endx , endy ) = pts [ - 2 : ] if startx == endx and starty == endy : del pts [ - 2 : ] _num_points_removed_from_polygon += 1 elem . setAttribute ( 'points' , scourCoordinates ( pts , options , True ) ) | Remove unnecessary closing point of polygon points attribute |
51,599 | def cleanPolyline ( elem , options ) : pts = parseListOfPoints ( elem . getAttribute ( 'points' ) ) elem . setAttribute ( 'points' , scourCoordinates ( pts , options , True ) ) | Scour the polyline points attribute |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.