idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
38,200 | def search_location_check ( cls , location ) : if not ( isinstance ( location , Mapping ) and set ( location . keys ( ) ) == _LOCATION_SEARCH_ARGS ) : raise ValueError ( 'Search location should be mapping with keys: %s' % _LOCATION_SEARCH_ARGS ) cls . location_check ( location [ 'lat' ] , location [ 'long' ] ) radius = location [ 'radius' ] if not ( isinstance ( radius , number_types ) and 0 < radius <= 20038 ) : raise ValueError ( "Radius: '{radius}' is invalid" . format ( radius = radius ) ) | Core . Client . request_search location parameter should be a dictionary that contains lat lon and radius floats |
38,201 | def __search_text_check_convert ( cls , text ) : text = cls . check_convert_string ( text , name = 'text' , no_leading_trailing_whitespace = False ) if len ( text ) > VALIDATION_META_SEARCH_TEXT : raise ValueError ( "Search text can contain at most %d characters" % VALIDATION_META_SEARCH_TEXT ) text = ' ' . join ( _PATTERN_WORDS . findall ( text ) ) if not text : raise ValueError ( 'Search text must contain at least one non-whitespace term (word)' ) return text | Converts and keeps only words in text deemed to be valid |
38,202 | def callable_check ( func , arg_count = 1 , arg_value = None , allow_none = False ) : if func is None : if not allow_none : raise ValueError ( 'callable cannot be None' ) elif not arg_checker ( func , * [ arg_value for _ in range ( arg_count ) ] ) : raise ValueError ( 'callable %s invalid (for %d arguments)' % ( func , arg_count ) ) | Check whether func is callable with the given number of positional arguments . Returns True if check succeeded False otherwise . |
38,203 | def list_feeds ( self , limit = 500 , offset = 0 ) : return self . __list ( R_FEED , limit = limit , offset = offset ) [ 'feeds' ] | List all the feeds on this Thing . |
38,204 | def list_controls ( self , limit = 500 , offset = 0 ) : return self . __list ( R_CONTROL , limit = limit , offset = offset ) [ 'controls' ] | List all the controls on this Thing . |
38,205 | def set_public ( self , public = True ) : logger . info ( "set_public(public=%s) [lid=%s]" , public , self . __lid ) evt = self . _client . _request_entity_meta_setpublic ( self . __lid , public ) self . _client . _wait_and_except_if_failed ( evt ) | Sets your Thing to be public to all . If public = True . This means the tags label and description of your Thing are now searchable by anybody along with its location and the units of any values on any Points . If public = False the metadata of your Thing is no longer searchable . |
38,206 | def rename ( self , new_lid ) : logger . info ( "rename(new_lid=\"%s\") [lid=%s]" , new_lid , self . __lid ) evt = self . _client . _request_entity_rename ( self . __lid , new_lid ) self . _client . _wait_and_except_if_failed ( evt ) self . __lid = new_lid self . _client . _notify_thing_lid_change ( self . __lid , new_lid ) | Rename the Thing . |
38,207 | def reassign ( self , new_epid ) : logger . info ( "reassign(new_epid=\"%s\") [lid=%s]" , new_epid , self . __lid ) evt = self . _client . _request_entity_reassign ( self . __lid , new_epid ) self . _client . _wait_and_except_if_failed ( evt ) | Reassign the Thing from one agent to another . |
38,208 | def delete_tag ( self , tags ) : if isinstance ( tags , str ) : tags = [ tags ] evt = self . _client . _request_entity_tag_update ( self . __lid , tags , delete = True ) self . _client . _wait_and_except_if_failed ( evt ) | Delete tags for a Thing in the language you specify . Case will be ignored and any tags matching lower - cased will be deleted . |
38,209 | def list_tag ( self , limit = 500 , offset = 0 ) : evt = self . _client . _request_entity_tag_list ( self . __lid , limit = limit , offset = offset ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'tags' ] | List all the tags for this Thing |
38,210 | def get_meta ( self ) : rdf = self . get_meta_rdf ( fmt = 'n3' ) return ThingMeta ( self , rdf , self . _client . default_lang , fmt = 'n3' ) | Get the metadata object for this Thing |
38,211 | def get_meta_rdf ( self , fmt = 'n3' ) : evt = self . _client . _request_entity_meta_get ( self . __lid , fmt = fmt ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'meta' ] | Get the metadata for this Thing in rdf fmt |
38,212 | def set_meta_rdf ( self , rdf , fmt = 'n3' ) : evt = self . _client . _request_entity_meta_set ( self . __lid , rdf , fmt = fmt ) self . _client . _wait_and_except_if_failed ( evt ) | Set the metadata for this Thing in RDF fmt |
38,213 | def get_feed ( self , pid ) : with self . __new_feeds : try : return self . __new_feeds . pop ( pid ) except KeyError as ex : raise_from ( KeyError ( 'Feed %s not know as new' % pid ) , ex ) | Get the details of a newly created feed . This only applies to asynchronous creation of feeds and the new feed instance can only be retrieved once . |
38,214 | def get_control ( self , pid ) : with self . __new_controls : try : return self . __new_controls . pop ( pid ) except KeyError as ex : raise_from ( KeyError ( 'Control %s not know as new' % pid ) , ex ) | Get the details of a newly created control . This only applies to asynchronous creation of feeds and the new control instance can only be retrieved once . |
38,215 | def delete_feed ( self , pid ) : logger . info ( "delete_feed(pid=\"%s\") [lid=%s]" , pid , self . __lid ) return self . __delete_point ( R_FEED , pid ) | Delete a feed identified by its local id . |
38,216 | def delete_control ( self , pid ) : logger . info ( "delete_control(pid=\"%s\") [lid=%s]" , pid , self . __lid ) return self . __delete_point ( R_CONTROL , pid ) | Delete a control identified by its local id . |
38,217 | def __sub_del_reference ( self , req , key ) : if not req . success : try : self . __new_subs . pop ( key ) except KeyError : logger . warning ( 'No sub ref %s' , key ) | Blindly clear reference to pending subscription on failure . |
38,218 | def list_connections ( self , limit = 500 , offset = 0 ) : evt = self . _client . _request_sub_list ( self . __lid , limit = limit , offset = offset ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'subs' ] | List Points to which this Things is subscribed . I . e . list all the Points this Thing is following and controls it s attached to |
38,219 | def get_recent_async ( self , count , callback ) : validate_nonnegative_int ( count , 'count' ) Validation . callable_check ( callback , allow_none = True ) evt = self . _client . _request_sub_recent ( self . subid , count = count ) self . _client . _add_recent_cb_for ( evt , callback ) return evt | Similar to get_recent except instead of returning an iterable passes each dict to the given function which must accept a single argument . Returns the request . |
38,220 | def simulate ( self , data , mime = None ) : self . _client . simulate_feeddata ( self . __pointid , data , mime ) | Simulate the arrival of feeddata into the feed . Useful if the remote Thing doesn t publish very often . |
38,221 | def ask ( self , data , mime = None ) : evt = self . ask_async ( data , mime = mime ) self . _client . _wait_and_except_if_failed ( evt ) | Request a remote control to do something . Ask is fire - and - forget in that you won t receive any notification of the success or otherwise of the action at the far end . |
38,222 | def tell ( self , data , timeout = 10 , mime = None ) : evt = self . tell_async ( data , timeout = timeout , mime = mime ) try : self . _client . _wait_and_except_if_failed ( evt , timeout = timeout ) except IOTSyncTimeout : return 'timeout' return True if evt . payload [ 'success' ] else evt . payload [ 'reason' ] | Order a remote control to do something . Tell is confirmed in that you will receive a notification of the success or otherwise of the action at the far end via a callback |
38,223 | def rename ( self , new_pid ) : logger . info ( "rename(new_pid=\"%s\") [lid=%s, pid=%s]" , new_pid , self . __lid , self . __pid ) evt = self . _client . _request_point_rename ( self . _type , self . __lid , self . __pid , new_pid ) self . _client . _wait_and_except_if_failed ( evt ) self . __pid = new_pid | Rename the Point . |
38,224 | def list ( self , limit = 50 , offset = 0 ) : logger . info ( "list(limit=%s, offset=%s) [lid=%s,pid=%s]" , limit , offset , self . __lid , self . __pid ) evt = self . _client . _request_point_value_list ( self . __lid , self . __pid , self . _type , limit = limit , offset = offset ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'values' ] | List all the values on this Point . |
38,225 | def list_followers ( self ) : evt = self . _client . _request_point_list_detailed ( self . _type , self . __lid , self . __pid ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'subs' ] | list followers for this point i . e . remote follows for feeds and remote attaches for controls . |
38,226 | def get_meta ( self ) : rdf = self . get_meta_rdf ( fmt = 'n3' ) return PointMeta ( self , rdf , self . _client . default_lang , fmt = 'n3' ) | Get the metadata object for this Point |
38,227 | def get_meta_rdf ( self , fmt = 'n3' ) : evt = self . _client . _request_point_meta_get ( self . _type , self . __lid , self . __pid , fmt = fmt ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'meta' ] | Get the metadata for this Point in rdf fmt |
38,228 | def set_meta_rdf ( self , rdf , fmt = 'n3' ) : evt = self . _client . _request_point_meta_set ( self . _type , self . __lid , self . __pid , rdf , fmt = fmt ) self . _client . _wait_and_except_if_failed ( evt ) | Set the metadata for this Point in rdf fmt |
38,229 | def delete_tag ( self , tags ) : if isinstance ( tags , str ) : tags = [ tags ] evt = self . _client . _request_point_tag_update ( self . _type , self . __lid , self . __pid , tags , delete = True ) self . _client . _wait_and_except_if_failed ( evt ) | Delete tags for a Point in the language you specify . Case will be ignored and any tags matching lower - cased will be deleted . |
38,230 | def list_tag ( self , limit = 50 , offset = 0 ) : evt = self . _client . _request_point_tag_list ( self . _type , self . __lid , self . __pid , limit = limit , offset = offset ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'tags' ] | List all the tags for this Point |
38,231 | def share ( self , data , mime = None , time = None ) : evt = self . share_async ( data , mime = mime , time = time ) self . _client . _wait_and_except_if_failed ( evt ) | Share some data from this Feed |
38,232 | def get_recent_info ( self ) : evt = self . _client . _request_point_recent_info ( self . _type , self . lid , self . pid ) self . _client . _wait_and_except_if_failed ( evt ) return evt . payload [ 'recent' ] | Retrieves statistics and configuration about recent storage for this Feed . |
38,233 | def to_dict ( self ) : return { value . label : value . value for value in self . __values if not value . unset } | Converts the set of values into a dictionary . Unset values are excluded . |
38,234 | def _from_dict ( cls , values , value_filter , dictionary , allow_unset = True ) : if not isinstance ( dictionary , Mapping ) : raise TypeError ( 'dictionary should be mapping' ) obj = cls ( values , value_filter ) values = obj . __values for name , value in dictionary . items ( ) : if not isinstance ( name , string_types ) : raise TypeError ( 'Key %s is not a string' % str ( name ) ) setattr ( values , name , value ) if obj . missing and not allow_unset : raise ValueError ( '%d value(s) are unset' % len ( obj . missing ) ) return obj | Instantiates new PointDataObject populated from the given dictionary . With allow_unset = False a ValueError will be raised if any value has not been set . Used by PointDataObjectHandler |
38,235 | def update ( self ) : graph = Graph ( ) graph . parse ( data = self . __parent . get_meta_rdf ( fmt = self . __fmt ) , format = self . __fmt ) self . _graph = graph | Gets the latest version of your metadata from the infrastructure and updates your local copy |
38,236 | def acquire ( self , blocking = True , timeout = - 1 ) : if not isinstance ( timeout , ( int , float ) ) : raise TypeError ( 'a float is required' ) if blocking : if timeout == - 1 : with self . __condition : while not self . __lock . acquire ( False ) : self . __condition . wait ( 60 ) return True elif timeout == 0 : return self . __lock . acquire ( False ) elif timeout < 0 : raise ValueError ( 'timeout value must be strictly positive (or -1)' ) else : start = time ( ) waited_time = 0 with self . __condition : while waited_time < timeout : if self . __lock . acquire ( False ) : return True else : self . __condition . wait ( timeout - waited_time ) waited_time = time ( ) - start return False elif timeout != - 1 : raise ValueError ( 'can\'t specify a timeout for a non-blocking call' ) else : return self . __lock . acquire ( False ) | Acquire a lock blocking or non - blocking . Blocks until timeout if timeout a positive float and blocking = True . A timeout value of - 1 blocks indefinitely unless blocking = False . |
38,237 | def release ( self ) : self . __lock . release ( ) with self . __condition : self . __condition . notify ( ) | Release a lock . |
38,238 | def set_config ( self , config ) : if self . launch_url == None : self . launch_url = config . launch_url self . custom_params . update ( config . custom_params ) | Set launch data from a ToolConfig . |
38,239 | def has_required_params ( self ) : return self . consumer_key and self . consumer_secret and self . resource_link_id and self . launch_url | Check if required parameters for a tool launch are set . |
38,240 | def _sent_without_response ( self , send_time_before ) : return not self . _messages and self . _send_time and self . _send_time < send_time_before | Used internally to determine whether the request has not received any response from the container and was send before the given time . Unsent requests are not considered . |
38,241 | def is_set ( self ) : if self . __event . is_set ( ) : if self . exception is not None : raise self . exception return True return False | Returns True if the request has finished or False if it is still pending . |
38,242 | def _set ( self ) : self . __event . set ( ) if self . _complete_func : self . __run_completion_func ( self . _complete_func , self . id_ ) | Called internally by Client to indicate this request has finished |
38,243 | def wait ( self , timeout = None ) : if self . __event . wait ( timeout ) : if self . exception is not None : raise self . exception return True return False | Wait for the request to finish optionally timing out . Returns True if the request has finished or False if it is still pending . |
38,244 | def _check_middleware_dependencies ( concerned_object , required_middleware ) : declared_middleware = getattr ( settings , 'MIDDLEWARE' , None ) if declared_middleware is None : declared_middleware = settings . MIDDLEWARE_CLASSES matching_middleware = [ mw for mw in declared_middleware if mw in required_middleware ] if required_middleware != matching_middleware : raise AssertionError ( "{} requires middleware order {} but matching middleware was {}" . format ( concerned_object , required_middleware , matching_middleware ) ) | Check required middleware dependencies exist and in the correct order . |
38,245 | def parse_request ( self , request , parameters = None , fake_method = None ) : return ( request . method , request . url , request . headers , request . form . copy ( ) ) | Parse Flask request |
38,246 | def parse_request ( self , request , parameters , fake_method = None ) : return ( fake_method or request . method , request . build_absolute_uri ( ) , request . META , ( dict ( request . POST . iteritems ( ) ) if request . method == 'POST' else parameters ) ) | Parse Django request |
38,247 | def parse_request ( self , request , parameters = None , fake_method = None ) : return ( request . method , request . url , request . headers , request . POST . mixed ( ) ) | Parse WebOb request |
38,248 | def from_post_response ( post_response , content ) : response = OutcomeResponse ( ) response . post_response = post_response response . response_code = post_response . status response . process_xml ( content ) return response | Convenience method for creating a new OutcomeResponse from a response object . |
38,249 | def process_xml ( self , xml ) : try : root = objectify . fromstring ( xml ) self . message_identifier = root . imsx_POXHeader . imsx_POXResponseHeaderInfo . imsx_messageIdentifier status_node = root . imsx_POXHeader . imsx_POXResponseHeaderInfo . imsx_statusInfo self . code_major = status_node . imsx_codeMajor self . severity = status_node . imsx_severity self . description = status_node . imsx_description self . message_ref_identifier = str ( status_node . imsx_messageRefIdentifier ) self . operation = status_node . imsx_operationRefIdentifier try : self . score = str ( root . imsx_POXBody . readResultResponse . result . resultScore . textString ) except AttributeError : pass except : pass | Parse OutcomeResponse data form XML . |
38,250 | def generate_response_xml ( self ) : root = etree . Element ( 'imsx_POXEnvelopeResponse' , xmlns = 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0' ) header = etree . SubElement ( root , 'imsx_POXHeader' ) header_info = etree . SubElement ( header , 'imsx_POXResponseHeaderInfo' ) version = etree . SubElement ( header_info , 'imsx_version' ) version . text = 'V1.0' message_identifier = etree . SubElement ( header_info , 'imsx_messageIdentifier' ) message_identifier . text = str ( self . message_identifier ) status_info = etree . SubElement ( header_info , 'imsx_statusInfo' ) code_major = etree . SubElement ( status_info , 'imsx_codeMajor' ) code_major . text = str ( self . code_major ) severity = etree . SubElement ( status_info , 'imsx_severity' ) severity . text = str ( self . severity ) description = etree . SubElement ( status_info , 'imsx_description' ) description . text = str ( self . description ) message_ref_identifier = etree . SubElement ( status_info , 'imsx_messageRefIdentifier' ) message_ref_identifier . text = str ( self . message_ref_identifier ) operation_ref_identifier = etree . SubElement ( status_info , 'imsx_operationRefIdentifier' ) operation_ref_identifier . text = str ( self . operation ) body = etree . SubElement ( root , 'imsx_POXBody' ) response = etree . SubElement ( body , '%s%s' % ( self . operation , 'Response' ) ) if self . score : result = etree . SubElement ( response , 'result' ) result_score = etree . SubElement ( result , 'resultScore' ) language = etree . SubElement ( result_score , 'language' ) language . text = 'en' text_string = etree . SubElement ( result_score , 'textString' ) text_string . text = str ( self . score ) return '<?xml version="1.0" encoding="UTF-8"?>' + etree . tostring ( root ) | Generate XML based on the current configuration . |
38,251 | def set_custom_metrics_for_course_key ( course_key ) : if not newrelic : return newrelic . agent . add_custom_parameter ( 'course_id' , six . text_type ( course_key ) ) newrelic . agent . add_custom_parameter ( 'org' , six . text_type ( course_key . org ) ) | Set monitoring custom metrics related to a course key . |
38,252 | def set_monitoring_transaction_name ( name , group = None , priority = None ) : if not newrelic : return newrelic . agent . set_transaction_name ( name , group , priority ) | Sets the transaction name for monitoring . |
38,253 | def function_trace ( function_name ) : if newrelic : nr_transaction = newrelic . agent . current_transaction ( ) with newrelic . agent . FunctionTrace ( nr_transaction , function_name ) : yield else : yield | Wraps a chunk of code that we want to appear as a separate explicit segment in our monitoring tools . |
38,254 | def filter_by ( self , types = ( ) , units = ( ) ) : if not ( isinstance ( types , Sequence ) and isinstance ( units , Sequence ) ) : raise TypeError ( 'types/units must be a sequence' ) empty = frozenset ( ) if types : type_names = set ( ) for type_ in types : type_names |= self . by_type . get ( type_ , empty ) if not units : return type_names if units : unit_names = set ( ) for unit in units : unit_names |= self . by_unit . get ( unit , empty ) if not types : return unit_names return ( type_names & unit_names ) if ( types and units ) else empty | Return list of value labels filtered by either or both type and unit . An empty sequence for either argument will match as long as the other argument matches any values . |
38,255 | def __get_values ( self ) : values = [ ] if self . __remote : description = self . __client . describe ( self . __point ) if description is not None : if description [ 'type' ] != 'Point' : raise IOTUnknown ( '%s is not a Point' % self . __point ) values = description [ 'meta' ] [ 'values' ] else : limit = 100 offset = 0 while True : new = self . __point . list ( limit = limit , offset = offset ) values += new if len ( new ) < limit : break offset += limit lang = self . __client . default_lang for value in values : value [ 'comment' ] = value [ 'comment' ] . get ( lang , None ) if value [ 'comment' ] else None return values | Retrieve value information either via describe or point value listing . MUST be called within lock . |
38,256 | def get_s3_multipart_chunk_size ( filesize ) : if filesize <= AWS_MAX_MULTIPART_COUNT * AWS_MIN_CHUNK_SIZE : return AWS_MIN_CHUNK_SIZE else : div = filesize // AWS_MAX_MULTIPART_COUNT if div * AWS_MAX_MULTIPART_COUNT < filesize : div += 1 return ( ( div + MiB - 1 ) // MiB ) * MiB | Returns the chunk size of the S3 multipart object given a file s size . |
38,257 | def set_ext_param ( self , ext_key , param_key , val ) : if not self . extensions [ ext_key ] : self . extensions [ ext_key ] = defaultdict ( lambda : None ) self . extensions [ ext_key ] [ param_key ] = val | Set the provided parameter in a set of extension parameters . |
38,258 | def get_ext_param ( self , ext_key , param_key ) : return self . extensions [ ext_key ] [ param_key ] if self . extensions [ ext_key ] else None | Get specific param in set of provided extension parameters . |
38,259 | def process_xml ( self , xml ) : root = objectify . fromstring ( xml , parser = etree . XMLParser ( ) ) for child in root . getchildren ( ) : if 'title' in child . tag : self . title = child . text if 'description' in child . tag : self . description = child . text if 'secure_launch_url' in child . tag : self . secure_launch_url = child . text elif 'launch_url' in child . tag : self . launch_url = child . text if 'icon' in child . tag : self . icon = child . text if 'secure_icon' in child . tag : self . secure_icon = child . text if 'cartridge_bundle' in child . tag : self . cartridge_bundle = child . attrib [ 'identifierref' ] if 'catridge_icon' in child . tag : self . cartridge_icon = child . atrib [ 'identifierref' ] if 'vendor' in child . tag : for v_child in child . getchildren ( ) : if 'code' in v_child . tag : self . vendor_code = v_child . text if 'description' in v_child . tag : self . vendor_description = v_child . text if 'name' in v_child . tag : self . vendor_name = v_child . text if 'url' in v_child . tag : self . vendor_url = v_child . text if 'contact' in v_child . tag : for c_child in v_child : if 'name' in c_child . tag : self . vendor_contact_name = c_child . text if 'email' in c_child . tag : self . vendor_contact_email = c_child . text if 'custom' in child . tag : for custom_child in child . getchildren ( ) : self . custom_params [ custom_child . attrib [ 'name' ] ] = custom_child . text if 'extensions' in child . tag : platform = child . attrib [ 'platform' ] properties = { } for ext_child in child . getchildren ( ) : if 'property' in ext_child . tag : properties [ ext_child . attrib [ 'name' ] ] = ext_child . text elif 'options' in ext_child . tag : opt_name = ext_child . attrib [ 'name' ] options = { } for option_child in ext_child . getchildren ( ) : options [ option_child . attrib [ 'name' ] ] = option_child . text properties [ opt_name ] = options self . set_ext_params ( platform , properties ) | Parse tool configuration data out of the Common Cartridge LTI link XML . |
38,260 | def to_xml ( self , opts = defaultdict ( lambda : None ) ) : if not self . launch_url or not self . secure_launch_url : raise InvalidLTIConfigError ( 'Invalid LTI configuration' ) root = etree . Element ( 'cartridge_basiclti_link' , attrib = { '{%s}%s' % ( NSMAP [ 'xsi' ] , 'schemaLocation' ) : 'http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd' , 'xmlns' : 'http://www.imsglobal.org/xsd/imslticc_v1p0' } , nsmap = NSMAP ) for key in [ 'title' , 'description' , 'launch_url' , 'secure_launch_url' ] : option = etree . SubElement ( root , '{%s}%s' % ( NSMAP [ 'blti' ] , key ) ) option . text = getattr ( self , key ) vendor_keys = [ 'name' , 'code' , 'description' , 'url' ] if any ( 'vendor_' + key for key in vendor_keys ) or self . vendor_contact_email : vendor_node = etree . SubElement ( root , '{%s}%s' % ( NSMAP [ 'blti' ] , 'vendor' ) ) for key in vendor_keys : if getattr ( self , 'vendor_' + key ) != None : v_node = etree . SubElement ( vendor_node , '{%s}%s' % ( NSMAP [ 'lticp' ] , key ) ) v_node . text = getattr ( self , 'vendor_' + key ) if getattr ( self , 'vendor_contact_email' ) : v_node = etree . SubElement ( vendor_node , '{%s}%s' % ( NSMAP [ 'lticp' ] , 'contact' ) ) c_name = etree . SubElement ( v_node , '{%s}%s' % ( NSMAP [ 'lticp' ] , 'name' ) ) c_name . text = self . vendor_contact_name c_email = etree . SubElement ( v_node , '{%s}%s' % ( NSMAP [ 'lticp' ] , 'email' ) ) c_email . text = self . vendor_contact_email if len ( self . custom_params ) != 0 : custom_node = etree . SubElement ( root , '{%s}%s' % ( NSMAP [ 'blti' ] , 'custom' ) ) for ( key , val ) in sorted ( self . custom_params . items ( ) ) : c_node = etree . SubElement ( custom_node , '{%s}%s' % ( NSMAP [ 'lticm' ] , 'property' ) ) c_node . set ( 'name' , key ) c_node . text = val if len ( self . extensions ) != 0 : for ( key , params ) in sorted ( self . extensions . items ( ) ) : extension_node = etree . SubElement ( root , '{%s}%s' % ( NSMAP [ 'blti' ] , 'extensions' ) , platform = key ) self . recursive_options ( extension_node , params ) if getattr ( self , 'cartridge_bundle' ) : identifierref = etree . SubElement ( root , 'cartridge_bundle' , identifierref = self . cartridge_bundle ) if getattr ( self , 'cartridge_icon' ) : identifierref = etree . SubElement ( root , 'cartridge_icon' , identifierref = self . cartridge_icon ) return '<?xml version="1.0" encoding="UTF-8"?>' + etree . tostring ( root ) | Generate XML from the current settings . |
38,261 | def destroy ( self ) : fragment = self . fragment if fragment : fragment . setFragmentListener ( None ) if self . adapter is not None : self . adapter . removeFragment ( self . fragment ) del self . fragment super ( AndroidFragment , self ) . destroy ( ) | Custom destructor that deletes the fragment and removes itself from the adapter it was added to . |
38,262 | def on_create_view ( self ) : d = self . declaration changed = not d . condition if changed : d . condition = True view = self . get_view ( ) if changed : self . ready . set_result ( True ) return view | Trigger the click |
38,263 | def get_view ( self ) : d = self . declaration if d . cached and self . widget : return self . widget if d . defer_loading : self . widget = FrameLayout ( self . get_context ( ) ) app = self . get_context ( ) app . deferred_call ( lambda : self . widget . addView ( self . load_view ( ) , 0 ) ) else : self . widget = self . load_view ( ) return self . widget | Get the page to display . If a view has already been created and is cached use that otherwise initialize the view and proxy . If defer loading is used wrap the view in a FrameLayout and defer add view until later . |
38,264 | def engine ( func ) : func = _make_coroutine_wrapper ( func , replace_callback = False ) @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : future = func ( * args , ** kwargs ) def final_callback ( future ) : if future . result ( ) is not None : raise ReturnValueIgnoredError ( "@gen.engine functions cannot return values: %r" % ( future . result ( ) , ) ) future . add_done_callback ( stack_context . wrap ( final_callback ) ) return wrapper | Callback - oriented decorator for asynchronous generators . |
38,265 | def Task ( func , * args , ** kwargs ) : future = Future ( ) def handle_exception ( typ , value , tb ) : if future . done ( ) : return False future . set_exc_info ( ( typ , value , tb ) ) return True def set_result ( result ) : if future . done ( ) : return future . set_result ( result ) with stack_context . ExceptionStackContext ( handle_exception ) : func ( * args , callback = _argument_adapter ( set_result ) , ** kwargs ) return future | Adapts a callback - based asynchronous function for use in coroutines . |
38,266 | def _contains_yieldpoint ( children ) : if isinstance ( children , dict ) : return any ( isinstance ( i , YieldPoint ) for i in children . values ( ) ) if isinstance ( children , list ) : return any ( isinstance ( i , YieldPoint ) for i in children ) return False | Returns True if children contains any YieldPoints . |
38,267 | def _argument_adapter ( callback ) : def wrapper ( * args , ** kwargs ) : if kwargs or len ( args ) > 1 : callback ( Arguments ( args , kwargs ) ) elif args : callback ( args [ 0 ] ) else : callback ( None ) return wrapper | Returns a function that when invoked runs callback with one arg . |
38,268 | def done ( self ) : if self . _finished or self . _unfinished : return False self . current_index = self . current_future = None return True | Returns True if this iterator has no more results . |
38,269 | def _return_result ( self , done ) : chain_future ( done , self . _running_future ) self . current_future = done self . current_index = self . _unfinished . pop ( done ) | Called set the returned future s state that of the future we yielded and set the current future for the iterator . |
38,270 | def register_callback ( self , key ) : if self . pending_callbacks is None : self . pending_callbacks = set ( ) self . results = { } if key in self . pending_callbacks : raise KeyReuseError ( "key %r is already pending" % ( key , ) ) self . pending_callbacks . add ( key ) | Adds key to the list of callbacks . |
38,271 | def is_ready ( self , key ) : if self . pending_callbacks is None or key not in self . pending_callbacks : raise UnknownKeyError ( "key %r is not pending" % ( key , ) ) return key in self . results | Returns true if a result is available for key . |
38,272 | def set_result ( self , key , result ) : self . results [ key ] = result if self . yield_point is not None and self . yield_point . is_ready ( ) : try : self . future . set_result ( self . yield_point . get_result ( ) ) except : self . future . set_exc_info ( sys . exc_info ( ) ) self . yield_point = None self . run ( ) | Sets the result for key and attempts to resume the generator . |
38,273 | def pop_result ( self , key ) : self . pending_callbacks . remove ( key ) return self . results . pop ( key ) | Returns the result for key and unregisters it . |
38,274 | def write_message ( self , data , binary = False ) : self . connection . write_message ( data , binary ) | Write a message to the client |
38,275 | def render_files ( self , root = None ) : if root is None : tmp = os . environ . get ( 'TMP' ) root = sys . path [ 1 if tmp and tmp in sys . path else 0 ] items = [ ] for filename in os . listdir ( root ) : f , ext = os . path . splitext ( filename ) if ext in [ '.py' , '.enaml' ] : items . append ( FILE_TMPL . format ( name = filename , id = filename ) ) return "" . join ( items ) | Render the file path as accordions |
38,276 | def start ( self ) : print ( "Starting debug client cwd: {}" . format ( os . getcwd ( ) ) ) print ( "Sys path: {}" . format ( sys . path ) ) self . hotswap = Hotswapper ( debug = False ) if self . mode == 'server' : self . server . start ( self ) else : self . client . start ( self ) | Start the dev session . Attempt to use tornado first then try twisted |
38,277 | def _default_url ( self ) : host = 'localhost' if self . mode == 'remote' else self . host return 'ws://{}:{}/dev' . format ( host , self . port ) | Websocket URL to connect to and listen for reload requests |
38,278 | def write_message ( self , data , binary = False ) : self . client . write_message ( data , binary = binary ) | Write a message to the active client |
38,279 | def handle_message ( self , data ) : msg = json . loads ( data ) print ( "Dev server message: {}" . format ( msg ) ) handler_name = 'do_{}' . format ( msg [ 'type' ] ) if hasattr ( self , handler_name ) : handler = getattr ( self , handler_name ) result = handler ( msg ) return { 'ok' : True , 'result' : result } else : err = "Warning: Unhandled message: {}" . format ( msg ) print ( err ) return { 'ok' : False , 'message' : err } | When we get a message |
38,280 | def do_reload ( self , msg ) : app = self . app try : self . app . widget . showLoading ( "Reloading... Please wait." , now = True ) except : pass self . save_changed_files ( msg ) if app . load_view is None : print ( "Warning: Reloading the view is not implemented. " "Please set `app.load_view` to support this." ) return if app . view is not None : try : app . view . destroy ( ) except : pass def wrapped ( f ) : def safe_reload ( * args , ** kwargs ) : try : return f ( * args , ** kwargs ) except : app . send_event ( Command . ERROR , traceback . format_exc ( ) ) return safe_reload app . deferred_call ( wrapped ( app . load_view ) , app ) | Called when the dev server wants to reload the view . |
38,281 | def do_hotswap ( self , msg ) : try : self . app . widget . showTooltip ( "Hot swapping..." , now = True ) except : pass self . save_changed_files ( msg ) hotswap = self . hotswap app = self . app try : print ( "Attempting hotswap...." ) with hotswap . active ( ) : hotswap . update ( app . view ) except : app . send_event ( Command . ERROR , traceback . format_exc ( ) ) | Attempt to hotswap the code |
38,282 | def update ( self ) : if not self . showing : return d = self . declaration self . set_show ( d . show ) | Update the PopupWindow if it is currently showing . This avoids calling update during initialization . |
38,283 | def refresh_items ( self ) : items = [ ] if self . condition : for nodes , key , f_locals in self . pattern_nodes : with new_scope ( key , f_locals ) : for node in nodes : child = node ( None ) if isinstance ( child , list ) : items . extend ( child ) else : items . append ( child ) for old in self . items : if not old . is_destroyed : old . destroy ( ) self . items = items | Refresh the items of the pattern . This method destroys the old items and creates and initializes the new items . |
38,284 | def load_module ( self , mod ) : try : return sys . modules [ mod ] except KeyError : pass lib = ExtensionImporter . extension_modules [ mod ] m = imp . load_dynamic ( mod , lib ) sys . modules [ mod ] = m return m | Load the extension using the load_dynamic method . |
38,285 | def destroy ( self ) : super ( AndroidTabLayout , self ) . destroy ( ) if self . tabs : del self . tabs | Destroy all tabs when destroyed |
38,286 | def update_atom_members ( old , new ) : old_keys = old . members ( ) . keys ( ) new_keys = new . members ( ) . keys ( ) for key in old_keys : old_obj = getattr ( old , key ) try : new_obj = getattr ( new , key ) if old_obj == new_obj : continue except AttributeError : try : delattr ( old , key ) except ( AttributeError , TypeError ) : pass continue try : setattr ( old , key , getattr ( new , key ) ) except ( AttributeError , TypeError ) : pass for key in set ( new_keys ) - set ( old_keys ) : try : setattr ( old , key , getattr ( new , key ) ) except ( AttributeError , TypeError ) : pass | Update an atom member |
38,287 | def update_class_by_type ( old , new ) : autoreload . update_class ( old , new ) if isinstance2 ( old , new , AtomMeta ) : update_atom_members ( old , new ) | Update declarative classes or fallback on default |
38,288 | def update ( self , old , new = None ) : if not new : new = type ( old ) ( ) if not new . is_initialized : new . initialize ( ) if self . debug : print ( "Updating {} with {}" . format ( old , new ) ) self . update_attrs ( old , new ) self . update_funcs ( old , new ) self . update_bindings ( old , new ) self . update_pattern_nodes ( old , new ) self . update_children ( old , new ) | Update given view declaration with new declaration |
38,289 | def find_best_matching_node ( self , new , old_nodes ) : name = new . __class__ . __name__ matches = [ c for c in old_nodes if name == c . __class__ . __name__ ] if self . debug : print ( "Found matches for {}: {} " . format ( new , matches ) ) return matches [ 0 ] if matches else None | Find the node that best matches the new node given the old nodes . If no good match exists return None . |
38,290 | def update_attrs ( self , old , new ) : if new . _d_storage : old . _d_storage = new . _d_storage | Update any attr members . |
38,291 | def update_bindings ( self , old , new ) : if new . _d_engine : old . _d_engine = new . _d_engine engine = old . _d_engine for k in engine . _handlers . keys ( ) : try : engine . update ( old , k ) except : if self . debug : print ( traceback . format_exc ( ) ) pass | Update any enaml operator bindings . |
38,292 | def init_widget ( self ) : super ( AndroidView , self ) . init_widget ( ) for k , v in self . get_declared_items ( ) : handler = getattr ( self , 'set_' + k , None ) if handler : handler ( v ) | Initialize the underlying widget . This reads all items declared in the enamldef block for this node and sets only the values that have been specified . All other values will be left as default . Doing it this way makes atom to only create the properties that need to be overridden from defaults thus greatly reducing the number of initialization checks saving time and memory . If you don t want this to happen override get_declared_keys to return an empty list . |
38,293 | def on_key ( self , view , key , event ) : d = self . declaration r = { 'key' : key , 'result' : False } d . key_event ( r ) return r [ 'result' ] | Trigger the key event |
38,294 | def on_touch ( self , view , event ) : d = self . declaration r = { 'event' : event , 'result' : False } d . touch_event ( r ) return r [ 'result' ] | Trigger the touch event |
38,295 | def set_visible ( self , visible ) : v = View . VISIBILITY_VISIBLE if visible else View . VISIBILITY_GONE self . widget . setVisibility ( v ) | Set the visibility of the widget . |
38,296 | def default ( cls ) : with enamlnative . imports ( ) : for impl in [ TornadoEventLoop , TwistedEventLoop , BuiltinEventLoop , ] : if impl . available ( ) : print ( "Using {} event loop!" . format ( impl ) ) return impl ( ) raise RuntimeError ( "No event loop implementation is available. " "Install tornado or twisted." ) | Get the first available event loop implementation based on which packages are installed . |
38,297 | def log_error ( self , callback , error = None ) : print ( "Uncaught error during callback: {}" . format ( callback ) ) print ( "Error: {}" . format ( error ) ) | Log the error that occurred when running the given callback . |
38,298 | def update_frame ( self ) : d = self . declaration if d . x or d . y or d . width or d . height : self . frame = ( d . x , d . y , d . width , d . height ) | Define the view frame for this widgets |
38,299 | def child_added ( self , child ) : super ( AndroidViewPager , self ) . child_added ( child ) self . _notify_count += 1 self . get_context ( ) . timed_call ( self . _notify_delay , self . _notify_change ) | When a child is added schedule a data changed notification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.