idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
54,400 | def on_exit ( self ) : answer = messagebox . askyesnocancel ( "Exit" , "Do you want to save as you quit the application?" ) if answer : self . save ( ) self . quit ( ) self . destroy ( ) elif answer is None : pass else : self . quit ( ) self . destroy ( ) | When you click to exit this function is called prompts whether to save |
54,401 | def make_gui ( self ) : self . option_window = Toplevel ( ) self . option_window . protocol ( "WM_DELETE_WINDOW" , self . on_exit ) self . canvas_frame = tk . Frame ( self , height = 500 ) self . option_frame = tk . Frame ( self . option_window , height = 300 ) self . canvas_frame . pack ( side = tk . LEFT , fill = tk ... | Setups the general structure of the gui the first function called |
54,402 | def make_options_frame ( self ) : self . tab_frame = ttk . Notebook ( self . option_frame , width = 800 ) self . tab_configure = tk . Frame ( self . tab_frame ) self . tab_classify = tk . Frame ( self . tab_frame ) self . make_configure_tab ( ) self . make_classify_tab ( ) self . tab_frame . add ( self . tab_configure ... | make the frame that allows for configuration and classification |
54,403 | def disable_multicolor ( self ) : for color in [ 'red' , 'green' , 'blue' ] : self . multicolorscales [ color ] . config ( state = tk . DISABLED , bg = 'grey' ) self . multicolorframes [ color ] . config ( bg = 'grey' ) self . multicolorlabels [ color ] . config ( bg = 'grey' ) self . multicolordropdowns [ color ] . co... | swap from the multicolor image to the single color image |
54,404 | def update_button_action ( self ) : if self . mode . get ( ) == 3 : self . configure_threecolor_image ( ) elif self . mode . get ( ) == 1 : self . configure_singlecolor_image ( ) else : raise ValueError ( "mode can only be singlecolor or threecolor" ) self . imageplot . set_data ( self . image ) if self . mode . get ( ... | when update button is clicked refresh the data preview |
54,405 | def make_configure_tab ( self ) : modeframe = tk . Frame ( self . tab_configure ) self . mode = tk . IntVar ( ) singlecolor = tk . Radiobutton ( modeframe , text = "Single color" , variable = self . mode , value = 1 , command = lambda : self . disable_multicolor ( ) ) multicolor = tk . Radiobutton ( modeframe , text = ... | initial set up of configure tab |
54,406 | def make_classify_tab ( self ) : self . pick_frame = tk . Frame ( self . tab_classify ) self . pick_frame2 = tk . Frame ( self . tab_classify ) self . solar_class_var = tk . IntVar ( ) self . solar_class_var . set ( 0 ) buttonnum = 0 frame = [ self . pick_frame , self . pick_frame2 ] for text , value in self . config .... | initial set up of classification tab |
54,407 | def setup_singlecolor ( self ) : self . singlecolorframe = tk . Frame ( self . tab_configure , bg = self . single_color_theme ) channel_choices = sorted ( list ( self . data . keys ( ) ) ) self . singlecolorlabel = tk . Label ( self . singlecolorframe , text = "single" , bg = self . single_color_theme , width = 10 ) se... | initial setup of single color options and variables |
54,408 | def undobutton_action ( self ) : if len ( self . history ) > 1 : old = self . history . pop ( - 1 ) self . selection_array = old self . mask . set_data ( old ) self . fig . canvas . draw_idle ( ) | when undo is clicked revert the thematic map to the previous state |
54,409 | def change_class ( self ) : self . toolbarcenterframe . config ( text = "Draw: {}" . format ( self . config . solar_class_name [ self . solar_class_var . get ( ) ] ) ) | on changing the classification label update the draw text |
54,410 | def values ( self ) : self . vals [ 'nfft' ] = self . ui . nfftSpnbx . value ( ) self . vals [ 'window' ] = str ( self . ui . windowCmbx . currentText ( ) ) . lower ( ) self . vals [ 'overlap' ] = self . ui . overlapSpnbx . value ( ) return self . vals | Gets the parameter values |
54,411 | def main ( ) : parser = argparse . ArgumentParser ( description = 'A pipeline that generates analysis pipelines.' ) parser . add_argument ( 'input' , nargs = '?' , help = 'A valid metapipe configuration file.' ) parser . add_argument ( '-o' , '--output' , help = 'An output destination. If none is provided, the ' 'resul... | Parses the command - line args and calls run . |
54,412 | def run ( config , max_jobs , output = sys . stdout , job_type = 'local' , report_type = 'text' , shell = '/bin/bash' , temp = '.metapipe' , run_now = False ) : if max_jobs == None : max_jobs = cpu_count ( ) parser = Parser ( config ) try : command_templates = parser . consume ( ) except ValueError as e : raise SyntaxE... | Create the metapipe based on the provided input . |
54,413 | def make_submit_job ( shell , output , job_type ) : run_cmd = [ shell , output ] submit_command = Command ( alias = PIPELINE_ALIAS , cmds = run_cmd ) submit_job = get_job ( submit_command , job_type ) submit_job . make ( ) return submit_job | Preps the metapipe main job to be submitted . |
54,414 | def yaml ( modules_to_register : Iterable [ Any ] = None , classes_to_register : Iterable [ Any ] = None ) -> ruamel . yaml . YAML : yaml = ruamel . yaml . YAML ( typ = "rt" ) yaml . representer . add_representer ( np . ndarray , numpy_to_yaml ) yaml . constructor . add_constructor ( "!numpy_array" , numpy_from_yaml ) ... | Create a YAML object for loading a YAML configuration . |
54,415 | def register_classes ( yaml : ruamel . yaml . YAML , classes : Optional [ Iterable [ Any ] ] = None ) -> ruamel . yaml . YAML : if classes is None : classes = [ ] for cls in classes : logger . debug ( f"Registering class {cls} with YAML" ) yaml . register_class ( cls ) return yaml | Register externally defined classes . |
54,416 | def register_module_classes ( yaml : ruamel . yaml . YAML , modules : Optional [ Iterable [ Any ] ] = None ) -> ruamel . yaml . YAML : if modules is None : modules = [ ] classes_to_register = set ( ) for module in modules : module_classes = [ member [ 1 ] for member in inspect . getmembers ( module , inspect . isclass ... | Register all classes in the given modules with the YAML object . |
54,417 | def numpy_to_yaml ( representer : Representer , data : np . ndarray ) -> Sequence [ Any ] : return representer . represent_sequence ( "!numpy_array" , data . tolist ( ) ) | Write a numpy array to YAML . |
54,418 | def numpy_from_yaml ( constructor : Constructor , data : ruamel . yaml . nodes . SequenceNode ) -> np . ndarray : values = [ constructor . construct_object ( n ) for n in data . value ] logger . debug ( f"{data}, {values}" ) return np . array ( values ) | Read an array from YAML to numpy . |
54,419 | def enum_to_yaml ( cls : Type [ T_EnumToYAML ] , representer : Representer , data : T_EnumToYAML ) -> ruamel . yaml . nodes . ScalarNode : return representer . represent_scalar ( f"!{cls.__name__}" , f"{str(data)}" ) | Encodes YAML representation . |
54,420 | def enum_from_yaml ( cls : Type [ T_EnumFromYAML ] , constructor : Constructor , node : ruamel . yaml . nodes . ScalarNode ) -> T_EnumFromYAML : return cls [ node . value ] | Decode YAML representation . |
54,421 | def _get_current_ids ( self , source = True , meta = True , spectra = True , spectra_annotation = True ) : c = self . c if source : c . execute ( 'SELECT max(id) FROM library_spectra_source' ) last_id_origin = c . fetchone ( ) [ 0 ] if last_id_origin : self . current_id_origin = last_id_origin + 1 else : self . current... | Get the current id for each table in the database |
54,422 | def _update_libdata ( self , line ) : if re . match ( '^Comment.*$' , line , re . IGNORECASE ) : comments = re . findall ( '"([^"]*)"' , line ) for c in comments : self . _parse_meta_info ( c ) self . _parse_compound_info ( c ) self . _parse_meta_info ( line ) self . _parse_compound_info ( line ) if self . collect_meta... | Update the library meta data from the current line being parsed |
54,423 | def _store_compound_info ( self ) : other_name_l = [ name for name in self . other_names if name != self . compound_info [ 'name' ] ] self . compound_info [ 'other_names' ] = ' <#> ' . join ( other_name_l ) if not self . compound_info [ 'inchikey_id' ] : self . _set_inchi_pcc ( self . compound_info [ 'pubchem_id' ] , '... | Update the compound_info dictionary with the current chunk of compound details |
54,424 | def _store_meta_info ( self ) : if not self . meta_info [ 'precursor_mz' ] and self . meta_info [ 'precursor_type' ] and self . compound_info [ 'exact_mass' ] : self . meta_info [ 'precursor_mz' ] = get_precursor_mz ( float ( self . compound_info [ 'exact_mass' ] ) , self . meta_info [ 'precursor_type' ] ) if not self ... | Update the meta dictionary with the current chunk of meta data details |
54,425 | def _parse_spectra_annotation ( self , line ) : if re . match ( '^PK\$NUM_PEAK(.*)' , line , re . IGNORECASE ) : self . start_spectra_annotation = False return saplist = line . split ( ) sarow = ( self . current_id_spectra_annotation , float ( saplist [ self . spectra_annotation_indexes [ 'm/z' ] ] ) if 'm/z' in self .... | Parse and store the spectral annotation details |
54,426 | def _parse_spectra ( self , line ) : if line in [ '\n' , '\r\n' , '//\n' , '//\r\n' , '' , '//' ] : self . start_spectra = False self . current_id_meta += 1 self . collect_meta = True return splist = line . split ( ) if len ( splist ) > 2 and not self . ignore_additional_spectra_info : additional_info = '' . join ( map... | Parse and store the spectral details |
54,427 | def _set_inchi_pcc ( self , in_str , pcp_type , elem ) : if not in_str : return 0 try : pccs = pcp . get_compounds ( in_str , pcp_type ) except pcp . BadRequestError as e : print ( e ) return 0 except pcp . TimeoutError as e : print ( e ) return 0 except pcp . ServerError as e : print ( e ) return 0 except URLError as ... | Check pubchem compounds via API for both an inchikey and any available compound details |
54,428 | def _get_other_names ( self , line ) : m = re . search ( self . compound_regex [ 'other_names' ] [ 0 ] , line , re . IGNORECASE ) if m : self . other_names . append ( m . group ( 1 ) . strip ( ) ) | Parse and extract any other names that might be recorded for the compound |
54,429 | def _parse_meta_info ( self , line ) : if self . mslevel : self . meta_info [ 'ms_level' ] = self . mslevel if self . polarity : self . meta_info [ 'polarity' ] = self . polarity for k , regexes in six . iteritems ( self . meta_regex ) : for reg in regexes : m = re . search ( reg , line , re . IGNORECASE ) if m : self ... | Parse and extract all meta data by looping through the dictionary of meta_info regexs |
54,430 | def _parse_compound_info ( self , line ) : for k , regexes in six . iteritems ( self . compound_regex ) : for reg in regexes : if self . compound_info [ k ] : continue m = re . search ( reg , line , re . IGNORECASE ) if m : self . compound_info [ k ] = m . group ( 1 ) . strip ( ) self . _get_other_names ( line ) | Parse and extract all compound data by looping through the dictionary of compound_info regexs |
54,431 | def insert_data ( self , remove_data = False , db_type = 'sqlite' ) : if self . update_source : import msp2db self . c . execute ( "INSERT INTO library_spectra_source (id, name, parsing_software) VALUES" " ({a}, '{b}', 'msp2db-v{c}')" . format ( a = self . current_id_origin , b = self . source , c = msp2db . __version_... | Insert data stored in the current chunk of parsing into the selected database |
54,432 | def line ( line_def , ** kwargs ) : def replace ( s ) : return "(%s)" % ansi . aformat ( s . group ( ) [ 1 : ] , attrs = [ "bold" , ] ) return ansi . aformat ( re . sub ( '@.?' , replace , line_def ) , ** kwargs ) | Highlights a character in the line |
54,433 | def try_and_error ( * funcs ) : def validate ( value ) : exc = None for func in funcs : try : return func ( value ) except ( ValueError , TypeError ) as e : exc = e raise exc return validate | Apply multiple validation functions |
54,434 | def validate_text ( value ) : possible_transform = [ 'axes' , 'fig' , 'data' ] validate_transform = ValidateInStrings ( 'transform' , possible_transform , True ) tests = [ validate_float , validate_float , validate_str , validate_transform , dict ] if isinstance ( value , six . string_types ) : xpos , ypos = rcParams [... | Validate a text formatoption |
54,435 | def validate_none ( b ) : if isinstance ( b , six . string_types ) : b = b . lower ( ) if b is None or b == 'none' : return None else : raise ValueError ( 'Could not convert "%s" to None' % b ) | Validate that None is given |
54,436 | def validate_axiscolor ( value ) : validate = try_and_error ( validate_none , validate_color ) possible_keys = { 'right' , 'left' , 'top' , 'bottom' } try : value = dict ( value ) false_keys = set ( value ) - possible_keys if false_keys : raise ValueError ( "Wrong keys (%s)!" % ( ', ' . join ( false_keys ) ) ) for key ... | Validate a dictionary containing axiscolor definitions |
54,437 | def validate_cbarpos ( value ) : patt = 'sh|sv|fl|fr|ft|fb|b|r' if value is True : value = { 'b' } elif not value : value = set ( ) elif isinstance ( value , six . string_types ) : for s in re . finditer ( '[^%s]+' % patt , value ) : warn ( "Unknown colorbar position %s!" % s . group ( ) , RuntimeWarning ) value = set ... | Validate a colorbar position |
54,438 | def validate_cmap ( val ) : from matplotlib . colors import Colormap try : return validate_str ( val ) except ValueError : if not isinstance ( val , Colormap ) : raise ValueError ( "Could not find a valid colormap!" ) return val | Validate a colormap |
54,439 | def validate_cmaps ( cmaps ) : cmaps = { validate_str ( key ) : validate_colorlist ( val ) for key , val in cmaps } for key , val in six . iteritems ( cmaps ) : cmaps . setdefault ( key + '_r' , val [ : : - 1 ] ) return cmaps | Validate a dictionary of color lists |
54,440 | def validate_lineplot ( value ) : if value is None : return value elif isinstance ( value , six . string_types ) : return six . text_type ( value ) else : value = list ( value ) for i , v in enumerate ( value ) : if v is None : pass elif isinstance ( v , six . string_types ) : value [ i ] = six . text_type ( v ) else :... | Validate the value for the LinePlotter . plot formatoption |
54,441 | def visit_GpxModel ( self , gpx_model , * args , ** kwargs ) : result = OrderedDict ( ) put_scalar = lambda name , json_name = None : self . optional_attribute_scalar ( result , gpx_model , name , json_name ) put_list = lambda name , json_name = None : self . optional_attribute_list ( result , gpx_model , name , json_n... | Render a GPXModel as a single JSON structure . |
54,442 | def visit_Metadata ( self , metadata , * args , ** kwargs ) : result = OrderedDict ( ) put_scalar = lambda name , json_name = None : self . optional_attribute_scalar ( result , metadata , name , json_name ) put_list = lambda name , json_name = None : self . optional_attribute_list ( result , metadata , name , json_name... | Render GPX Metadata as a single JSON structure . |
54,443 | def swap_default ( mode , equation , symbol_names , default , ** kwargs ) : if mode == 'subs' : swap_f = _subs default_swap_f = _subs elif mode == 'limit' : swap_f = _limit default_swap_f = _subs elif mode == 'limit_default' : swap_f = _subs default_swap_f = _limit else : raise ValueError ( ) result = equation for s in... | Given a sympy equation or equality along with a list of symbol names substitute the specified default value for each symbol for which a value is not provided through a keyword argument . |
54,444 | def z_transfer_functions ( ) : r V1 , V2 , Z1 , Z2 = sp . symbols ( 'V1 V2 Z1 Z2' ) xfer_funcs = pd . Series ( [ sp . Eq ( V2 / Z2 , V1 / ( Z1 + Z2 ) ) , sp . Eq ( V2 / V1 , Z2 / Z1 ) ] , index = [ 1 , 2 ] ) xfer_funcs . index . name = 'Hardware version' return xfer_funcs | r Return a symbolic equality representation of the transfer function of RMS voltage measured by either control board analog feedback circuits . |
54,445 | def has_option ( section , name ) : cfg = ConfigParser . SafeConfigParser ( { "working_dir" : "/tmp" , "debug" : "0" } ) cfg . read ( CONFIG_LOCATIONS ) return cfg . has_option ( section , name ) | Wrapper around ConfigParser s has_option method . |
54,446 | def get ( section , name ) : cfg = ConfigParser . SafeConfigParser ( { "working_dir" : "/tmp" , "debug" : "0" } ) cfg . read ( CONFIG_LOCATIONS ) val = cfg . get ( section , name ) return val . strip ( "'" ) . strip ( '"' ) | Wrapper around ConfigParser s get method . |
54,447 | def make_key ( table_name , objid ) : key = datastore . Key ( ) path = key . path_element . add ( ) path . kind = table_name path . name = str ( objid ) return key | Create an object key for storage . |
54,448 | def extract_entity ( found ) : obj = dict ( ) for prop in found . entity . property : obj [ prop . name ] = prop . value . string_value return obj | Copy found entity to a dict . |
54,449 | def read_rec ( table_name , objid ) : req = datastore . LookupRequest ( ) req . key . extend ( [ make_key ( table_name , objid ) ] ) for found in datastore . lookup ( req ) . found : yield extract_entity ( found ) | Generator that yields keyed recs from store . |
54,450 | def read_by_indexes ( table_name , index_name_values = None ) : req = datastore . RunQueryRequest ( ) query = req . query query . kind . add ( ) . name = table_name if not index_name_values : index_name_values = [ ] for name , val in index_name_values : queryFilter = query . filter . property_filter queryFilter . prope... | Index reader . |
54,451 | def delete_table ( table_name ) : to_delete = [ make_key ( table_name , rec [ 'id' ] ) for rec in read_by_indexes ( table_name , [ ] ) ] with DatastoreTransaction ( ) as tx : tx . get_commit_req ( ) . mutation . delete . extend ( to_delete ) | Mainly for testing . |
54,452 | def get_commit_req ( self ) : if not self . commit_req : self . commit_req = datastore . CommitRequest ( ) self . commit_req . transaction = self . tx return self . commit_req | Lazy commit request getter . |
54,453 | def call ( command , stdin = None , stdout = subprocess . PIPE , env = os . environ , cwd = None , shell = False , output_log_level = logging . INFO , sensitive_info = False ) : if not sensitive_info : logger . debug ( "calling command: %s" % command ) else : logger . debug ( "calling command with sensitive information... | Better smarter call logic |
54,454 | def whitespace_smart_split ( command ) : return_array = [ ] s = "" in_double_quotes = False escape = False for c in command : if c == '"' : if in_double_quotes : if escape : s += c escape = False else : s += c in_double_quotes = False else : in_double_quotes = True s += c else : if in_double_quotes : if c == '\\' : esc... | Split a command by whitespace taking care to not split on whitespace within quotes . |
54,455 | def sync ( self ) : phase = _get_phase ( self . _formula_instance ) self . logger . info ( "%s %s..." % ( phase . verb . capitalize ( ) , self . feature_name ) ) message = "...finished %s %s." % ( phase . verb , self . feature_name ) result = getattr ( self , phase . name ) ( ) if result or phase in ( PHASE . INSTALL ,... | execute the steps required to have the feature end with the desired state . |
54,456 | def isloaded ( self , name ) : if name is None : return True if isinstance ( name , str ) : return ( name in [ x . __module__ for x in self ] ) if isinstance ( name , Iterable ) : return set ( name ) . issubset ( [ x . __module__ for x in self ] ) return False | Checks if given hook module has been loaded |
54,457 | def hook ( self , function , dependencies = None ) : if not isinstance ( dependencies , ( Iterable , type ( None ) , str ) ) : raise TypeError ( "Invalid list of dependencies provided!" ) if not hasattr ( function , "__deps__" ) : function . __deps__ = dependencies if self . isloaded ( function . __deps__ ) : self . ap... | Tries to load a hook |
54,458 | def parse_from_json ( json_str ) : try : message_dict = json . loads ( json_str ) except ValueError : raise ParseError ( "Mal-formed JSON input." ) upload_keys = message_dict . get ( 'uploadKeys' , False ) if upload_keys is False : raise ParseError ( "uploadKeys does not exist. At minimum, an empty array is required." ... | Given a Unified Uploader message parse the contents and return a MarketOrderList or MarketHistoryList instance . |
54,459 | def encode_to_json ( order_or_history ) : if isinstance ( order_or_history , MarketOrderList ) : return orders . encode_to_json ( order_or_history ) elif isinstance ( order_or_history , MarketHistoryList ) : return history . encode_to_json ( order_or_history ) else : raise Exception ( "Must be one of MarketOrderList or... | Given an order or history entry encode it to JSON and return . |
54,460 | def add ( self , classifier , threshold , begin = None , end = None ) : boosted_machine = bob . learn . boosting . BoostedMachine ( ) if begin is None : begin = 0 if end is None : end = len ( classifier . weak_machines ) for i in range ( begin , end ) : boosted_machine . add_weak_machine ( classifier . weak_machines [ ... | Adds a new strong classifier with the given threshold to the cascade . |
54,461 | def create_from_boosted_machine ( self , boosted_machine , classifiers_per_round , classification_thresholds = - 5. ) : indices = list ( range ( 0 , len ( boosted_machine . weak_machines ) , classifiers_per_round ) ) if indices [ - 1 ] != len ( boosted_machine . weak_machines ) : indices . append ( len ( boosted_machin... | Creates this cascade from the given boosted machine by simply splitting off strong classifiers that have classifiers_per_round weak classifiers . |
54,462 | def save ( self , hdf5 ) : hdf5 . set ( "Thresholds" , self . thresholds ) for i in range ( len ( self . cascade ) ) : hdf5 . create_group ( "Classifier_%d" % ( i + 1 ) ) hdf5 . cd ( "Classifier_%d" % ( i + 1 ) ) self . cascade [ i ] . save ( hdf5 ) hdf5 . cd ( ".." ) hdf5 . create_group ( "FeatureExtractor" ) hdf5 . c... | Saves this cascade into the given HDF5 file . |
54,463 | def load ( self , hdf5 ) : self . thresholds = hdf5 . read ( "Thresholds" ) self . cascade = [ ] for i in range ( len ( self . thresholds ) ) : hdf5 . cd ( "Classifier_%d" % ( i + 1 ) ) self . cascade . append ( bob . learn . boosting . BoostedMachine ( hdf5 ) ) hdf5 . cd ( ".." ) hdf5 . cd ( "FeatureExtractor" ) self ... | Loads this cascade from the given HDF5 file . |
54,464 | def check ( ctx , repository , config ) : ctx . obj = Repo ( repository = repository , config = config ) | Check commits . |
54,465 | def message ( obj , commit = 'HEAD' , skip_merge_commits = False ) : from . . kwalitee import check_message options = obj . options repository = obj . repository if options . get ( 'colors' ) is not False : colorama . init ( autoreset = True ) reset = colorama . Style . RESET_ALL yellow = colorama . Fore . YELLOW green... | Check the messages of the commits . |
54,466 | def get_obj_subcmds ( obj ) : subcmds = [ ] for label in dir ( obj . __class__ ) : if label . startswith ( "_" ) : continue if isinstance ( getattr ( obj . __class__ , label , False ) , property ) : continue rvalue = getattr ( obj , label ) if not callable ( rvalue ) or not is_cmd ( rvalue ) : continue if isinstance ( ... | Fetch action in callable attributes which and commands |
54,467 | def get_module_resources ( mod ) : path = os . path . dirname ( os . path . realpath ( mod . __file__ ) ) prefix = kf . basename ( mod . __file__ , ( ".py" , ".pyc" ) ) if not os . path . exists ( mod . __file__ ) : import pkg_resources for resource_name in pkg_resources . resource_listdir ( mod . __name__ , '' ) : if ... | Return probed sub module names from given module |
54,468 | def get_mod_subcmds ( mod ) : subcmds = get_obj_subcmds ( mod ) path = os . path . dirname ( os . path . realpath ( mod . __file__ ) ) if mod . __package__ is None : sys . path . insert ( 0 , os . path . dirname ( path ) ) mod . __package__ = kf . basename ( path ) for module_name in get_module_resources ( mod ) : try ... | Fetch action in same directory in python module |
54,469 | def get_help ( obj , env , subcmds ) : doc = txt . dedent ( obj . __doc__ or "" ) env = env . copy ( ) doc = doc . strip ( ) if not re . search ( r"^usage:\s*$" , doc , flags = re . IGNORECASE | re . MULTILINE ) : doc += txt . dedent ( ) help_line = ( " %%-%ds %%s" % ( max ( [ 5 ] + [ len ( a ) for a in subcmds ] ) ,... | Interpolate complete help doc of given object |
54,470 | def get_calling_prototype ( acallable ) : assert callable ( acallable ) if inspect . ismethod ( acallable ) or inspect . isfunction ( acallable ) : args , vargs , vkwargs , defaults = inspect . getargspec ( acallable ) elif not inspect . isfunction ( acallable ) and hasattr ( acallable , "__call__" ) : args , vargs , v... | Returns actual working calling prototype |
54,471 | def initialize ( self ) : if not os . path . exists ( self . root_dir ) : os . makedirs ( self . root_dir ) assert os . path . isdir ( self . root_dir ) , "%s is not a directory! Please move or remove it." % self . root_dir for d in [ "bin" , "lib" , "include" ] : target_path = os . path . join ( self . root_dir , d ) ... | Generate the root directory root if it doesn t already exist |
54,472 | def finalize ( self ) : if self . rc_file : self . rc_file . close ( ) if self . env_file : self . env_file . close ( ) | finalize any open file handles |
54,473 | def remove ( self ) : if self . rc_file : self . rc_file . close ( ) if self . env_file : self . env_file . close ( ) shutil . rmtree ( self . root_dir ) | Removes the sprinter directory if it exists |
54,474 | def symlink_to_bin ( self , name , path ) : self . __symlink_dir ( "bin" , name , path ) os . chmod ( os . path . join ( self . root_dir , "bin" , name ) , os . stat ( path ) . st_mode | stat . S_IXUSR | stat . S_IRUSR ) | Symlink an object at path to name in the bin folder . |
54,475 | def remove_feature ( self , feature_name ) : self . clear_feature_symlinks ( feature_name ) if os . path . exists ( self . install_directory ( feature_name ) ) : self . __remove_path ( self . install_directory ( feature_name ) ) | Remove an feature from the environment root folder . |
54,476 | def clear_feature_symlinks ( self , feature_name ) : logger . debug ( "Clearing feature symlinks for %s" % feature_name ) feature_path = self . install_directory ( feature_name ) for d in ( 'bin' , 'lib' ) : if os . path . exists ( os . path . join ( self . root_dir , d ) ) : for link in os . listdir ( os . path . join... | Clear the symlinks for a feature in the symlinked path |
54,477 | def add_to_env ( self , content ) : if not self . rewrite_config : raise DirectoryException ( "Error! Directory was not intialized w/ rewrite_config." ) if not self . env_file : self . env_path , self . env_file = self . __get_env_handle ( self . root_dir ) self . env_file . write ( content + '\n' ) | add content to the env script . |
54,478 | def add_to_rc ( self , content ) : if not self . rewrite_config : raise DirectoryException ( "Error! Directory was not intialized w/ rewrite_config." ) if not self . rc_file : self . rc_path , self . rc_file = self . __get_rc_handle ( self . root_dir ) self . rc_file . write ( content + '\n' ) | add content to the rc script . |
54,479 | def add_to_gui ( self , content ) : if not self . rewrite_config : raise DirectoryException ( "Error! Directory was not intialized w/ rewrite_config." ) if not self . gui_file : self . gui_path , self . gui_file = self . __get_gui_handle ( self . root_dir ) self . gui_file . write ( content + '\n' ) | add content to the gui script . |
54,480 | def __remove_path ( self , path ) : curpath = os . path . abspath ( os . curdir ) if not os . path . exists ( path ) : logger . warn ( "Attempted to remove a non-existent path %s" % path ) return try : if os . path . islink ( path ) : os . unlink ( path ) elif os . path . isdir ( path ) : shutil . rmtree ( path ) else ... | Remove an object |
54,481 | def __get_rc_handle ( self , root_dir ) : rc_path = os . path . join ( root_dir , '.rc' ) env_path = os . path . join ( root_dir , '.env' ) fh = open ( rc_path , "w+" ) fh . write ( source_template % ( env_path , env_path ) ) return ( rc_path , fh ) | get the filepath and filehandle to the rc file for the environment |
54,482 | def __symlink_dir ( self , dir_name , name , path ) : target_dir = os . path . join ( self . root_dir , dir_name ) if not os . path . exists ( target_dir ) : os . makedirs ( target_dir ) target_path = os . path . join ( self . root_dir , dir_name , name ) logger . debug ( "Attempting to symlink %s to %s..." % ( path , ... | Symlink an object at path to name in the dir_name folder . remove it if it already exists . |
54,483 | def list_docs ( self , options = None ) : if options is None : raise ValueError ( "Please pass in an options dict" ) default_options = { "page" : 1 , "per_page" : 100 , "raise_exception_on_failure" : False , "user_credentials" : self . api_key , } options = dict ( list ( default_options . items ( ) ) + list ( options .... | Return list of previously created documents . |
54,484 | def status ( self , status_id , raise_exception_on_failure = False ) : query = { "output" : "json" , "user_credentials" : self . api_key } resp = requests . get ( "%sstatus/%s" % ( self . _url , status_id ) , params = query , timeout = self . _timeout ) if raise_exception_on_failure and resp . status_code != 200 : rais... | Return the status of the generation job . |
54,485 | def download ( self , download_key , raise_exception_on_failure = False ) : query = { "output" : "json" , "user_credentials" : self . api_key } resp = requests . get ( "%sdownload/%s" % ( self . _url , download_key ) , params = query , timeout = self . _timeout , ) if raise_exception_on_failure and resp . status_code !... | Download the file represented by the download_key . |
54,486 | def _get_parsing_plan_for_multifile_children ( self , obj_on_fs : PersistedObject , desired_type : Type [ Any ] , logger : Logger ) -> Dict [ str , Any ] : n_children = len ( obj_on_fs . get_multifile_children ( ) ) subtypes , key_type = _extract_collection_base_type ( desired_type ) if isinstance ( subtypes , tuple ) ... | Simply inspects the required type to find the base type expected for items of the collection and relies on the ParserFinder to find the parsing plan |
54,487 | def plot_stat_summary ( df , fig = None ) : if fig is None : fig = plt . figure ( figsize = ( 8 , 8 ) ) grid = GridSpec ( 3 , 2 ) stats = calculate_stats ( df , groupby = [ 'test_capacitor' , 'frequency' ] ) . dropna ( ) for i , stat in enumerate ( [ 'RMSE %' , 'cv %' , 'bias %' ] ) : axis = fig . add_subplot ( grid [ ... | Plot stats grouped by test capacitor load _and_ frequency . |
54,488 | def load_manifest ( raw_manifest , namespace = None , ** kwargs ) : if isinstance ( raw_manifest , configparser . RawConfigParser ) : return Manifest ( raw_manifest ) manifest = create_configparser ( ) if not manifest . has_section ( 'config' ) : manifest . add_section ( 'config' ) _load_manifest_interpret_source ( man... | wrapper method which generates the manifest from various sources |
54,489 | def _load_manifest_from_url ( manifest , url , verify_certificate = True , username = None , password = None ) : try : if username and password : manifest_file_handler = StringIO ( lib . authenticated_get ( username , password , url , verify = verify_certificate ) . decode ( "utf-8" ) ) else : manifest_file_handler = S... | load a url body into a manifest |
54,490 | def _load_manifest_from_file ( manifest , path ) : path = os . path . abspath ( os . path . expanduser ( path ) ) if not os . path . exists ( path ) : raise ManifestException ( "Manifest does not exist at {0}!" . format ( path ) ) manifest . read ( path ) if not manifest . has_option ( 'config' , 'source' ) : manifest ... | load manifest from file |
54,491 | def formula_sections ( self ) : if self . dtree is not None : return self . dtree . order else : return [ s for s in self . manifest . sections ( ) if s != "config" ] | Return all sections related to a formula re - ordered according to the depends section . |
54,492 | def is_affirmative ( self , section , option ) : return self . has_option ( section , option ) and lib . is_affirmative ( self . get ( section , option ) ) | Return true if the section option combo exists and it is set to a truthy value . |
54,493 | def write ( self , file_handle ) : for k , v in self . inputs . write_values ( ) . items ( ) : self . set ( 'config' , k , v ) self . set ( 'config' , 'namespace' , self . namespace ) self . manifest . write ( file_handle ) | write the current state to a file manifest |
54,494 | def get_context_dict ( self ) : context_dict = { } for s in self . sections ( ) : for k , v in self . manifest . items ( s ) : context_dict [ "%s:%s" % ( s , k ) ] = v for k , v in self . inputs . values ( ) . items ( ) : context_dict [ "config:{0}" . format ( k ) ] = v context_dict . update ( self . additional_context... | return a context dict of the desired state |
54,495 | def get ( self , section , key , default = MANIFEST_NULL_KEY ) : if not self . manifest . has_option ( section , key ) and default is not MANIFEST_NULL_KEY : return default return self . manifest . get ( section , key ) | Returns the value if it exist or default if default is set |
54,496 | def __parse_namespace ( self ) : if self . manifest . has_option ( 'config' , 'namespace' ) : return self . manifest . get ( 'config' , 'namespace' ) elif self . manifest . has_option ( 'config' , 'source' ) : return NAMESPACE_REGEX . search ( self . manifest . get ( 'config' , 'source' ) ) . groups ( ) [ 0 ] else : lo... | Parse the namespace from various sources |
54,497 | def __generate_dependency_tree ( self ) : dependency_dict = { } for s in self . manifest . sections ( ) : if s != "config" : if self . manifest . has_option ( s , 'depends' ) : dependency_list = [ d . strip ( ) for d in re . split ( '\n|,' , self . manifest . get ( s , 'depends' ) ) ] dependency_dict [ s ] = dependency... | Generate the dependency tree object |
54,498 | def __substitute_objects ( self , value , context_dict ) : if type ( value ) == dict : return dict ( [ ( k , self . __substitute_objects ( v , context_dict ) ) for k , v in value . items ( ) ] ) elif type ( value ) == str : try : return value % context_dict except KeyError : e = sys . exc_info ( ) [ 1 ] logger . warn (... | recursively substitute value with the context_dict |
54,499 | def __setup_inputs ( self ) : input_object = Inputs ( ) for s in self . manifest . sections ( ) : if self . has_option ( s , 'inputs' ) : input_object . add_inputs_from_inputstring ( self . get ( s , 'inputs' ) ) for k , v in self . items ( 'config' ) : if input_object . is_input ( s ) : input_object . set_input ( k , ... | Setup the inputs object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.