idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
7,800 | def projectname ( self ) : if self . _projectname is None : exps = self . config . experiments if self . _experiment is not None and self . _experiment in exps : return exps [ self . _experiment ] [ 'project' ] try : self . _projectname = list ( self . config . projects . keys ( ) ) [ - 1 ] except IndexError : raise ValueError ( "No experiment has yet been created! Please run setup " "before." ) return self . _projectname | The name of the project that is currently processed |
7,801 | def experiment ( self ) : if self . _experiment is None : self . _experiment = list ( self . config . experiments . keys ( ) ) [ - 1 ] return self . _experiment | The identifier or the experiment that is currently processed |
7,802 | def app_main ( self , experiment = None , last = False , new = False , verbose = False , verbosity_level = None , no_modification = False , match = False ) : if match : patt = re . compile ( experiment ) matches = list ( filter ( patt . search , self . config . experiments ) ) if len ( matches ) > 1 : raise ValueError ( "Found multiple matches for %s: %s" % ( experiment , matches ) ) elif len ( matches ) == 0 : raise ValueError ( "No experiment matches %s" % experiment ) experiment = matches [ 0 ] if last and self . config . experiments : self . experiment = None elif new and self . config . experiments : try : self . experiment = utils . get_next_name ( self . experiment ) except ValueError : raise ValueError ( "Could not estimate an experiment id! Please use the " "experiment argument to provide an id." ) else : self . _experiment = experiment if verbose : verbose = logging . DEBUG elif verbosity_level : if verbosity_level in [ 'DEBUG' , 'INFO' , 'WARNING' , 'ERROR' ] : verbose = getattr ( logging , verbosity_level ) else : verbose = int ( verbosity_level ) if verbose : logging . getLogger ( utils . get_toplevel_module ( inspect . getmodule ( self ) ) ) . setLevel ( verbose ) self . logger . setLevel ( verbose ) self . no_modification = no_modification | The main function for parsing global arguments |
7,803 | def setup ( self , root_dir , projectname = None , link = False , ** kwargs ) : projects = self . config . projects if not projects and projectname is None : projectname = self . name + '0' elif projectname is None : try : projectname = utils . get_next_name ( self . projectname ) except ValueError : raise ValueError ( "Could not estimate a project name! Please use the " "projectname argument to provide a project name." ) self . app_main ( ** kwargs ) root_dir = osp . abspath ( osp . join ( root_dir , projectname ) ) projects [ projectname ] = OrderedDict ( [ ( 'name' , projectname ) , ( 'root' , root_dir ) , ( 'timestamps' , OrderedDict ( ) ) ] ) data_dir = self . config . global_config . get ( 'data' , osp . join ( root_dir , 'data' ) ) projects [ projectname ] [ 'data' ] = data_dir self . projectname = projectname self . logger . info ( "Initializing project %s" , projectname ) self . logger . debug ( " Creating root directory %s" , root_dir ) if not osp . exists ( root_dir ) : os . makedirs ( root_dir ) return root_dir | Perform the initial setup for the project |
7,804 | def init ( self , projectname = None , description = None , ** kwargs ) : self . app_main ( ** kwargs ) experiments = self . config . experiments experiment = self . _experiment if experiment is None and not experiments : experiment = self . name + '_exp0' elif experiment is None : try : experiment = utils . get_next_name ( self . experiment ) except ValueError : raise ValueError ( "Could not estimate an experiment id! Please use the " "experiment argument to provide an id." ) self . experiment = experiment if self . is_archived ( experiment ) : raise ValueError ( "The specified experiment has already been archived! Run " "``%s -id %s unarchive`` first" % ( self . name , experiment ) ) if projectname is None : projectname = self . projectname else : self . projectname = projectname self . logger . info ( "Initializing experiment %s of project %s" , experiment , projectname ) exp_dict = experiments . setdefault ( experiment , OrderedDict ( ) ) if description is not None : exp_dict [ 'description' ] = description exp_dict [ 'project' ] = projectname exp_dict [ 'expdir' ] = exp_dir = osp . join ( 'experiments' , experiment ) exp_dir = osp . join ( self . config . projects [ projectname ] [ 'root' ] , exp_dir ) exp_dict [ 'timestamps' ] = OrderedDict ( ) if not os . path . exists ( exp_dir ) : self . logger . debug ( " Creating experiment directory %s" , exp_dir ) os . makedirs ( exp_dir ) self . fix_paths ( exp_dict ) return exp_dict | Initialize a new experiment |
7,805 | def get_value ( self , keys , exp_path = False , project_path = False , complete = False , on_projects = False , on_globals = False , projectname = None , no_fix = False , only_keys = False , base = '' , return_list = False , archives = False , ** kwargs ) : def pretty_print ( val ) : if isinstance ( val , dict ) : if only_keys : val = list ( val . keys ( ) ) return ordered_yaml_dump ( val , default_flow_style = False ) . rstrip ( ) return str ( val ) config = self . info ( exp_path = exp_path , project_path = project_path , complete = complete , on_projects = on_projects , on_globals = on_globals , projectname = projectname , no_fix = no_fix , return_dict = True , insert_id = False , archives = archives , ** kwargs ) ret = [ 0 ] * len ( keys ) for i , key in enumerate ( keys ) : if base : key = base + key key , sub_config = utils . go_through_dict ( key , config ) ret [ i ] = sub_config [ key ] if return_list : return ret return ( self . print_ or six . print_ ) ( '\n' . join ( map ( pretty_print , ret ) ) ) | Get one or more values in the configuration |
7,806 | def del_value ( self , keys , complete = False , on_projects = False , on_globals = False , projectname = None , base = '' , dtype = None , ** kwargs ) : config = self . info ( complete = complete , on_projects = on_projects , on_globals = on_globals , projectname = projectname , return_dict = True , insert_id = False , ** kwargs ) for key in keys : if base : key = base + key key , sub_config = utils . go_through_dict ( key , config ) del sub_config [ key ] | Delete a value in the configuration |
7,807 | def configure ( self , global_config = False , project_config = False , ifile = None , forcing = None , serial = False , nprocs = None , update_from = None , ** kwargs ) : if global_config : d = self . config . global_config elif project_config : self . app_main ( ** kwargs ) d = self . config . projects [ self . projectname ] else : d = self . config . experiments [ self . experiment ] if ifile is not None : d [ 'input' ] = osp . abspath ( ifile ) if forcing is not None : d [ 'forcing' ] = osp . abspath ( forcing ) if update_from is not None : with open ( 'update_from' ) as f : d . update ( yaml . load ( f ) ) global_config = self . config . global_config if serial : global_config [ 'serial' ] = True elif nprocs : nprocs = int ( nprocs ) if nprocs != 'all' else nprocs global_config [ 'serial' ] = False global_config [ 'nprocs' ] = nprocs | Configure the project and experiments |
7,808 | def set_value ( self , items , complete = False , on_projects = False , on_globals = False , projectname = None , base = '' , dtype = None , ** kwargs ) : def identity ( val ) : return val config = self . info ( complete = complete , on_projects = on_projects , on_globals = on_globals , projectname = projectname , return_dict = True , insert_id = False , ** kwargs ) if isinstance ( dtype , six . string_types ) : dtype = getattr ( builtins , dtype ) elif dtype is None : dtype = identity for key , value in six . iteritems ( dict ( items ) ) : if base : key = base + key key , sub_config = utils . go_through_dict ( key , config , setdefault = OrderedDict ) if key in self . paths : if isinstance ( value , six . string_types ) : value = osp . abspath ( value ) else : value = list ( map ( osp . abspath , value ) ) sub_config [ key ] = dtype ( value ) | Set a value in the configuration |
7,809 | def rel_paths ( self , * args , ** kwargs ) : return self . config . experiments . rel_paths ( * args , ** kwargs ) | Fix the paths in the given dictionary to get relative paths |
7,810 | def abspath ( self , path , project = None , root = None ) : if root is None : root = self . config . projects [ project or self . projectname ] [ 'root' ] return osp . join ( root , path ) | Returns the path from the current working directory |
7,811 | def relpath ( self , path , project = None , root = None ) : if root is None : root = self . config . projects [ project or self . projectname ] [ 'root' ] return osp . relpath ( path , root ) | Returns the relative path from the root directory of the project |
7,812 | def setup_parser ( self , parser = None , subparsers = None ) : commands = self . commands [ : ] parser_cmds = self . parser_commands . copy ( ) if subparsers is None : if parser is None : parser = FuncArgParser ( self . name ) subparsers = parser . add_subparsers ( chain = True ) ret = { } for i , cmd in enumerate ( commands [ : ] ) : func = getattr ( self , cmd ) parser_cmd = parser_cmds . setdefault ( cmd , cmd . replace ( '_' , '-' ) ) ret [ cmd ] = sp = parser . setup_subparser ( func , name = parser_cmd , return_parser = True ) sp . setup_args ( func ) modifier = getattr ( self , '_modify_' + cmd , None ) if modifier is not None : modifier ( sp ) self . parser_commands = parser_cmds parser . setup_args ( self . app_main ) self . _modify_app_main ( parser ) self . parser = parser self . subparsers = ret return parser , subparsers , ret | Create the argument parser for this instance |
7,813 | def get_parser ( cls ) : organizer = cls ( ) organizer . setup_parser ( ) organizer . _finish_parser ( ) return organizer . parser | Function returning the command line parser for this class |
7,814 | def is_archived ( self , experiment , ignore_missing = True ) : if ignore_missing : if isinstance ( self . config . experiments . get ( experiment , True ) , Archive ) : return self . config . experiments . get ( experiment , True ) else : if isinstance ( self . config . experiments [ experiment ] , Archive ) : return self . config . experiments [ experiment ] | Convenience function to determine whether the given experiment has been archived already |
7,815 | def _archive_extensions ( ) : if six . PY3 : ext_map = { } fmt_map = { } for key , exts , desc in shutil . get_unpack_formats ( ) : fmt_map [ key ] = exts [ 0 ] for ext in exts : ext_map [ ext ] = key else : ext_map = { '.tar' : 'tar' , '.tar.bz2' : 'bztar' , '.tar.gz' : 'gztar' , '.tar.xz' : 'xztar' , '.tbz2' : 'bztar' , '.tgz' : 'gztar' , '.txz' : 'xztar' , '.zip' : 'zip' } fmt_map = { 'bztar' : '.tar.bz2' , 'gztar' : '.tar.gz' , 'tar' : '.tar' , 'xztar' : '.tar.xz' , 'zip' : '.zip' } return ext_map , fmt_map | Create translations from file extension to archive format |
7,816 | def loadFile ( self , fileName ) : if not QtCore . QFile ( fileName ) . exists ( ) : msg = "File <b>{}</b> does not exist" . format ( self . qteAppletID ( ) ) self . qteLogger . info ( msg ) self . fileName = None return self . fileName = fileName doc = popplerqt4 . Poppler . Document . load ( fileName ) doc . setRenderHint ( popplerqt4 . Poppler . Document . Antialiasing ) doc . setRenderHint ( popplerqt4 . Poppler . Document . TextAntialiasing ) hbox = QtGui . QVBoxLayout ( ) for ii in range ( doc . numPages ( ) ) : pdf_img = doc . page ( ii ) . renderToImage ( ) pdf_label = self . qteAddWidget ( QtGui . QLabel ( ) ) pdf_label . setPixmap ( QtGui . QPixmap . fromImage ( pdf_img ) ) hbox . addWidget ( pdf_label ) tmp = self . qteAddWidget ( QtGui . QWidget ( self ) ) tmp . setLayout ( hbox ) self . qteScroll . setWidget ( tmp ) | Load and display the PDF file specified by fileName . |
7,817 | def get_product ( membersuite_id , client = None ) : if not membersuite_id : return None client = client or get_new_client ( request_session = True ) object_query = "SELECT Object() FROM PRODUCT WHERE ID = '{}'" . format ( membersuite_id ) result = client . execute_object_query ( object_query ) msql_result = result [ "body" ] [ "ExecuteMSQLResult" ] if msql_result [ "Success" ] : membersuite_object_data = ( msql_result [ "ResultValue" ] [ "SingleObject" ] ) else : raise ExecuteMSQLError ( result = result ) return Product ( membersuite_object_data = membersuite_object_data ) | Return a Product object by ID . |
7,818 | def __watchers_callbacks_exec ( self , signal_name ) : def callback_fn ( ) : for watcher in self . __watchers_callbacks [ signal_name ] : if watcher is not None : watcher . notify ( ) return callback_fn | Generate callback for a queue |
7,819 | def py_doc_trim ( docstring ) : if not docstring : return '' lines = docstring . expandtabs ( ) . splitlines ( ) indent = sys . maxint for line in lines [ 1 : ] : stripped = line . lstrip ( ) if stripped : indent = min ( indent , len ( line ) - len ( stripped ) ) trimmed = [ lines [ 0 ] . strip ( ) ] if indent < sys . maxint : for line in lines [ 1 : ] : trimmed . append ( line [ indent : ] . rstrip ( ) ) while trimmed and not trimmed [ - 1 ] : trimmed . pop ( ) while trimmed and not trimmed [ 0 ] : trimmed . pop ( 0 ) joined = '\n' . join ( trimmed ) return newline_substitution_regex . sub ( " " , joined ) | Trim a python doc string . |
7,820 | def _fix_up_fields ( cls ) : cls . _fields = { } if cls . __module__ == __name__ and cls . __name__ != 'DebugResource' : return for name in set ( dir ( cls ) ) : attr = getattr ( cls , name , None ) if isinstance ( attr , BaseField ) : if name . startswith ( '_' ) : raise TypeError ( "Resource field %s cannot begin with an " "underscore. Underscore attributes are reserved " "for instance variables that aren't intended to " "propagate out to the HTTP caller." % name ) attr . _fix_up ( cls , name ) cls . _fields [ attr . name ] = attr if cls . _default_fields is None : cls . _default_fields = tuple ( cls . _fields . keys ( ) ) | Add names to all of the Resource fields . |
7,821 | def _render_serializable ( self , obj , context ) : logging . info ( ) if obj is None : logging . debug ( "_render_serializable passed a None obj, returning None" ) return None output = { } if self . _fields_to_render is None : return output for field in self . _fields_to_render : renderer = self . _fields [ field ] . render output [ field ] = renderer ( obj , field , context ) return output | Renders a JSON - serializable version of the object passed in . Usually this means turning a Python object into a dict but sometimes it might make sense to render a list or a string or a tuple . |
7,822 | def _render_serializable ( self , list_of_objs , context ) : output = [ ] for obj in list_of_objs : if obj is not None : item = self . _item_resource . _render_serializable ( obj , context ) output . append ( item ) return output | Iterates through the passed in list_of_objs and calls the _render_serializable method of each object s Resource type . |
7,823 | def critical_section_dynamic_lock ( lock_fn , blocking = True , timeout = None , raise_exception = True ) : if blocking is False or timeout is None : timeout = - 1 def first_level_decorator ( decorated_function ) : def second_level_decorator ( original_function , * args , ** kwargs ) : lock = lock_fn ( * args , ** kwargs ) if lock . acquire ( blocking = blocking , timeout = timeout ) is True : try : result = original_function ( * args , ** kwargs ) return result finally : lock . release ( ) elif raise_exception is True : raise WCriticalSectionError ( 'Unable to lock critical section\n' ) return decorator ( second_level_decorator ) ( decorated_function ) return first_level_decorator | Protect a function with a lock that was get from the specified function . If a lock can not be acquire then no function call will be made |
7,824 | def generate_json_docs ( module , pretty_print = False , user = None ) : indent = None separators = ( ',' , ':' ) if pretty_print : indent = 4 separators = ( ',' , ': ' ) module_doc_dict = generate_doc_dict ( module , user ) json_str = json . dumps ( module_doc_dict , indent = indent , separators = separators ) return json_str | Return a JSON string format of a Pale module s documentation . |
7,825 | def generate_raml_docs ( module , fields , shared_types , user = None , title = "My API" , version = "v1" , api_root = "api" , base_uri = "http://mysite.com/{version}" ) : output = StringIO ( ) output . write ( '#%RAML 1.0 \n' ) output . write ( 'title: ' + title + ' \n' ) output . write ( 'baseUri: ' + base_uri + ' \n' ) output . write ( 'version: ' + version + '\n' ) output . write ( 'mediaType: application/json\n\n' ) output . write ( 'documentation:\n' ) output . write ( ' - title: Welcome\n' ) output . write ( ' content: |\n' ) output . write ( ) output . write ( "\n###############\n# Resource Types:\n###############\n\n" ) output . write ( 'types:\n' ) basic_fields = [ ] for field_module in inspect . getmembers ( fields , inspect . ismodule ) : for field_class in inspect . getmembers ( field_module [ 1 ] , inspect . isclass ) : basic_fields . append ( field_class [ 1 ] ) pale_basic_types = generate_basic_type_docs ( basic_fields , { } ) output . write ( "\n# Pale Basic Types:\n\n" ) output . write ( pale_basic_types [ 0 ] ) shared_fields = [ ] for shared_type in shared_types : for field_class in inspect . getmembers ( shared_type , inspect . isclass ) : shared_fields . append ( field_class [ 1 ] ) pale_shared_types = generate_basic_type_docs ( shared_fields , pale_basic_types [ 1 ] ) output . write ( "\n# Pale Shared Types:\n\n" ) output . write ( pale_shared_types [ 0 ] ) raml_resource_types = generate_raml_resource_types ( module ) output . write ( "\n# API Resource Types:\n\n" ) output . write ( raml_resource_types ) raml_resources = generate_raml_resources ( module , api_root , user ) output . write ( "\n\n###############\n# API Endpoints:\n###############\n\n" ) output . write ( raml_resources ) raml_docs = output . getvalue ( ) output . close ( ) return raml_docs | Return a RAML file of a Pale module s documentation as a string . |
7,826 | def generate_basic_type_docs ( fields , existing_types ) : raml_built_in_types = { "any" : { "parent" : None , } , "time-only" : { "parent" : "any" , } , "datetime" : { "parent" : "any" , "pale_children" : [ "timestamp" ] , } , "datetime-only" : { "parent" : "any" , } , "date-only" : { "parent" : "any" , "pale_children" : [ "date" ] , } , "number" : { "parent" : "any" , } , "boolean" : { "parent" : "any" , "pale_children" : [ "boolean" ] } , "string" : { "parent" : "any" , "pale_children" : [ "url" , "string" , "uri" ] , } , "null" : { "parent" : "any" , } , "file" : { "parent" : "any" , } , "array" : { "parent" : "any" , "pale_children" : [ "list" ] , } , "object" : { "parent" : "any" , } , "union" : { "parent" : "any" , } , "XSD Schema" : { "parent" : "any" , } , "JSON Schema" : { "parent" : "any" , } , "integer" : { "parent" : "number" , "pale_children" : [ "integer" ] , } , } basic_types = { } for field in fields : if hasattr ( field , "value_type" ) : type_name = field . value_type . replace ( " " , "_" ) if type_name not in raml_built_in_types and type_name not in basic_types and type_name not in existing_types : basic_types [ type_name ] = { } if hasattr ( field , "__doc__" ) : modified_description = clean_description ( field . __doc__ ) basic_types [ type_name ] [ "description" ] = modified_description for raml_type in raml_built_in_types : if "pale_children" in raml_built_in_types [ raml_type ] : if type_name in raml_built_in_types [ raml_type ] [ "pale_children" ] : basic_types [ type_name ] [ "type" ] = raml_type break else : if hasattr ( field , "is_list" ) and field . is_list : basic_types [ type_name ] [ "type" ] = "array" if hasattr ( field , "list_item_type" ) and field . list_item_type != None : basic_types [ type_name ] [ "items" ] = field . list_item_type else : basic_types [ type_name ] [ "items" ] = "base" else : pale_parent_class = field . __mro__ [ 1 ] if pale_parent_class . __name__ == "object" : basic_types [ type_name ] [ "type" ] = "object" else : basic_types [ type_name ] [ "type" ] = pale_parent_class . value_type ordered_basic_types = OrderedDict ( sorted ( basic_types . items ( ) , key = lambda t : t [ 0 ] ) ) basic_docs = generate_type_docs ( ordered_basic_types ) return ( basic_docs , basic_types ) | Map resource types to their RAML equivalents . Expects fields to be a list of modules - each module would be something like pale . fields . Expects existing_types to be a list of dict of existing types which will take precedence and prevent a new type with the same name from being added . |
7,827 | def generate_doc_dict ( module , user ) : from pale import extract_endpoints , extract_resources , is_pale_module if not is_pale_module ( module ) : raise ValueError ( ) module_endpoints = extract_endpoints ( module ) ep_doc = { ep . _route_name : document_endpoint ( ep ) for ep in module_endpoints } ep_doc_filtered = { } for endpoint in ep_doc : if ep_doc [ endpoint ] . get ( "requires_permission" ) != None and user != None and user . is_admin or ep_doc [ endpoint ] . get ( "requires_permission" ) == None : ep_doc_filtered [ endpoint ] = ep_doc [ endpoint ] module_resources = extract_resources ( module ) res_doc = { r . _value_type : document_resource ( r ) for r in module_resources } return { 'endpoints' : ep_doc_filtered , 'resources' : res_doc } | Compile a Pale module s documentation into a python dictionary . |
7,828 | def document_endpoint ( endpoint ) : descr = clean_description ( py_doc_trim ( endpoint . __doc__ ) ) docs = { 'name' : endpoint . _route_name , 'http_method' : endpoint . _http_method , 'uri' : endpoint . _uri , 'description' : descr , 'arguments' : extract_endpoint_arguments ( endpoint ) , 'returns' : format_endpoint_returns_doc ( endpoint ) , } if hasattr ( endpoint , "_success" ) : docs [ "success" ] = endpoint . _success if hasattr ( endpoint , "_requires_permission" ) : docs [ "requires_permission" ] = endpoint . _requires_permission return docs | Extract the full documentation dictionary from the endpoint . |
7,829 | def extract_endpoint_arguments ( endpoint ) : ep_args = endpoint . _arguments if ep_args is None : return None arg_docs = { k : format_endpoint_argument_doc ( a ) for k , a in ep_args . iteritems ( ) } return arg_docs | Extract the argument documentation from the endpoint . |
7,830 | def format_endpoint_argument_doc ( argument ) : doc = argument . doc_dict ( ) doc [ 'description' ] = clean_description ( py_doc_trim ( doc [ 'description' ] ) ) details = doc . get ( 'detailed_description' , None ) if details is not None : doc [ 'detailed_description' ] = clean_description ( py_doc_trim ( details ) ) return doc | Return documentation about the argument that an endpoint accepts . |
7,831 | def format_endpoint_returns_doc ( endpoint ) : description = clean_description ( py_doc_trim ( endpoint . _returns . _description ) ) return { 'description' : description , 'resource_name' : endpoint . _returns . _value_type , 'resource_type' : endpoint . _returns . __class__ . __name__ } | Return documentation about the resource that an endpoint returns . |
7,832 | def save ( self , * args , ** kwargs ) : self . body_formatted = sanetize_text ( self . body ) super ( Contact , self ) . save ( ) | Create formatted version of body text . |
7,833 | def get_current_membership_for_org ( self , account_num , verbose = False ) : all_memberships = self . get_memberships_for_org ( account_num = account_num , verbose = verbose ) for membership in all_memberships : if ( membership . expiration_date and membership . expiration_date > datetime . datetime . now ( ) ) : return membership return None | Return a current membership for this org or None if there is none . |
7,834 | def get_memberships_for_org ( self , account_num , verbose = False ) : if not self . client . session_id : self . client . request_session ( ) query = "SELECT Objects() FROM Membership " "WHERE Owner = '%s' ORDER BY ExpirationDate" % account_num membership_list = self . get_long_query ( query , verbose = verbose ) return membership_list or [ ] | Retrieve all memberships associated with an organization ordered by expiration date . |
7,835 | def get_all_memberships ( self , limit_to = 100 , max_calls = None , parameters = None , since_when = None , start_record = 0 , verbose = False ) : if not self . client . session_id : self . client . request_session ( ) query = "SELECT Objects() FROM Membership" where_params = [ ] if parameters : for k , v in parameters . items ( ) : where_params . append ( ( k , "=" , v ) ) if since_when : d = datetime . date . today ( ) - datetime . timedelta ( days = since_when ) where_params . append ( ( 'LastModifiedDate' , ">" , "'%s 00:00:00'" % d ) ) if where_params : query += " WHERE " query += " AND " . join ( [ "%s %s %s" % ( p [ 0 ] , p [ 1 ] , p [ 2 ] ) for p in where_params ] ) query += " ORDER BY LocalID" membership_list = self . get_long_query ( query , limit_to = limit_to , max_calls = max_calls , start_record = start_record , verbose = verbose ) return membership_list or [ ] | Retrieve all memberships updated since since_when |
7,836 | def get_all_membership_products ( self , verbose = False ) : if not self . client . session_id : self . client . request_session ( ) query = "SELECT Objects() FROM MembershipDuesProduct" membership_product_list = self . get_long_query ( query , verbose = verbose ) return membership_product_list or [ ] | Retrieves membership product objects |
7,837 | def get_driver ( self , desired_capabilities = None ) : override_caps = desired_capabilities or { } desired_capabilities = self . config . make_selenium_desired_capabilities ( ) desired_capabilities . update ( override_caps ) browser_string = self . config . browser chromedriver_version = None if self . remote : driver = self . remote_service . build_driver ( desired_capabilities ) if browser_string == "CHROME" and self . remote_service . name == "saucelabs" : chromedriver_version = desired_capabilities . get ( "chromedriver-version" , None ) if chromedriver_version is None : raise ValueError ( "when using Chrome, you must set a " "``chromedriver-version`` capability so that Selenic " "can detect which version of Chromedriver will " "be used." ) else : if browser_string == "CHROME" : chromedriver_path = self . local_conf [ "CHROMEDRIVER_PATH" ] driver = webdriver . Chrome ( chromedriver_path , chrome_options = self . local_conf . get ( "CHROME_OPTIONS" ) , desired_capabilities = desired_capabilities , service_log_path = self . local_conf [ "SERVICE_LOG_PATH" ] , service_args = self . local_conf . get ( "SERVICE_ARGS" ) ) version_line = subprocess . check_output ( [ chromedriver_path , "--version" ] ) version_str = re . match ( ur"^ChromeDriver (\d+\.\d+)" , version_line ) . group ( 1 ) chromedriver_version = StrictVersion ( version_str ) elif browser_string == "FIREFOX" : profile = self . local_conf . get ( "FIREFOX_PROFILE" ) or FirefoxProfile ( ) binary = self . local_conf . get ( "FIREFOX_BINARY" ) or FirefoxBinary ( ) driver = webdriver . Firefox ( profile , binary , capabilities = desired_capabilities ) elif browser_string == "INTERNETEXPLORER" : driver = webdriver . Ie ( ) elif browser_string == "OPERA" : driver = webdriver . Opera ( ) else : raise ValueError ( "can't start a local " + browser_string ) driver_caps = NormalizedCapabilities ( driver . desired_capabilities ) browser_version = re . sub ( r"\..*$" , "" , driver_caps [ "browserVersion" ] ) if driver_caps [ "platformName" ] . upper ( ) != self . config . platform : raise ValueError ( "the platform you want is not the one " "you are running selenic on" ) if browser_version != self . config . version : raise ValueError ( "the version installed is not the one " "you wanted" ) if ( self . remote_service and self . remote_service . name == "browserstack" ) or ( chromedriver_version is not None and chromedriver_version > StrictVersion ( "2.13" ) ) : chromedriver_element_center_patch ( ) setattr ( driver , CHROMEDRIVER_ELEMENT_CENTER_PATCH_FLAG , True ) driver = self . patch ( driver ) return driver | Creates a Selenium driver on the basis of the configuration file upon which this object was created . |
7,838 | def update_ff_binary_env ( self , variable ) : if self . config . browser != 'FIREFOX' : return binary = self . local_conf . get ( 'FIREFOX_BINARY' ) if binary is None : return binary . _firefox_env [ variable ] = os . environ [ variable ] | If a FIREFOX_BINARY was specified this method updates an environment variable used by the FirefoxBinary instance to the current value of the variable in the environment . |
7,839 | def regex ( self , protocols , localhost = True ) : p = r"^" p += r"(?:(?:(?:{}):)?//)" . format ( '|' . join ( protocols ) ) p += r"(?:\S+(?::\S*)?@)?" p += r"(?:" p += r"(?!(?:10|127)(?:\.\d{1,3}){3})" p += r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})" p += r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})" p += r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" p += r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}" p += r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" p += r"|" p += r"(?:" p += r"(?:" p += r"[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?" p += r"[a-z0-9\u00a1-\uffff]" p += r"\." if not localhost else r"[\.]?|localhost" p += r")+" p += r"(?:[a-z\u00a1-\uffff]{2,}\.?)" p += r")" p += r"(?::\d{2,5})?" p += r"(?:[/?#]\S*)?" p += r"$" return p | URL Validation regex Based on regular expression by Diego Perini ( |
7,840 | def add_layers ( self , * layers ) : for layer in layers : if layer . name ( ) in self . __layers . keys ( ) : raise ValueError ( 'Layer "%s" already exists' % layer . name ( ) ) self . __layers [ layer . name ( ) ] = layer | Append given layers to this onion |
7,841 | def index ( objects , attr ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) return { getattr ( obj , attr ) : obj for obj in objects } | Generate a mapping of a list of objects indexed by the given attr . |
7,842 | def register ( self , typedef ) : if typedef in self . bound_types : return if not self . is_compatible ( typedef ) : raise ValueError ( "Incompatible type {} for engine {}" . format ( typedef , self ) ) if typedef not in self . unbound_types : self . unbound_types . add ( typedef ) typedef . _register ( self ) | Add the typedef to this engine if it is compatible . |
7,843 | def bind ( self , ** config ) : while self . unbound_types : typedef = self . unbound_types . pop ( ) try : load , dump = typedef . bind ( self , ** config ) self . bound_types [ typedef ] = { "load" : load , "dump" : dump } except Exception : self . unbound_types . add ( typedef ) raise | Bind all unbound types to the engine . |
7,844 | def load ( self , typedef , value , ** kwargs ) : try : bound_type = self . bound_types [ typedef ] except KeyError : raise DeclareException ( "Can't load unknown type {}" . format ( typedef ) ) else : return bound_type [ "load" ] ( value , ** kwargs ) | Return the result of the bound load method for a typedef |
7,845 | def get_configdir ( name ) : configdir = os . environ . get ( '%sCONFIGDIR' % name . upper ( ) ) if configdir is not None : return os . path . abspath ( configdir ) p = None h = _get_home ( ) if ( ( sys . platform . startswith ( 'linux' ) or sys . platform . startswith ( 'darwin' ) ) and h is not None ) : p = os . path . join ( h , '.config/' + name ) elif h is not None : p = os . path . join ( h , '.' + name ) if not os . path . exists ( p ) : os . makedirs ( p ) return p | Return the string representing the configuration directory . |
7,846 | def ordered_yaml_dump ( data , stream = None , Dumper = None , ** kwds ) : Dumper = Dumper or yaml . Dumper class OrderedDumper ( Dumper ) : pass def _dict_representer ( dumper , data ) : return dumper . represent_mapping ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , data . items ( ) ) OrderedDumper . add_representer ( OrderedDict , _dict_representer ) return yaml . dump ( data , stream , OrderedDumper , ** kwds ) | Dumps the stream from an OrderedDict . Taken from |
7,847 | def safe_load ( fname ) : lock = fasteners . InterProcessLock ( fname + '.lck' ) lock . acquire ( ) try : with open ( fname ) as f : return ordered_yaml_load ( f ) except : raise finally : lock . release ( ) | Load the file fname and make sure it can be done in parallel |
7,848 | def safe_dump ( d , fname , * args , ** kwargs ) : if osp . exists ( fname ) : os . rename ( fname , fname + '~' ) lock = fasteners . InterProcessLock ( fname + '.lck' ) lock . acquire ( ) try : with open ( fname , 'w' ) as f : ordered_yaml_dump ( d , f , * args , ** kwargs ) except : raise finally : lock . release ( ) | Savely dump d to fname using yaml |
7,849 | def project_map ( self ) : for key , val in self . items ( ) : if isinstance ( val , dict ) : l = self . _project_map [ val [ 'project' ] ] elif isinstance ( val , Archive ) : l = self . _project_map [ val . project ] else : continue if key not in l : l . append ( key ) return self . _project_map | A mapping from project name to experiments |
7,850 | def exp_files ( self ) : ret = OrderedDict ( ) exp_file = self . exp_file if osp . exists ( exp_file ) : for key , val in safe_load ( exp_file ) . items ( ) : ret [ key ] = val for project , d in self . projects . items ( ) : project_path = d [ 'root' ] config_path = osp . join ( project_path , '.project' ) if not osp . exists ( config_path ) : continue for fname in glob . glob ( osp . join ( config_path , '*.yml' ) ) : if fname == '.project.yml' : continue exp = osp . splitext ( osp . basename ( fname ) ) [ 0 ] if not isinstance ( ret . get ( exp ) , Archive ) : ret [ exp ] = osp . join ( config_path , exp + '.yml' ) if exp not in self . _project_map [ project ] : self . _project_map [ project ] . append ( exp ) return ret | A mapping from experiment to experiment configuration file |
7,851 | def save ( self ) : for exp , d in dict ( self ) . items ( ) : if isinstance ( d , dict ) : project_path = self . projects [ d [ 'project' ] ] [ 'root' ] d = self . rel_paths ( copy . deepcopy ( d ) ) fname = osp . join ( project_path , '.project' , exp + '.yml' ) if not osp . exists ( osp . dirname ( fname ) ) : os . makedirs ( osp . dirname ( fname ) ) safe_dump ( d , fname , default_flow_style = False ) exp_file = self . exp_file lock = fasteners . InterProcessLock ( exp_file + '.lck' ) lock . acquire ( ) safe_dump ( OrderedDict ( ( exp , val if isinstance ( val , Archive ) else None ) for exp , val in self . items ( ) ) , exp_file , default_flow_style = False ) lock . release ( ) | Save the experiment configuration |
7,852 | def as_ordereddict ( self ) : if six . PY2 : d = OrderedDict ( ) copied = dict ( self ) for key in self : d [ key ] = copied [ key ] else : d = OrderedDict ( self ) return d | Convenience method to convert this object into an OrderedDict |
7,853 | def remove ( self , experiment ) : try : project_path = self . projects [ self [ experiment ] [ 'project' ] ] [ 'root' ] except KeyError : return config_path = osp . join ( project_path , '.project' , experiment + '.yml' ) for f in [ config_path , config_path + '~' , config_path + '.lck' ] : if os . path . exists ( f ) : os . remove ( f ) del self [ experiment ] | Remove the configuration of an experiment |
7,854 | def save ( self ) : project_paths = OrderedDict ( ) for project , d in OrderedDict ( self ) . items ( ) : if isinstance ( d , dict ) : project_path = d [ 'root' ] fname = osp . join ( project_path , '.project' , '.project.yml' ) if not osp . exists ( osp . dirname ( fname ) ) : os . makedirs ( osp . dirname ( fname ) ) if osp . exists ( fname ) : os . rename ( fname , fname + '~' ) d = self . rel_paths ( copy . deepcopy ( d ) ) safe_dump ( d , fname , default_flow_style = False ) project_paths [ project ] = project_path else : project_paths = self . project_paths [ project ] self . project_paths = project_paths safe_dump ( project_paths , self . all_projects , default_flow_style = False ) | Save the project configuration |
7,855 | def save ( self ) : self . projects . save ( ) self . experiments . save ( ) safe_dump ( self . global_config , self . _globals_file , default_flow_style = False ) | Save the entire configuration files |
7,856 | def reverseCommit ( self ) : self . baseClass . setText ( self . oldText ) self . qteWidget . SCISetStylingEx ( 0 , 0 , self . style ) | Replace the current widget content with the original text . Note that the original text has styling information available whereas the new text does not . |
7,857 | def placeCursor ( self , line , col ) : num_lines , num_col = self . qteWidget . getNumLinesAndColumns ( ) if line >= num_lines : line , col = num_lines , num_col else : text = self . qteWidget . text ( line ) if col >= len ( text ) : col = len ( text ) - 1 self . qteWidget . setCursorPosition ( line , col ) | Try to place the cursor in line at col if possible otherwise place it at the end . |
7,858 | def reverseCommit ( self ) : self . baseClass . setText ( self . textBefore ) self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleBefore ) | Put the document into the before state . |
7,859 | def fromMimeData ( self , data ) : if data . hasText ( ) : self . insert ( data . text ( ) ) return ( QtCore . QByteArray ( ) , False ) | Paste the clipboard data at the current cursor position . |
7,860 | def keyPressEvent ( self , keyEvent : QtGui . QKeyEvent ) : undoObj = UndoInsert ( self , keyEvent . text ( ) ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native keyPressEvent method . |
7,861 | def replaceSelectedText ( self , text : str ) : undoObj = UndoReplaceSelectedText ( self , text ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native replaceSelectedText method . |
7,862 | def insert ( self , text : str ) : undoObj = UndoInsert ( self , text ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native insert method . |
7,863 | def insertAt ( self , text : str , line : int , col : int ) : undoObj = UndoInsertAt ( self , text , line , col ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native insertAt method . |
7,864 | def append ( self , text : str ) : pos = self . getCursorPosition ( ) line , col = self . getNumLinesAndColumns ( ) undoObj = UndoInsertAt ( self , text , line , col ) self . qteUndoStack . push ( undoObj ) self . setCursorPosition ( * pos ) | Undo safe wrapper for the native append method . |
7,865 | def setText ( self , text : str ) : undoObj = UndoSetText ( self , text ) self . qteUndoStack . push ( undoObj ) | Undo safe wrapper for the native setText method . |
7,866 | def SCIGetStyledText ( self , selectionPos : tuple ) : if not self . isSelectionPositionValid ( selectionPos ) : return None start = self . positionFromLineIndex ( * selectionPos [ : 2 ] ) end = self . positionFromLineIndex ( * selectionPos [ 2 : ] ) if start > end : start , end = end , start bufSize = 2 * ( end - start ) + 2 buf = bytearray ( bufSize ) numRet = self . SendScintilla ( self . SCI_GETSTYLEDTEXT , start , end , buf ) buf = buf [ : - 2 ] if numRet > bufSize : qteMain . qteLogger . error ( 'SCI_GETSTYLEDTEX function returned more' ' bytes than expected.' ) text = buf [ 0 : : 2 ] style = buf [ 1 : : 2 ] return ( text , style ) | Pythonic wrapper for the SCI_GETSTYLEDTEXT command . |
7,867 | def SCISetStyling ( self , line : int , col : int , numChar : int , style : bytearray ) : if not self . isPositionValid ( line , col ) : return pos = self . positionFromLineIndex ( line , col ) self . SendScintilla ( self . SCI_STARTSTYLING , pos , 0xFF ) self . SendScintilla ( self . SCI_SETSTYLING , numChar , style ) | Pythonic wrapper for the SCI_SETSTYLING command . |
7,868 | def SCISetStylingEx ( self , line : int , col : int , style : bytearray ) : if not self . isPositionValid ( line , col ) : return pos = self . positionFromLineIndex ( line , col ) self . SendScintilla ( self . SCI_STARTSTYLING , pos , 0xFF ) self . SendScintilla ( self . SCI_SETSTYLINGEX , len ( style ) , style ) | Pythonic wrapper for the SCI_SETSTYLINGEX command . |
7,869 | def qteSetLexer ( self , lexer ) : if ( lexer is not None ) and ( not issubclass ( lexer , Qsci . QsciLexer ) ) : QtmacsOtherError ( 'lexer must be a class object and derived from' ' <b>QsciLexer</b>' ) return self . qteLastLexer = lexer if lexer is None : self . setLexer ( None ) else : self . setLexer ( lexer ( ) ) self . setMonospace ( ) | Specify the lexer to use . |
7,870 | def setMonospace ( self ) : font = bytes ( 'courier new' , 'utf-8' ) for ii in range ( 32 ) : self . SendScintilla ( self . SCI_STYLESETFONT , ii , font ) | Fix the fonts of the first 32 styles to a mono space one . |
7,871 | def setModified ( self , isModified : bool ) : if not isModified : self . qteUndoStack . saveState ( ) super ( ) . setModified ( isModified ) | Set the modified state to isModified . |
7,872 | def attribute ( func ) : def inner ( self ) : name , attribute_type = func ( self ) if not name : name = func . __name__ try : return attribute_type ( self . et . attrib [ name ] ) except KeyError : raise AttributeError return inner | Decorator used to declare that property is a tag attribute |
7,873 | def section ( func ) : def inner ( self ) : return func ( self ) ( self . et . find ( func . __name__ ) ) return inner | Decorator used to declare that the property is xml section |
7,874 | def tag_value ( func ) : def inner ( self ) : tag , attrib , attrib_type = func ( self ) tag_obj = self . et . find ( tag ) if tag_obj is not None : try : return attrib_type ( self . et . find ( tag ) . attrib [ attrib ] ) except KeyError : raise AttributeError return inner | Decorator used to declare that the property is attribute of embedded tag |
7,875 | def tag_value_setter ( tag , attrib ) : def outer ( func ) : def inner ( self , value ) : tag_elem = self . et . find ( tag ) if tag_elem is None : et = ElementTree . fromstring ( "<{}></{}>" . format ( tag , tag ) ) self . et . append ( et ) tag_elem = self . et . find ( tag ) tag_elem . attrib [ attrib ] = str ( value ) return inner return outer | Decorator used to declare that the setter function is an attribute of embedded tag |
7,876 | def run ( self , value , model = None , context = None ) : res = self . validate ( value , model , context ) if not isinstance ( res , Error ) : err = 'Validator "{}" result must be of type "{}", got "{}"' raise InvalidErrorType ( err . format ( self . __class__ . __name__ , Error , type ( res ) ) ) return res | Run validation Wraps concrete implementation to ensure custom validators return proper type of result . |
7,877 | def _collect_data ( self ) : all_data = [ ] for line in self . engine . run_engine ( ) : logging . debug ( "Adding {} to all_data" . format ( line ) ) all_data . append ( line . copy ( ) ) logging . debug ( "all_data is now {}" . format ( all_data ) ) return all_data | Returns a list of all the data gathered from the engine iterable . |
7,878 | def _get_module_name_from_fname ( fname ) : fname = fname . replace ( ".pyc" , ".py" ) for mobj in sys . modules . values ( ) : if ( hasattr ( mobj , "__file__" ) and mobj . __file__ and ( mobj . __file__ . replace ( ".pyc" , ".py" ) == fname ) ) : module_name = mobj . __name__ return module_name raise RuntimeError ( "Module could not be found" ) | Get module name from module file name . |
7,879 | def get_function_args ( func , no_self = False , no_varargs = False ) : par_dict = signature ( func ) . parameters pos = lambda x : x . kind == Parameter . VAR_POSITIONAL kw = lambda x : x . kind == Parameter . VAR_KEYWORD opts = [ "" , "*" , "**" ] args = [ "{prefix}{arg}" . format ( prefix = opts [ pos ( value ) + 2 * kw ( value ) ] , arg = par ) for par , value in par_dict . items ( ) ] self_filtered_args = ( args if not args else ( args [ 1 if ( args [ 0 ] == "self" ) and no_self else 0 : ] ) ) pos = lambda x : ( len ( x ) > 1 ) and ( x [ 0 ] == "*" ) and ( x [ 1 ] != "*" ) kw = lambda x : ( len ( x ) > 2 ) and ( x [ : 2 ] == "**" ) varargs_filtered_args = [ arg for arg in self_filtered_args if ( not no_varargs ) or all ( [ no_varargs , not pos ( arg ) , not kw ( arg ) ] ) ] return tuple ( varargs_filtered_args ) | Return tuple of the function argument names in the order of the function signature . |
7,880 | def get_module_name ( module_obj ) : r if not is_object_module ( module_obj ) : raise RuntimeError ( "Argument `module_obj` is not valid" ) name = module_obj . __name__ msg = "Module object `{name}` could not be found in loaded modules" if name not in sys . modules : raise RuntimeError ( msg . format ( name = name ) ) return name | r Retrieve the module name from a module object . |
7,881 | def private_props ( obj ) : props = [ item for item in dir ( obj ) ] priv_props = [ _PRIVATE_PROP_REGEXP . match ( item ) for item in props ] call_props = [ callable ( getattr ( obj , item ) ) for item in props ] iobj = zip ( props , priv_props , call_props ) for obj_name in [ prop for prop , priv , call in iobj if priv and ( not call ) ] : yield obj_name | Yield private properties of an object . |
7,882 | def _check_intersection ( self , other ) : props = [ "_callables_db" , "_reverse_callables_db" , "_modules_dict" ] for prop in props : self_dict = getattr ( self , prop ) other_dict = getattr ( other , prop ) keys_self = set ( self_dict . keys ( ) ) keys_other = set ( other_dict . keys ( ) ) for key in keys_self & keys_other : svalue = self_dict [ key ] ovalue = other_dict [ key ] same_type = type ( svalue ) == type ( ovalue ) if same_type : list_comp = isinstance ( svalue , list ) and any ( [ item not in svalue for item in ovalue ] ) str_comp = isinstance ( svalue , str ) and svalue != ovalue dict_comp = isinstance ( svalue , dict ) and svalue != ovalue comp = any ( [ list_comp , str_comp , dict_comp ] ) if ( not same_type ) or ( same_type and comp ) : emsg = "Conflicting information between objects" raise RuntimeError ( emsg ) | Check that intersection of two objects has the same information . |
7,883 | def get_callable_from_line ( self , module_file , lineno ) : module_name = _get_module_name_from_fname ( module_file ) if module_name not in self . _modules_dict : self . trace ( [ module_file ] ) ret = None iobj = sorted ( self . _modules_dict [ module_name ] , key = lambda x : x [ "code_id" ] [ 1 ] ) for value in iobj : if value [ "code_id" ] [ 1 ] <= lineno <= value [ "last_lineno" ] : ret = value [ "name" ] elif value [ "code_id" ] [ 1 ] > lineno : break return ret if ret else module_name | Get the callable that the line number belongs to . |
7,884 | def refresh ( self ) : self . trace ( list ( self . _fnames . keys ( ) ) , _refresh = True ) | Re - traces modules modified since the time they were traced . |
7,885 | def save ( self , callables_fname ) : r _validate_fname ( callables_fname ) items = self . _reverse_callables_db . items ( ) fdict = { "_callables_db" : self . _callables_db , "_reverse_callables_db" : dict ( [ ( str ( k ) , v ) for k , v in items ] ) , "_modules_dict" : self . _modules_dict , "_fnames" : self . _fnames , "_module_names" : self . _module_names , "_class_names" : self . _class_names , } with open ( callables_fname , "w" ) as fobj : json . dump ( fdict , fobj ) | r Save traced modules information to a JSON _ file . |
7,886 | def _close_callable ( self , node , force = False ) : try : lineno = node . lineno except AttributeError : return if lineno <= self . _processed_line : return name = "" try : name = ( node . name if hasattr ( node , "name" ) else ( node . targets [ 0 ] . id if hasattr ( node . targets [ 0 ] , "id" ) else node . targets [ 0 ] . value . id ) ) except AttributeError : pass indent = self . _get_indent ( node ) count = - 1 dlist = [ ] while count >= - len ( self . _indent_stack ) : element_full_name = self . _indent_stack [ count ] [ "full_name" ] edict = self . _callables_db . get ( element_full_name , None ) stack_indent = self . _indent_stack [ count ] [ "level" ] open_callable = element_full_name and ( not edict [ "last_lineno" ] ) if open_callable and ( force or ( indent < stack_indent ) or ( ( indent == stack_indent ) and ( ( edict [ "type" ] != "prop" ) or ( ( edict [ "type" ] == "prop" ) and ( name and ( name != element_full_name ) ) ) ) ) ) : edict [ "last_lineno" ] = lineno - 1 dlist . append ( count ) if indent > stack_indent : break count -= 1 stack = self . _indent_stack stack_length = len ( self . _indent_stack ) dlist = [ item for item in dlist if stack [ item ] [ "type" ] != "module" ] for item in dlist : del self . _indent_stack [ stack_length + item ] | Record last line number of callable . |
7,887 | def _get_indent ( self , node ) : lineno = node . lineno if lineno > len ( self . _lines ) : return - 1 wsindent = self . _wsregexp . match ( self . _lines [ lineno - 1 ] ) return len ( wsindent . group ( 1 ) ) | Get node indentation level . |
7,888 | def _in_class ( self , node ) : indent = self . _get_indent ( node ) for indent_dict in reversed ( self . _indent_stack ) : if ( indent_dict [ "level" ] < indent ) or ( indent_dict [ "type" ] == "module" ) : return indent_dict [ "type" ] == "class" | Find if callable is function or method . |
7,889 | def _pop_indent_stack ( self , node , node_type = None , action = None ) : indent = self . _get_indent ( node ) indent_stack = copy . deepcopy ( self . _indent_stack ) while ( len ( indent_stack ) > 1 ) and ( ( ( indent <= indent_stack [ - 1 ] [ "level" ] ) and ( indent_stack [ - 1 ] [ "type" ] != "module" ) ) or ( indent_stack [ - 1 ] [ "type" ] == "prop" ) ) : self . _close_callable ( node ) indent_stack . pop ( ) name = ( ( node . targets [ 0 ] . id if hasattr ( node . targets [ 0 ] , "id" ) else node . targets [ 0 ] . value . id ) if node_type == "prop" else node . name ) element_full_name = "." . join ( [ self . _module ] + [ indent_dict [ "prefix" ] for indent_dict in indent_stack if indent_dict [ "type" ] != "module" ] + [ name ] ) + ( "({0})" . format ( action ) if action else "" ) self . _indent_stack = indent_stack self . _indent_stack . append ( { "level" : indent , "prefix" : name , "type" : node_type , "full_name" : element_full_name , "lineno" : node . lineno , } ) return element_full_name | Get callable full name . |
7,890 | def generic_visit ( self , node ) : self . _close_callable ( node ) super ( _AstTreeScanner , self ) . generic_visit ( node ) | Implement generic node . |
7,891 | def visit_Assign ( self , node ) : if self . _in_class ( node ) : element_full_name = self . _pop_indent_stack ( node , "prop" ) code_id = ( self . _fname , node . lineno ) self . _processed_line = node . lineno self . _callables_db [ element_full_name ] = { "name" : element_full_name , "type" : "prop" , "code_id" : code_id , "last_lineno" : None , } self . _reverse_callables_db [ code_id ] = element_full_name self . generic_visit ( node ) | Implement assignment walker . |
7,892 | def visit_ClassDef ( self , node ) : element_full_name = self . _pop_indent_stack ( node , "class" ) code_id = ( self . _fname , node . lineno ) self . _processed_line = node . lineno self . _class_names . append ( element_full_name ) self . _callables_db [ element_full_name ] = { "name" : element_full_name , "type" : "class" , "code_id" : code_id , "last_lineno" : None , } self . _reverse_callables_db [ code_id ] = element_full_name self . generic_visit ( node ) | Implement class walker . |
7,893 | def run ( task_creators , args , task_selectors = [ ] ) : if args . reset_dep : sys . exit ( DoitMain ( WrapitLoader ( args , task_creators ) ) . run ( [ 'reset-dep' ] ) ) else : sys . exit ( DoitMain ( WrapitLoader ( args , task_creators ) ) . run ( task_selectors ) ) | run doit using task_creators |
7,894 | def tasks_by_tag ( self , registry_tag ) : if registry_tag not in self . __registry . keys ( ) : return None tasks = self . __registry [ registry_tag ] return tasks if self . __multiple_tasks_per_tag__ is True else tasks [ 0 ] | Get tasks from registry by its tag |
7,895 | def count ( self ) : result = 0 for tasks in self . __registry . values ( ) : result += len ( tasks ) return result | Registered task count |
7,896 | def add ( cls , task_cls ) : if task_cls . __registry_tag__ is None and cls . __skip_none_registry_tag__ is True : return cls . registry_storage ( ) . add ( task_cls ) | Add task class to storage |
7,897 | def my_func ( name ) : exobj = addex ( TypeError , "Argument `name` is not valid" ) exobj ( not isinstance ( name , str ) ) print ( "My name is {0}" . format ( name ) ) | Sample function . |
7,898 | def add_prioritized ( self , command_obj , priority ) : if priority not in self . __priorities . keys ( ) : self . __priorities [ priority ] = [ ] self . __priorities [ priority ] . append ( command_obj ) | Add command with the specified priority |
7,899 | def __track_vars ( self , command_result ) : command_env = command_result . environment ( ) for var_name in self . tracked_vars ( ) : if var_name in command_env . keys ( ) : self . __vars [ var_name ] = command_env [ var_name ] | Check if there are any tracked variable inside the result . And keep them for future use . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.