idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
15,900
def convert_config_value ( self , value , label ) : if isinstance ( value , six . string_types ) : value = value . lower ( ) if value in self . TRUTHY_VALUES : return True elif value in self . FALSY_VALUES : return False else : raise YapconfValueError ( "Cowardly refusing to interpret " "config value as a boolean. Name...
Converts all Truthy values to True and Falsy values to False .
15,901
def add_argument ( self , parser , bootstrap = False ) : if self . cli_expose : if isinstance ( self . child , YapconfBoolItem ) : original_default = self . child . default self . child . default = True args = self . child . _get_argparse_names ( parser . prefix_chars ) kwargs = self . _get_argparse_kwargs ( bootstrap ...
Add list - style item as an argument to the given parser .
15,902
def add_argument ( self , parser , bootstrap = False ) : if self . cli_expose : for child in self . children . values ( ) : child . add_argument ( parser , bootstrap )
Add dict - style item as an argument to the given parser .
15,903
def log_time ( func ) : @ functools . wraps ( func ) def _execute ( * args , ** kwargs ) : func_name = get_method_name ( func ) timer = Timer ( ) log_message ( func_name , "has started" ) with timer : result = func ( * args , ** kwargs ) seconds = "{:.3f}" . format ( timer . elapsed_time ( ) ) log_message ( func_name ,...
Executes function and logs time
15,904
def load_configuration ( yaml : yaml . ruamel . yaml . YAML , filename : str ) -> DictLike : with open ( filename , "r" ) as f : config = yaml . load ( f ) return config
Load an analysis configuration from a file .
15,905
def override_options ( config : DictLike , selected_options : Tuple [ Any , ... ] , set_of_possible_options : Tuple [ enum . Enum , ... ] , config_containing_override : DictLike = None ) -> DictLike : if config_containing_override is None : config_containing_override = config override_opts = config_containing_override ...
Determine override options for a particular configuration .
15,906
def simplify_data_representations ( config : DictLike ) -> DictLike : for k , v in config . items ( ) : if v and isinstance ( v , list ) and len ( v ) == 1 : logger . debug ( "v: {}" . format ( v ) ) config [ k ] = v [ 0 ] return config
Convert one entry lists to the scalar value
15,907
def determine_selection_of_iterable_values_from_config ( config : DictLike , possible_iterables : Mapping [ str , Type [ enum . Enum ] ] ) -> Dict [ str , List [ Any ] ] : iterables = { } requested_iterables = config [ "iterables" ] for k , v in requested_iterables . items ( ) : if k not in possible_iterables : raise K...
Determine iterable values to use to create objects for a given configuration .
15,908
def _key_index_iter ( self ) -> Iterator [ Tuple [ str , Any ] ] : for k , v in vars ( self ) . items ( ) : yield k , v
Allows for iteration over the KeyIndex values .
15,909
def create_key_index_object ( key_index_name : str , iterables : Dict [ str , Any ] ) -> Any : for name , iterable in iterables . items ( ) : if iter ( iterable ) == iter ( iterable ) : raise TypeError ( f"Iterable {name} is in iterator which can be exhausted. Please pass the iterable" f" in a container that can recrea...
Create a KeyIndex class based on the passed attributes .
15,910
def create_objects_from_iterables ( obj , args : dict , iterables : Dict [ str , Any ] , formatting_options : Dict [ str , Any ] , key_index_name : str = "KeyIndex" ) -> Tuple [ Any , Dict [ str , Any ] , dict ] : objects = { } names = list ( iterables ) logger . debug ( f"iterables: {iterables}" ) KeyIndex = create_ke...
Create objects for each set of values based on the given arguments .
15,911
def apply_formatting_dict ( obj : Any , formatting : Dict [ str , Any ] ) -> Any : new_obj = obj if isinstance ( obj , str ) : if "$" not in obj : new_obj = string . Formatter ( ) . vformat ( obj , ( ) , formatting_dict ( ** formatting ) ) elif isinstance ( obj , dict ) : new_obj = { } for k , v in obj . items ( ) : ne...
Recursively apply a formatting dict to all strings in a configuration .
15,912
def iterate_with_selected_objects ( analysis_objects : Mapping [ Any , Any ] , ** selections : Mapping [ str , Any ] ) -> Iterator [ Tuple [ Any , Any ] ] : for key_index , obj in analysis_objects . items ( ) : selected_obj = not selections or all ( [ getattr ( key_index , selector ) == selected_value for selector , se...
Iterate over an analysis dictionary with selected attributes .
15,913
def iterate_with_selected_objects_in_order ( analysis_objects : Mapping [ Any , Any ] , analysis_iterables : Dict [ str , Sequence [ Any ] ] , selection : Union [ str , Sequence [ str ] ] ) -> Iterator [ List [ Tuple [ Any , Any ] ] ] : if isinstance ( selection , str ) : selection = [ selection ] assert not isinstance...
Iterate over an analysis dictionary yielding the selected attributes in order .
15,914
def _db ( self ) : if not hasattr ( self , "_db_client" ) or getattr ( self , "_db_client" ) is None : self . _db_client = get_db_client ( ) return self . _db_client
Database client for accessing storage .
15,915
async def filter_new_posts ( self , source_id , post_ids ) : new_ids = [ ] try : db_client = self . _db posts_in_db = await db_client . get_known_posts ( source_id , post_ids ) new_ids = [ p for p in post_ids if p not in posts_in_db ] except Exception as exc : logger . error ( "Error when filtering for new posts {} {}"...
Filters ist of post_id for new ones .
15,916
async def get_last_updated ( self , source_id ) : last_updated = await self . _db . get_last_updated ( source_id ) logger . info ( "LAST UPDATED: {} {}" . format ( last_updated , self ) ) return last_updated
Returns latest update - timestamp from storage for source .
15,917
def clearParameters ( self ) : self . beginRemoveRows ( QtCore . QModelIndex ( ) , 0 , self . rowCount ( ) ) self . model . clear_parameters ( ) self . endRemoveRows ( )
Removes all parameters from model
15,918
def insertRows ( self , position , rows , parent = QtCore . QModelIndex ( ) ) : self . beginInsertRows ( parent , position , position + rows - 1 ) for i in range ( rows ) : self . model . insertRow ( position ) self . endInsertRows ( ) if self . rowCount ( ) == 1 : self . emptied . emit ( False ) return True
Inserts new parameters and emits an emptied False signal
15,919
def removeRows ( self , position , rows , parent = QtCore . QModelIndex ( ) ) : self . beginRemoveRows ( parent , position , position + rows - 1 ) for i in range ( rows ) : self . model . removeRow ( position ) self . endRemoveRows ( ) if self . rowCount ( ) == 0 : self . emptied . emit ( True ) return True
Removes parameters from the model . Emits and emptied True signal if there are no parameters left .
15,920
def toggleSelection ( self , index , comp ) : self . model . toggleSelection ( index . row ( ) , comp )
Toggles a component in or out of the currently selected parameter s compnents list
15,921
def parseruninfo ( self ) : try : runinfo = ElementTree . ElementTree ( file = self . runinfo ) for elem in runinfo . iter ( ) : for run in elem : try : self . runid = run . attrib [ 'Id' ] self . runnumber = run . attrib [ 'Number' ] except KeyError : break for elem in runinfo . iter ( tag = "Flowcell" ) : self . flow...
Extracts the flowcell ID as well as the instrument name from RunInfo . xml . If this file is not provided NA values are substituted
15,922
def get_lines ( self ) : with open ( self . path , "r" ) as data : self . lines = data . readlines ( ) return self . lines
Gets lines in file
15,923
def get_matrix ( self ) : data = [ ] with open ( self . path , encoding = self . encoding ) as csv_file : csv_reader = csv . reader ( csv_file , delimiter = "," , quotechar = "\"" ) for row in csv_reader : data . append ( row ) return data
Stores values in array store lines in array
15,924
def get_dicts ( self ) : reader = csv . DictReader ( open ( self . path , "r" , encoding = self . encoding ) ) for row in reader : if row : yield row
Gets dicts in file
15,925
def get_by_id ( self , id_code : str ) -> Currency or None : try : return [ _ for _ in self . currencies if _ . id == id_code ] [ 0 ] except IndexError : return None
Get currency by ID
15,926
def get_stimuli_models ( ) : package_path = os . path . dirname ( __file__ ) mod = '.' . join ( get_stimuli_models . __module__ . split ( '.' ) ) if mod == '__main__' : mod = '' else : mod = mod + '.' module_files = glob . glob ( package_path + os . sep + '[a-zA-Z]*.py' ) module_names = [ os . path . splitext ( os . pa...
Returns all subclasses of AbstractStimulusComponent in python files in this package
15,927
def parse_wait_time ( text : str ) -> int : val = RATELIMIT . findall ( text ) if len ( val ) > 0 : try : res = val [ 0 ] if res [ 1 ] == 'minutes' : return int ( res [ 0 ] ) * 60 if res [ 1 ] == 'seconds' : return int ( res [ 0 ] ) except Exception as e : util_logger . warning ( 'Could not parse ratelimit: ' + str ( e...
Parse the waiting time from the exception
15,928
def check_comment_depth ( comment : praw . models . Comment , max_depth = 3 ) -> bool : count = 0 while not comment . is_root : count += 1 if count > max_depth : return False comment = comment . parent ( ) return True
Check if comment is in a allowed depth range
15,929
def get_subs ( subs_file = 'subreddits.txt' , blacklist_file = 'blacklist.txt' ) -> List [ str ] : subsf = open ( subs_file ) blacklf = open ( blacklist_file ) subs = [ b . lower ( ) . replace ( '\n' , '' ) for b in subsf . readlines ( ) ] blacklisted = [ b . lower ( ) . replace ( '\n' , '' ) for b in blacklf . readlin...
Get subs based on a file of subreddits and a file of blacklisted subreddits .
15,930
def enable_all_links ( ) : for link in client . list_data_links ( instance = 'simulator' ) : client . enable_data_link ( instance = link . instance , link = link . name )
Enable all links .
15,931
def load_a3m ( fasta , max_gap_fraction = 0.9 ) : mapping = { '-' : 21 , 'A' : 1 , 'B' : 21 , 'C' : 2 , 'D' : 3 , 'E' : 4 , 'F' : 5 , 'G' : 6 , 'H' : 7 , 'I' : 8 , 'K' : 9 , 'L' : 10 , 'M' : 11 , 'N' : 12 , 'O' : 21 , 'P' : 13 , 'Q' : 14 , 'R' : 15 , 'S' : 16 , 'T' : 17 , 'V' : 18 , 'W' : 19 , 'Y' : 20 , 'U' : 21 , 'Z'...
load alignment with the alphabet used in GaussDCA
15,932
def run_plasmid_extractor ( self ) : logging . info ( 'Extracting plasmids' ) extract_command = 'PlasmidExtractor.py -i {inf} -o {outf} -p {plasdb} -d {db} -t {cpus} -nc' . format ( inf = self . path , outf = self . plasmid_output , plasdb = os . path . join ( self . plasmid_db , 'plasmid_db.fasta' ) , db = self . plas...
Create and run the plasmid extractor system call
15,933
def parse_report ( self ) : logging . info ( 'Parsing Plasmid Extractor outputs' ) nesteddictionary = dict ( ) dictionary = pandas . read_csv ( self . plasmid_report ) . to_dict ( ) for header in dictionary : for sample , value in dictionary [ header ] . items ( ) : try : nesteddictionary [ sample ] . update ( { header...
Parse the plasmid extractor report and populate metadata objects
15,934
def object_clean ( self ) : for sample in self . metadata : try : delattr ( sample [ self . analysistype ] , 'aaidentity' ) delattr ( sample [ self . analysistype ] , 'aaalign' ) delattr ( sample [ self . analysistype ] , 'aaindex' ) delattr ( sample [ self . analysistype ] , 'ntalign' ) delattr ( sample [ self . analy...
Remove large attributes from the metadata objects
15,935
def values ( self ) : if self . ui . hzBtn . isChecked ( ) : fscale = SmartSpinBox . Hz else : fscale = SmartSpinBox . kHz if self . ui . msBtn . isChecked ( ) : tscale = SmartSpinBox . MilliSeconds else : tscale = SmartSpinBox . Seconds return fscale , tscale
Gets the scales that the user chose
15,936
def insert_trie ( trie , value ) : if value in trie : return trie [ value ] multi_check = False for key in tuple ( trie . keys ( ) ) : if len ( value ) > len ( key ) and value . startswith ( key ) : return insert_trie ( trie [ key ] , value ) elif key . startswith ( value ) : if not multi_check : trie [ value ] = { } m...
Insert a value into the trie if it is not already contained in the trie . Return the subtree for the value regardless of whether it is a new value or not .
15,937
def get_valid_cell_indecies ( self ) : return pd . DataFrame ( self ) . groupby ( self . frame_columns ) . apply ( lambda x : list ( x [ 'cell_index' ] ) ) . reset_index ( ) . rename ( columns = { 0 : 'valid' } )
Return a dataframe of images present with valid being a list of cell indecies that can be included
15,938
def prune_neighbors ( self ) : def _neighbor_check ( neighbors , valid ) : if not neighbors == neighbors : return np . nan valid_keys = set ( valid ) & set ( neighbors . keys ( ) ) d = dict ( [ ( k , v ) for k , v in neighbors . items ( ) if k in valid_keys ] ) return d fixed = self . copy ( ) valid = self . get_valid_...
If the CellDataFrame has been subsetted some of the cell - cell contacts may no longer be part of the the dataset . This prunes those no - longer existant connections .
15,939
def to_hdf ( self , path , key , mode = 'a' ) : pd . DataFrame ( self . serialize ( ) ) . to_hdf ( path , key , mode = mode , format = 'table' , complib = 'zlib' , complevel = 9 ) f = h5py . File ( path , 'r+' ) f [ key ] . attrs [ "microns_per_pixel" ] = float ( self . microns_per_pixel ) if self . microns_per_pixel i...
Save the CellDataFrame to an hdf5 file .
15,940
def phenotypes_to_scored ( self , phenotypes = None , overwrite = False ) : if not self . is_uniform ( ) : raise ValueError ( "inconsistent phenotypes" ) if phenotypes is None : phenotypes = self . phenotypes elif isinstance ( phenotypes , str ) : phenotypes = [ phenotypes ] def _post ( binary , phenotype_label , pheno...
Add mutually exclusive phenotypes to the scored calls
15,941
def concat ( self , array_like ) : arr = list ( array_like ) if len ( set ( [ x . microns_per_pixel for x in arr ] ) ) != 1 : raise ValueError ( "Multiple microns per pixel set" ) cdf = CellDataFrame ( pd . concat ( [ pd . DataFrame ( x ) for x in arr ] ) ) cdf . microns_per_pixel = arr [ 0 ] . microns_per_pixel return...
Concatonate multiple CellDataFrames
15,942
def read_hdf ( cls , path , key = None ) : df = pd . read_hdf ( path , key ) df [ 'scored_calls' ] = df [ 'scored_calls' ] . apply ( lambda x : json . loads ( x ) ) df [ 'channel_values' ] = df [ 'channel_values' ] . apply ( lambda x : json . loads ( x ) ) df [ 'regions' ] = df [ 'regions' ] . apply ( lambda x : json ....
Read a CellDataFrame from an hdf5 file .
15,943
def serialize ( self ) : df = self . copy ( ) df [ 'scored_calls' ] = df [ 'scored_calls' ] . apply ( lambda x : json . dumps ( x ) ) df [ 'channel_values' ] = df [ 'channel_values' ] . apply ( lambda x : json . dumps ( x ) ) df [ 'regions' ] = df [ 'regions' ] . apply ( lambda x : json . dumps ( x ) ) df [ 'phenotype_...
Convert the data to one that can be saved in h5 structures
15,944
def contacts ( self , * args , ** kwargs ) : n = Contacts . read_cellframe ( self , prune_neighbors = True ) if 'measured_regions' in kwargs : n . measured_regions = kwargs [ 'measured_regions' ] else : n . measured_regions = self . get_measured_regions ( ) if 'measured_phenotypes' in kwargs : n . measured_phenotypes =...
Use assess the cell - to - cell contacts recorded in the celldataframe
15,945
def cartesian ( self , subsets = None , step_pixels = 100 , max_distance_pixels = 150 , * args , ** kwargs ) : n = Cartesian . read_cellframe ( self , subsets = subsets , step_pixels = step_pixels , max_distance_pixels = max_distance_pixels , prune_neighbors = False , * args , ** kwargs ) if 'measured_regions' in kwarg...
Return a class that can be used to create honeycomb plots
15,946
def counts ( self , * args , ** kwargs ) : n = Counts . read_cellframe ( self , prune_neighbors = False ) if 'measured_regions' in kwargs : n . measured_regions = kwargs [ 'measured_regions' ] else : n . measured_regions = self . get_measured_regions ( ) if 'measured_phenotypes' in kwargs : n . measured_phenotypes = kw...
Return a class that can be used to access count densities
15,947
def merge_scores ( self , df_addition , reference_markers = 'all' , addition_markers = 'all' , on = [ 'project_name' , 'sample_name' , 'frame_name' , 'cell_index' ] ) : if isinstance ( reference_markers , str ) : reference_markers = self . scored_names elif reference_markers is None : reference_markers = [ ] if isinsta...
Combine CellDataFrames that differ by score composition
15,948
def zero_fill_missing_phenotypes ( self ) : if self . is_uniform ( verbose = False ) : return self . copy ( ) output = self . copy ( ) def _do_fill ( d , names ) : old_names = list ( d . keys ( ) ) old_values = list ( d . values ( ) ) missing = set ( names ) - set ( old_names ) return dict ( zip ( old_names + list ( mi...
Fill in missing phenotypes and scored types by listing any missing data as negative
15,949
def drop_scored_calls ( self , names ) : def _remove ( calls , names ) : d = dict ( [ ( k , v ) for k , v in calls . items ( ) if k not in names ] ) return d if isinstance ( names , str ) : names = [ names ] output = self . copy ( ) output [ 'scored_calls' ] = output [ 'scored_calls' ] . apply ( lambda x : _remove ( x ...
Take a name or list of scored call names and drop those from the scored calls
15,950
def subset ( self , logic , update = False ) : pnames = self . phenotypes snames = self . scored_names data = self . copy ( ) values = [ ] phenotypes = logic . phenotypes if len ( phenotypes ) == 0 : phenotypes = pnames removing = set ( self . phenotypes ) - set ( phenotypes ) for k in phenotypes : if k not in pnames :...
subset create a specific phenotype based on a logic logic is a SubsetLogic class take union of all the phenotypes listed . If none are listed use all phenotypes . take the intersection of all the scored calls .
15,951
def collapse_phenotypes ( self , input_phenotype_labels , output_phenotype_label , verbose = True ) : if isinstance ( input_phenotype_labels , str ) : input_phenotype_labels = [ input_phenotype_labels ] bad_phenotypes = set ( input_phenotype_labels ) - set ( self . phenotypes ) if len ( bad_phenotypes ) > 0 : raise Val...
Rename one or more input phenotypes to a single output phenotype
15,952
def fill_phenotype_label ( self , inplace = False ) : def _get_phenotype ( d ) : vals = [ k for k , v in d . items ( ) if v == 1 ] return np . nan if len ( vals ) == 0 else vals [ 0 ] if inplace : if self . shape [ 0 ] == 0 : return self self [ 'phenotype_label' ] = self . apply ( lambda x : _get_phenotype ( x [ 'pheno...
Set the phenotype_label column according to our rules for mutual exclusion
15,953
def fill_phenotype_calls ( self , phenotypes = None , inplace = False ) : if phenotypes is None : phenotypes = list ( self [ 'phenotype_label' ] . unique ( ) ) def _get_calls ( label , phenos ) : d = dict ( [ ( x , 0 ) for x in phenos ] ) if label != label : return d d [ label ] = 1 return d if inplace : self [ 'phenot...
Set the phenotype_calls according to the phenotype names
15,954
def scored_to_phenotype ( self , phenotypes ) : def _apply_score ( scored_calls , phenotypes ) : present = sorted ( list ( set ( phenotypes ) & set ( scored_calls . keys ( ) ) ) ) total = sum ( [ scored_calls [ x ] for x in present ] ) if total > 1 : raise ValueError ( "You cant extract phenotypes from scores if they a...
Convert binary pehnotypes to mutually exclusive phenotypes . If none of the phenotypes are set then phenotype_label becomes nan If any of the phenotypes are multiply set then it throws a fatal error .
15,955
def issue_and_listen_to_command_history ( ) : def tc_callback ( rec ) : print ( 'TC:' , rec ) command = processor . issue_command ( '/YSS/SIMULATOR/SWITCH_VOLTAGE_OFF' , args = { 'voltage_num' : 1 , } , comment = 'im a comment' ) command . create_command_history_subscription ( on_data = tc_callback )
Listen to command history updates of a single issued command .
15,956
def get_many2many_table ( table1 , table2 ) : table_name = ( '{}{}__{}' . format ( TABLE_PREFIX , table1 , table2 ) ) return Table ( table_name , Base . metadata , Column ( '{}_id' . format ( table1 ) , Integer , ForeignKey ( '{}{}.id' . format ( TABLE_PREFIX , table1 ) ) ) , Column ( '{}_id' . format ( table2 ) , Inte...
Creates a many - to - many table that links the given tables table1 and table2 .
15,957
async def search ( self , regex ) : coro = self . _loop . run_in_executor ( None , self . _search , regex ) match = await coro return match
Wraps the search for a match in an executor _ and awaits for it .
15,958
def show_help ( self ) : print ( "Sorry, not well understood." ) print ( "- use" , str ( self . yes_input ) , "to answer 'YES'" ) print ( "- use" , str ( self . no_input ) , "to answer 'NO'" )
Prints to stdout help on how to answer properly
15,959
def re_ask ( self , with_help = True ) : if with_help : self . show_help ( ) return self . get_answer ( self . last_question )
Re - asks user the last question
15,960
def get_answer ( self , question ) : self . last_question = str ( question ) . strip ( ) user_answer = input ( self . last_question ) return user_answer . strip ( )
Asks user a question then gets user answer
15,961
def get_number ( self , question , min_i = float ( "-inf" ) , max_i = float ( "inf" ) , just_these = None ) : try : user_answer = self . get_answer ( question ) user_answer = float ( user_answer ) if min_i < user_answer < max_i : if just_these : if user_answer in just_these : return user_answer exc = "Number cannot be ...
Parses answer and gets number
15,962
def get_list ( self , question , splitter = "," , at_least = 0 , at_most = float ( "inf" ) ) : try : user_answer = self . get_answer ( question ) user_answer = user_answer . split ( splitter ) user_answer = [ str ( item ) . strip ( ) for item in user_answer ] if at_least < len ( user_answer ) < at_most : return user_an...
Parses answer and gets list
15,963
def batlab2sparkle ( experiment_data ) : nsdata = { } for attr in [ 'computername' , 'pst_filename' , 'title' , 'who' , 'date' , 'program_date' ] : nsdata [ attr ] = experiment_data [ attr ] for itest , test in enumerate ( experiment_data [ 'test' ] ) : setname = 'test_{}' . format ( itest + 1 ) nsdata [ setname ] = { ...
Sparkle expects meta data to have a certain heirarchial organization reformat batlab experiment data to fit .
15,964
def sanitize_type ( raw_type ) : cleaned = get_printable ( raw_type ) . strip ( ) for bad in [ r'__drv_aliasesMem' , r'__drv_freesMem' , r'__drv_strictTypeMatch\(\w+\)' , r'__out_data_source\(\w+\)' , r'_In_NLS_string_\(\w+\)' , r'_Frees_ptr_' , r'_Frees_ptr_opt_' , r'opt_' , r'\(Mem\) ' ] : cleaned = re . sub ( bad , ...
Sanitize the raw type string .
15,965
def clean_ret_type ( ret_type ) : ret_type = get_printable ( ret_type ) . strip ( ) if ret_type == 'LRESULT LRESULT' : ret_type = 'LRESULT' for bad in [ 'DECLSPEC_NORETURN' , 'NTSYSCALLAPI' , '__kernel_entry' , '__analysis_noreturn' , '_Post_equals_last_error_' , '_Maybe_raises_SEH_exception_' , '_CRT_STDIO_INLINE' , '...
Clean the erraneous parsed return type .
15,966
async def setup ( self ) : try : client = await self . db response = await client . list_tables ( ) created = False if self . table_name not in response [ "TableNames" ] : logger . info ( "Creating DynamoDB table [{}]" . format ( self . table_name ) ) resp = await client . create_table ( ** self . table_schema ) if res...
Setting up DynamoDB table if it not exists .
15,967
def maxRange ( self ) : try : x , freqs = self . datafile . get_calibration ( str ( self . ui . calChoiceCmbbx . currentText ( ) ) , self . calf ) self . ui . frangeLowSpnbx . setValue ( freqs [ 0 ] ) self . ui . frangeHighSpnbx . setValue ( freqs [ - 1 ] ) print 'set freq range' , freqs [ 0 ] , freqs [ - 1 ] , freqs [...
Sets the maximum range for the currently selection calibration determined from its range of values store on file
15,968
def plotCurve ( self ) : try : attenuations , freqs = self . datafile . get_calibration ( str ( self . ui . calChoiceCmbbx . currentText ( ) ) , self . calf ) self . pw = SimplePlotWidget ( freqs , attenuations , parent = self ) self . pw . setWindowFlags ( QtCore . Qt . Window ) self . pw . setLabels ( 'Frequency' , '...
Shows a calibration curve in a separate window of the currently selected calibration
15,969
def values ( self ) : results = { } results [ 'use_calfile' ] = self . ui . calfileRadio . isChecked ( ) results [ 'calname' ] = str ( self . ui . calChoiceCmbbx . currentText ( ) ) results [ 'frange' ] = ( self . ui . frangeLowSpnbx . value ( ) , self . ui . frangeHighSpnbx . value ( ) ) return results
Gets the values the user input to this dialog
15,970
def conditional_accept ( self ) : if self . ui . calfileRadio . isChecked ( ) and str ( self . ui . calChoiceCmbbx . currentText ( ) ) == '' : self . ui . noneRadio . setChecked ( True ) if self . ui . calfileRadio . isChecked ( ) : try : x , freqs = self . datafile . get_calibration ( str ( self . ui . calChoiceCmbbx ...
Accepts the inputs if all values are valid and congruent . i . e . Valid datafile and frequency range within the given calibration dataset .
15,971
def customized_warning ( message , category = UserWarning , filename = '' , lineno = - 1 , file = None , line = None ) : print ( "WARNING: {0}" . format ( message ) )
Customized function to display warnings . Monkey patch for warnings . showwarning .
15,972
def read_cmdline ( ) : info = { "prog" : "Ellis" , "description" : "%(prog)s version {0}" . format ( __version__ ) , "epilog" : "For further help please head over to {0}" . format ( __url__ ) , "usage" : argparse . SUPPRESS , } argp = argparse . ArgumentParser ( ** info ) argp . add_argument ( "-c" , "--config" , dest ...
Parses optional command line arguments .
15,973
def main ( ) : warnings . showwarning = customized_warning args = read_cmdline ( ) config_file = args [ 'config_file' ] try : ellis = Ellis ( config_file ) except NoRuleError : msg = ( "There are no valid rules in the config file. " "Ellis can not run without rules." ) print_err ( msg ) else : ellis . start ( )
Entry point for Ellis .
15,974
def shape ( self , shape = None ) : if shape is None : return self . _shape data , color = self . renderer . manager . set_shape ( self . model . id , shape ) self . model . data = data self . color = color self . _shape = shape
We need to shift buffers in order to change shape
15,975
def reply ( self , timeout = None ) : self . _wait_on_signal ( self . _response_received ) if self . _response_exception is not None : msg = self . _response_exception . message raise YamcsError ( msg ) return self . _response_reply
Returns the initial reply . This is emitted before any subscription data is emitted . This function raises an exception if the subscription attempt failed .
15,976
async def stop_bridges ( self ) : for task in self . sleep_tasks : task . cancel ( ) for bridge in self . bridges : bridge . stop ( )
Stop all sleep tasks to allow bridges to end .
15,977
def str_to_date ( date : str ) -> datetime . datetime : date = date . split ( '.' ) date . reverse ( ) y , m , d = date return datetime . datetime ( int ( y ) , int ( m ) , int ( d ) )
Convert cbr . ru API date ste to python datetime
15,978
def load ( self , data , size = None ) : self . bind ( ) if size is None : size = sizeof ( data ) if size == self . buffer_size : glBufferSubData ( self . array_type , 0 , size , to_raw_pointer ( data ) ) else : glBufferData ( self . array_type , size , to_raw_pointer ( data ) , self . draw_type ) self . buffer_size = ...
Data is cffi array
15,979
def init ( ) : main . init_environment ( ) pluginpath = os . pathsep . join ( ( os . environ . get ( 'JUKEBOX_PLUGIN_PATH' , '' ) , BUILTIN_PLUGIN_PATH ) ) os . environ [ 'JUKEBOX_PLUGIN_PATH' ] = pluginpath try : maya . standalone . initialize ( ) jukeboxmaya . STANDALONE_INITIALIZED = True except RuntimeError as e : ...
Initialize the pipeline in maya so everything works
15,980
def all_jobs ( self ) : return list ( set ( self . complete + self . failed + self . queue + self . running ) )
Returns a list of all jobs submitted to the queue complete in - progess or failed .
15,981
def progress ( self ) : total = len ( self . all_jobs ) remaining = total - len ( self . active_jobs ) if total > 0 else 0 percent = int ( 100 * ( float ( remaining ) / total ) ) if total > 0 else 0 return percent
Returns the percentage current and total number of jobs in the queue .
15,982
def ready ( self , job ) : no_deps = len ( job . depends_on ) == 0 all_complete = all ( j . is_complete ( ) for j in self . active_jobs if j . alias in job . depends_on ) none_failed = not any ( True for j in self . failed if j . alias in job . depends_on ) queue_is_open = len ( self . running ) < self . MAX_CONCURRENT...
Determines if the job is ready to be sumitted to the queue . It checks if the job depends on any currently running or queued operations .
15,983
def locked ( self ) : if len ( self . failed ) == 0 : return False for fail in self . failed : for job in self . active_jobs : if fail . alias in job . depends_on : return True
Determines if the queue is locked .
15,984
def read_args ( ** kwargs ) : if kwargs . get ( "control" ) : args = Namespace ( control = kwargs [ "control" ] ) elif config . CONTROLFILE : args = Namespace ( control = config . CONTROLFILE ) elif config . DB . get ( "control_table_name" ) : args = Namespace ( control = "sql" ) elif config . AWS . get ( "control_tabl...
Read controlfile parameter .
15,985
def best_assemblyfile ( self ) : for sample in self . metadata : assembly_file = os . path . join ( sample . general . spadesoutput , 'contigs.fasta' ) if os . path . isfile ( assembly_file ) : sample . general . bestassemblyfile = assembly_file else : sample . general . bestassemblyfile = 'NA' filteredfile = os . path...
Determine whether the contigs . fasta output file from SPAdes is present . If not set the . bestassembly attribute to NA
15,986
def assemble ( self ) : threadlock = threading . Lock ( ) while True : ( sample , command ) = self . assemblequeue . get ( ) if command and not os . path . isfile ( os . path . join ( sample . general . spadesoutput , 'contigs.fasta' ) ) : out , err = run_subprocess ( command ) threadlock . acquire ( ) write_to_logfile...
Run the assembly command in a multi - threaded fashion
15,987
def get_diff_amounts ( self ) : diffs = [ ] last_commit = None for commit in self . repo . iter_commits ( ) : if last_commit is not None : diff = self . get_diff ( commit . hexsha , last_commit . hexsha ) total_changed = diff [ Diff . ADD ] + diff [ Diff . DEL ] diffs . append ( total_changed ) last_commit = commit ret...
Gets list of total diff
15,988
def get_new_version ( self , last_version , last_commit , diff_to_increase_ratio ) : version = Version ( last_version ) diff = self . get_diff ( last_commit , self . get_last_commit_hash ( ) ) total_changed = diff [ Diff . ADD ] + diff [ Diff . DEL ] version . increase_by_changes ( total_changed , diff_to_increase_rati...
Gets new version
15,989
def get_mime_message ( subject , text ) : message = MIMEText ( "<html>" + str ( text ) . replace ( "\n" , "<br>" ) + "</html>" , "html" ) message [ "subject" ] = str ( subject ) return message
Creates MIME message
15,990
def send_email ( sender , msg , driver ) : driver . users ( ) . messages ( ) . send ( userId = sender , body = msg ) . execute ( )
Sends email to me with this message
15,991
def get_readme ( ) : try : import pypandoc description = pypandoc . convert ( 'README.md' , 'rst' ) except ( IOError , ImportError ) : description = open ( 'README.md' ) . read ( ) return description
Get the contents of the README . rst file as a Unicode string .
15,992
def get_absolute_path ( * args ) : directory = os . path . dirname ( os . path . abspath ( __file__ ) ) return os . path . join ( directory , * args )
Transform relative pathnames into absolute pathnames .
15,993
def trim ( self , key ) : current_index = self . meta [ key ] [ 'cursor' ] self . hdf5 [ key ] . resize ( current_index , axis = 0 )
Removes empty rows from dataset ... I am still wanting to use this???
15,994
def get_channel_page ( self ) : channel_url = YOUTUBE_USER_BASE_URL + self . channel_name source_page = Webpage ( channel_url ) . get_html_source ( ) return source_page
Fetches source page
15,995
def get_feed_url_from_video ( video_url ) : web_page = Webpage ( video_url ) web_page . get_html_source ( ) channel_id = web_page . soup . find_all ( "div" , { "class" : "yt-user-info" } ) [ 0 ] . a [ "href" ] channel_id = str ( channel_id ) . strip ( ) . replace ( "/channel/" , "" ) return YoutubeChannel . get_feed_ur...
Gets channel id and then creates feed url
15,996
def process_file ( path ) : info = dict ( ) with fits . open ( path ) as hdu : head = hdu [ 0 ] . header data = hdu [ 0 ] . data labels = { theme : value for value , theme in list ( hdu [ 1 ] . data ) } info [ 'filename' ] = os . path . basename ( path ) info [ 'trainer' ] = head [ 'expert' ] info [ 'date-label' ] = da...
Open a single labeled image at path and get needed information return as a dictionary
15,997
def plot_counts ( df , theme ) : dates , counts = df [ 'date-observation' ] , df [ theme + "_count" ] fig , ax = plt . subplots ( ) ax . set_ylabel ( "{} pixel counts" . format ( " " . join ( theme . split ( "_" ) ) ) ) ax . set_xlabel ( "observation date" ) ax . plot ( dates , counts , '.' ) fig . autofmt_xdate ( ) pl...
plot the counts of a given theme from a created database over time
15,998
def deformat ( value ) : output = [ ] for c in value : if c in delchars : continue output . append ( c ) return "" . join ( output )
REMOVE NON - ALPHANUMERIC CHARACTERS
15,999
def _expand ( template , seq ) : if is_text ( template ) : return _simple_expand ( template , seq ) elif is_data ( template ) : template = wrap ( template ) assert template [ "from" ] , "Expecting template to have 'from' attribute" assert template . template , "Expecting template to have 'template' attribute" data = se...
seq IS TUPLE OF OBJECTS IN PATH ORDER INTO THE DATA TREE