idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
234,700
def list_instances ( self , hourly = True , monthly = True , tags = None , cpus = None , memory = None , hostname = None , domain = None , local_disk = None , datacenter = None , nic_speed = None , public_ip = None , private_ip = None , ** kwargs ) : if 'mask' not in kwargs : items = [ 'id' , 'globalIdentifier' , 'host...
Retrieve a list of all virtual servers on the account .
234,701
def get_instance ( self , instance_id , ** kwargs ) : if 'mask' not in kwargs : kwargs [ 'mask' ] = ( 'id,' 'globalIdentifier,' 'fullyQualifiedDomainName,' 'hostname,' 'domain,' 'createDate,' 'modifyDate,' 'provisionDate,' 'notes,' 'dedicatedAccountHostOnlyFlag,' 'privateNetworkOnlyFlag,' 'primaryBackendIpAddress,' 'pr...
Get details about a virtual server instance .
234,702
def reload_instance ( self , instance_id , post_uri = None , ssh_keys = None , image_id = None ) : config = { } if post_uri : config [ 'customProvisionScriptUri' ] = post_uri if ssh_keys : config [ 'sshKeyIds' ] = [ key_id for key_id in ssh_keys ] if image_id : config [ 'imageTemplateId' ] = image_id return self . clie...
Perform an OS reload of an instance .
234,703
def wait_for_transaction ( self , instance_id , limit , delay = 10 ) : return self . wait_for_ready ( instance_id , limit , delay = delay , pending = True )
Waits on a VS transaction for the specified amount of time .
234,704
def verify_create_instance ( self , ** kwargs ) : kwargs . pop ( 'tags' , None ) create_options = self . _generate_create_dict ( ** kwargs ) return self . guest . generateOrderTemplate ( create_options )
Verifies an instance creation command .
234,705
def create_instance ( self , ** kwargs ) : tags = kwargs . pop ( 'tags' , None ) inst = self . guest . createObject ( self . _generate_create_dict ( ** kwargs ) ) if tags is not None : self . set_tags ( tags , guest_id = inst [ 'id' ] ) return inst
Creates a new virtual server instance .
234,706
def set_tags ( self , tags , guest_id ) : self . guest . setTags ( tags , id = guest_id )
Sets tags on a guest with a retry decorator
234,707
def create_instances ( self , config_list ) : tags = [ conf . pop ( 'tags' , None ) for conf in config_list ] resp = self . guest . createObjects ( [ self . _generate_create_dict ( ** kwargs ) for kwargs in config_list ] ) for instance , tag in zip ( resp , tags ) : if tag is not None : self . set_tags ( tag , guest_id...
Creates multiple virtual server instances .
234,708
def change_port_speed ( self , instance_id , public , speed ) : if public : return self . client . call ( 'Virtual_Guest' , 'setPublicNetworkInterfaceSpeed' , speed , id = instance_id ) else : return self . client . call ( 'Virtual_Guest' , 'setPrivateNetworkInterfaceSpeed' , speed , id = instance_id )
Allows you to change the port speed of a virtual server s NICs .
234,709
def _get_ids_from_hostname ( self , hostname ) : results = self . list_instances ( hostname = hostname , mask = "id" ) return [ result [ 'id' ] for result in results ]
List VS ids which match the given hostname .
234,710
def _get_ids_from_ip ( self , ip_address ) : try : socket . inet_aton ( ip_address ) except socket . error : return [ ] results = self . list_instances ( public_ip = ip_address , mask = "id" ) if results : return [ result [ 'id' ] for result in results ] results = self . list_instances ( private_ip = ip_address , mask ...
List VS ids which match the given ip address .
234,711
def upgrade ( self , instance_id , cpus = None , memory = None , nic_speed = None , public = True , preset = None ) : upgrade_prices = self . _get_upgrade_prices ( instance_id ) prices = [ ] data = { 'nic_speed' : nic_speed } if cpus is not None and preset is not None : raise ValueError ( "Do not use cpu, private and m...
Upgrades a VS instance .
234,712
def _get_package_items ( self ) : warnings . warn ( "use _get_upgrade_prices() instead" , DeprecationWarning ) mask = [ 'description' , 'capacity' , 'units' , 'prices[id,locationGroupId,categories[name,id,categoryCode]]' ] mask = "mask[%s]" % ',' . join ( mask ) package_keyname = "CLOUD_SERVER" package = self . orderin...
Following Method gets all the item ids related to VS .
234,713
def _get_upgrade_prices ( self , instance_id , include_downgrade_options = True ) : mask = [ 'id' , 'locationGroupId' , 'categories[name,id,categoryCode]' , 'item[description,capacity,units]' ] mask = "mask[%s]" % ',' . join ( mask ) return self . guest . getUpgradeItemPrices ( include_downgrade_options , id = instance...
Following Method gets all the price ids related to upgrading a VS .
234,714
def _get_price_id_for_upgrade_option ( self , upgrade_prices , option , value , public = True ) : option_category = { 'memory' : 'ram' , 'cpus' : 'guest_core' , 'nic_speed' : 'port_speed' } category_code = option_category . get ( option ) for price in upgrade_prices : if price . get ( 'categories' ) is None or price . ...
Find the price id for the option and value to upgrade . This
234,715
def _get_price_id_for_upgrade ( self , package_items , option , value , public = True ) : warnings . warn ( "use _get_price_id_for_upgrade_option() instead" , DeprecationWarning ) option_category = { 'memory' : 'ram' , 'cpus' : 'guest_core' , 'nic_speed' : 'port_speed' } category_code = option_category [ option ] for i...
Find the price id for the option and value to upgrade .
234,716
def interface_list ( env , securitygroup_id , sortby ) : mgr = SoftLayer . NetworkManager ( env . client ) table = formatting . Table ( COLUMNS ) table . sortby = sortby mask = ( ) secgroup = mgr . get_securitygroup ( securitygroup_id , mask = mask ) for binding in secgroup . get ( 'networkComponentBindings' , [ ] ) : ...
List interfaces associated with security groups .
234,717
def add ( env , securitygroup_id , network_component , server , interface ) : _validate_args ( network_component , server , interface ) mgr = SoftLayer . NetworkManager ( env . client ) component_id = _get_component_id ( env , network_component , server , interface ) ret = mgr . attach_securitygroup_component ( securit...
Attach an interface to a security group .
234,718
def default_select ( identifier , all_entry_points ) : if len ( all_entry_points ) == 0 : raise PluginMissingError ( identifier ) elif len ( all_entry_points ) == 1 : return all_entry_points [ 0 ] elif len ( all_entry_points ) > 1 : raise AmbiguousPluginError ( all_entry_points )
Raise an exception when we have ambiguous entry points .
234,719
def _load_class_entry_point ( cls , entry_point ) : class_ = entry_point . load ( ) setattr ( class_ , 'plugin_name' , entry_point . name ) return class_
Load entry_point and set the entry_point . name as the attribute plugin_name on the loaded object
234,720
def load_class ( cls , identifier , default = None , select = None ) : identifier = identifier . lower ( ) key = ( cls . entry_point , identifier ) if key not in PLUGIN_CACHE : if select is None : select = default_select all_entry_points = list ( pkg_resources . iter_entry_points ( cls . entry_point , name = identifier...
Load a single class specified by identifier .
234,721
def load_classes ( cls , fail_silently = True ) : all_classes = itertools . chain ( pkg_resources . iter_entry_points ( cls . entry_point ) , ( entry_point for identifier , entry_point in cls . extra_entry_points ) , ) for class_ in all_classes : try : yield ( class_ . name , cls . _load_class_entry_point ( class_ ) ) ...
Load all the classes for a plugin .
234,722
def register_temp_plugin ( cls , class_ , identifier = None , dist = 'xblock' ) : from mock import Mock if identifier is None : identifier = class_ . __name__ . lower ( ) entry_point = Mock ( dist = Mock ( key = dist ) , load = Mock ( return_value = class_ ) , ) entry_point . name = identifier def _decorator ( func ) :...
Decorate a function to run with a temporary plugin available .
234,723
def webob_to_django_response ( webob_response ) : from django . http import HttpResponse django_response = HttpResponse ( webob_response . app_iter , content_type = webob_response . content_type , status = webob_response . status_code , ) for name , value in webob_response . headerlist : django_response [ name ] = valu...
Returns a django response to the webob_response
234,724
def querydict_to_multidict ( query_dict , wrap = None ) : wrap = wrap or ( lambda val : val ) return MultiDict ( chain . from_iterable ( six . moves . zip ( repeat ( key ) , ( wrap ( v ) for v in vals ) ) for key , vals in six . iterlists ( query_dict ) ) )
Returns a new webob . MultiDict from a django . http . QueryDict .
234,725
def _meta_name ( self , name ) : name = name . upper ( ) . replace ( '-' , '_' ) if name not in self . UNPREFIXED_HEADERS : name = 'HTTP_' + name return name
Translate HTTP header names to the format used by Django request objects .
234,726
def _un_meta_name ( self , name ) : if name . startswith ( 'HTTP_' ) : name = name [ 5 : ] return name . replace ( '_' , '-' ) . title ( )
Reverse of _meta_name
234,727
def environ ( self ) : environ = dict ( self . _request . META ) environ [ 'PATH_INFO' ] = self . _request . path_info return environ
Add path_info to the request s META dictionary .
234,728
def _getfield ( self , block , name ) : block_field = getattr ( block . __class__ , name , None ) if block_field is not None and isinstance ( block_field , Field ) : return block_field raise KeyError ( name )
Return the field with the given name from block . If no field with name exists in any namespace raises a KeyError .
234,729
def get ( self , block , name ) : return self . _kvs . get ( self . _key ( block , name ) )
Retrieve the value for the field named name .
234,730
def set ( self , block , name , value ) : self . _kvs . set ( self . _key ( block , name ) , value )
Set the value of the field named name
234,731
def delete ( self , block , name ) : self . _kvs . delete ( self . _key ( block , name ) )
Reset the value of the field named name to the default
234,732
def has ( self , block , name ) : try : return self . _kvs . has ( self . _key ( block , name ) ) except KeyError : return False
Return whether or not the field named name has a non - default value
234,733
def set_many ( self , block , update_dict ) : updated_dict = { } for ( key , value ) in six . iteritems ( update_dict ) : updated_dict [ self . _key ( block , key ) ] = value self . _kvs . set_many ( updated_dict )
Update the underlying model with the correct values .
234,734
def create_aside ( self , definition_id , usage_id , aside_type ) : return ( self . ASIDE_DEFINITION_ID ( definition_id , aside_type ) , self . ASIDE_USAGE_ID ( usage_id , aside_type ) , )
Create the aside .
234,735
def create_usage ( self , def_id ) : usage_id = self . _next_id ( "u" ) self . _usages [ usage_id ] = def_id return usage_id
Make a usage storing its definition id .
234,736
def get_definition_id ( self , usage_id ) : try : return self . _usages [ usage_id ] except KeyError : raise NoSuchUsage ( repr ( usage_id ) )
Get a definition_id by its usage id .
234,737
def create_definition ( self , block_type , slug = None ) : prefix = "d" if slug : prefix += "_" + slug def_id = self . _next_id ( prefix ) self . _definitions [ def_id ] = block_type return def_id
Make a definition storing its block type .
234,738
def get_block_type ( self , def_id ) : try : return self . _definitions [ def_id ] except KeyError : try : return def_id . aside_type except AttributeError : raise NoSuchDefinition ( repr ( def_id ) )
Get a block_type by its definition id .
234,739
def field_data ( self , field_data ) : warnings . warn ( "Runtime.field_data is deprecated" , FieldDataDeprecationWarning , stacklevel = 2 ) self . _deprecated_per_instance_field_data = field_data
Set field_data .
234,740
def construct_xblock_from_class ( self , cls , scope_ids , field_data = None , * args , ** kwargs ) : return self . mixologist . mix ( cls ) ( runtime = self , field_data = field_data , scope_ids = scope_ids , * args , ** kwargs )
Construct a new xblock of type cls mixing in the mixins defined for this application .
234,741
def get_block ( self , usage_id , for_parent = None ) : def_id = self . id_reader . get_definition_id ( usage_id ) try : block_type = self . id_reader . get_block_type ( def_id ) except NoSuchDefinition : raise NoSuchUsage ( repr ( usage_id ) ) keys = ScopeIds ( self . user_id , block_type , def_id , usage_id ) block =...
Create an XBlock instance in this runtime .
234,742
def get_aside ( self , aside_usage_id ) : aside_type = self . id_reader . get_aside_type_from_usage ( aside_usage_id ) xblock_usage = self . id_reader . get_usage_id_from_aside ( aside_usage_id ) xblock_def = self . id_reader . get_definition_id ( xblock_usage ) aside_def_id , aside_usage_id = self . id_generator . cre...
Create an XBlockAside in this runtime .
234,743
def parse_xml_string ( self , xml , id_generator = None ) : if id_generator is not None : warnings . warn ( "Passing an id_generator directly is deprecated " "in favor of constructing the Runtime with the id_generator" , DeprecationWarning , stacklevel = 2 , ) id_generator = id_generator or self . id_generator if isins...
Parse a string of XML returning a usage id .
234,744
def parse_xml_file ( self , fileobj , id_generator = None ) : root = etree . parse ( fileobj ) . getroot ( ) usage_id = self . _usage_id_from_node ( root , None , id_generator ) return usage_id
Parse an open XML file returning a usage id .
234,745
def _usage_id_from_node ( self , node , parent_id , id_generator = None ) : if id_generator is not None : warnings . warn ( "Passing an id_generator directly is deprecated " "in favor of constructing the Runtime with the id_generator" , DeprecationWarning , stacklevel = 3 , ) id_generator = id_generator or self . id_ge...
Create a new usage id from an XML dom node .
234,746
def _aside_from_xml ( self , node , block_def_id , block_usage_id , id_generator ) : id_generator = id_generator or self . id_generator aside_type = node . tag aside_class = self . load_aside_type ( aside_type ) aside_def_id , aside_usage_id = id_generator . create_aside ( block_def_id , block_usage_id , aside_type ) k...
Create an aside from the xml and attach it to the given block
234,747
def add_node_as_child ( self , block , node , id_generator = None ) : usage_id = self . _usage_id_from_node ( node , block . scope_ids . usage_id , id_generator ) block . children . append ( usage_id )
Called by XBlock . parse_xml to treat a child node as a child block .
234,748
def export_to_xml ( self , block , xmlfile ) : root = etree . Element ( "unknown_root" , nsmap = XML_NAMESPACES ) tree = etree . ElementTree ( root ) block . add_xml_to_node ( root ) for aside in self . get_asides ( block ) : if aside . needs_serialization ( ) : aside_node = etree . Element ( "unknown_root" , nsmap = X...
Export the block to XML writing the XML to xmlfile .
234,749
def add_block_as_child_node ( self , block , node ) : child = etree . SubElement ( node , "unknown" ) block . add_xml_to_node ( child )
Export block as a child node of node .
234,750
def render ( self , block , view_name , context = None ) : old_view_name = self . _view_name self . _view_name = view_name try : view_fn = getattr ( block , view_name , None ) if view_fn is None : view_fn = getattr ( block , "fallback_view" , None ) if view_fn is None : raise NoSuchViewError ( block , view_name ) view_...
Render a block by invoking its view .
234,751
def render_child ( self , child , view_name = None , context = None ) : return child . render ( view_name or self . _view_name , context )
A shortcut to render a child block .
234,752
def render_children ( self , block , view_name = None , context = None ) : results = [ ] for child_id in block . children : child = self . get_block ( child_id ) result = self . render_child ( child , view_name , context ) results . append ( result ) return results
Render a block s children returning a list of results .
234,753
def wrap_xblock ( self , block , view , frag , context ) : if hasattr ( self , 'wrap_child' ) : log . warning ( "wrap_child is deprecated in favor of wrap_xblock and wrap_aside %s" , self . __class__ ) return self . wrap_child ( block , view , frag , context ) extra_data = { 'name' : block . name } if block . name else...
Creates a div which identifies the xblock and writes out the json_init_args into a script tag .
234,754
def wrap_aside ( self , block , aside , view , frag , context ) : return self . _wrap_ele ( aside , view , frag , { 'block_id' : block . scope_ids . usage_id , 'url_selector' : 'asideBaseUrl' , } )
Creates a div which identifies the aside points to the original block and writes out the json_init_args into a script tag .
234,755
def _wrap_ele ( self , block , view , frag , extra_data = None ) : wrapped = Fragment ( ) data = { 'usage' : block . scope_ids . usage_id , 'block-type' : block . scope_ids . block_type , } data . update ( extra_data ) if frag . js_init_fn : data [ 'init' ] = frag . js_init_fn data [ 'runtime-version' ] = frag . js_ini...
Does the guts of the wrapping the same way for both xblocks and asides . Their wrappers provide other info in extra_data which gets put into the dom data - attrs .
234,756
def get_asides ( self , block ) : aside_instances = [ self . get_aside_of_type ( block , aside_type ) for aside_type in self . applicable_aside_types ( block ) ] return [ aside_instance for aside_instance in aside_instances if aside_instance . should_apply_to_block ( block ) ]
Return instances for all of the asides that will decorate this block .
234,757
def get_aside_of_type ( self , block , aside_type ) : if self . id_generator is None : raise Exception ( "Runtimes must be supplied with an IdGenerator to load XBlockAsides." ) usage_id = block . scope_ids . usage_id aside_cls = self . load_aside_type ( aside_type ) definition_id = self . id_reader . get_definition_id ...
Return the aside of the given aside_type which might be decorating this block .
234,758
def render_asides ( self , block , view_name , frag , context ) : aside_frag_fns = [ ] for aside in self . get_asides ( block ) : aside_view_fn = aside . aside_view_declaration ( view_name ) if aside_view_fn is not None : aside_frag_fns . append ( ( aside , aside_view_fn ) ) if aside_frag_fns : return self . layout_asi...
Collect all of the asides add ons and format them into the frag . The frag already has the given block s rendering .
234,759
def layout_asides ( self , block , context , frag , view_name , aside_frag_fns ) : result = Fragment ( frag . content ) result . add_fragment_resources ( frag ) for aside , aside_fn in aside_frag_fns : aside_frag = self . wrap_aside ( block , aside , view_name , aside_fn ( block , context ) , context ) aside . save ( )...
Execute and layout the aside_frags wrt the block s frag . Runtimes should feel free to override this method to control execution place and style the asides appropriately for their application
234,760
def handle ( self , block , handler_name , request , suffix = '' ) : handler = getattr ( block , handler_name , None ) if handler and getattr ( handler , '_is_xblock_handler' , False ) : results = handler ( request , suffix ) else : fallback_handler = getattr ( block , "fallback_handler" , None ) if fallback_handler an...
Handles any calls to the specified handler_name .
234,761
def service ( self , block , service_name ) : declaration = block . service_declaration ( service_name ) if declaration is None : raise NoSuchServiceError ( "Service {!r} was not requested." . format ( service_name ) ) service = self . _services . get ( service_name ) if service is None and declaration == "need" : rais...
Return a service or None .
234,762
def querypath ( self , block , path ) : class BadPath ( Exception ) : pass results = self . query ( block ) ROOT , SEP , WORD , FINAL = six . moves . range ( 4 ) state = ROOT lexer = RegexLexer ( ( "dotdot" , r"\.\." ) , ( "dot" , r"\." ) , ( "slashslash" , r"//" ) , ( "slash" , r"/" ) , ( "atword" , r"@\w+" ) , ( "wor...
An XPath - like interface to query .
234,763
def _object_with_attr ( self , name ) : for obj in self . _objects : if hasattr ( obj , name ) : return obj raise AttributeError ( "No object has attribute {!r}" . format ( name ) )
Returns the first object that has the attribute name
234,764
def mix ( self , cls ) : if hasattr ( cls , 'unmixed_class' ) : base_class = cls . unmixed_class old_mixins = cls . __bases__ [ 1 : ] mixins = old_mixins + tuple ( mixin for mixin in self . _mixins if mixin not in old_mixins ) else : base_class = cls mixins = self . _mixins mixin_key = ( base_class , mixins ) if mixin_...
Returns a subclass of cls mixed with self . mixins .
234,765
def lex ( self , text ) : for match in self . regex . finditer ( text ) : name = match . lastgroup yield ( name , match . group ( name ) )
Iterator that tokenizes text and yields up tokens as they are found
234,766
def strftime ( self , dtime , format ) : format = self . STRFTIME_FORMATS . get ( format + "_FORMAT" , format ) if six . PY2 and isinstance ( format , six . text_type ) : format = format . encode ( "utf8" ) timestring = dtime . strftime ( format ) if six . PY2 : timestring = timestring . decode ( "utf8" ) return timest...
Locale - aware strftime with format short - cuts .
234,767
def ugettext ( self ) : if six . PY2 : return self . _translations . ugettext else : return self . _translations . gettext
Dispatch to the appropriate gettext method to handle text objects .
234,768
def ungettext ( self ) : if six . PY2 : return self . _translations . ungettext else : return self . _translations . ngettext
Dispatch to the appropriate ngettext method to handle text objects .
234,769
def load ( self , instance , xblock ) : if djpyfs : return djpyfs . get_filesystem ( scope_key ( instance , xblock ) ) else : raise NotImplementedError ( "djpyfs not available" )
Get the filesystem for the field specified in instance and the xblock in xblock It is locally scoped .
234,770
def emit_completion ( self , completion_percent ) : completion_mode = XBlockCompletionMode . get_mode ( self ) if not self . has_custom_completion or completion_mode != XBlockCompletionMode . COMPLETABLE : raise AttributeError ( "Using `emit_completion` requires `has_custom_completion == True` (was {}) " "and `completi...
Emits completion event through Completion API .
234,771
def has ( self , block , name ) : try : self . get ( block , name ) return True except KeyError : return False
Return whether or not the field named name has a non - default value for the XBlock block .
234,772
def set_many ( self , block , update_dict ) : for key , value in six . iteritems ( update_dict ) : self . set ( block , key , value )
Update many fields on an XBlock simultaneously .
234,773
def get_response ( self , ** kwargs ) : return Response ( json . dumps ( { "error" : self . message } ) , status_code = self . status_code , content_type = "application/json" , charset = "utf-8" , ** kwargs )
Returns a Response object containing this object s status code and a JSON object containing the key error with the value of this object s error message in the body . Keyword args are passed through to the Response .
234,774
def json_handler ( cls , func ) : @ cls . handler @ functools . wraps ( func ) def wrapper ( self , request , suffix = '' ) : if request . method != "POST" : return JsonHandlerError ( 405 , "Method must be POST" ) . get_response ( allow = [ "POST" ] ) try : request_json = json . loads ( request . body ) except ValueErr...
Wrap a handler to consume and produce JSON .
234,775
def handle ( self , handler_name , request , suffix = '' ) : return self . runtime . handle ( self , handler_name , request , suffix )
Handle request with this block s runtime .
234,776
def _combined_services ( cls ) : combined = { } for parent in reversed ( cls . mro ( ) ) : combined . update ( getattr ( parent , "_services_requested" , { } ) ) return combined
A dictionary that collects all _services_requested by all ancestors of this XBlock class .
234,777
def needs ( cls , * service_names ) : def _decorator ( cls_ ) : for service_name in service_names : cls_ . _services_requested [ service_name ] = "need" return cls_ return _decorator
A class decorator to indicate that an XBlock class needs particular services .
234,778
def wants ( cls , * service_names ) : def _decorator ( cls_ ) : for service_name in service_names : cls_ . _services_requested [ service_name ] = "want" return cls_ return _decorator
A class decorator to indicate that an XBlock class wants particular services .
234,779
def get_parent ( self ) : if not self . has_cached_parent : if self . parent is not None : self . _parent_block = self . runtime . get_block ( self . parent ) else : self . _parent_block = None self . _parent_block_id = self . parent return self . _parent_block
Return the parent block of this block or None if there isn t one .
234,780
def get_child ( self , usage_id ) : if usage_id in self . _child_cache : return self . _child_cache [ usage_id ] child_block = self . runtime . get_block ( usage_id , for_parent = self ) self . _child_cache [ usage_id ] = child_block return child_block
Return the child identified by usage_id .
234,781
def get_children ( self , usage_id_filter = None ) : if not self . has_children : return [ ] return [ self . get_child ( usage_id ) for usage_id in self . children if usage_id_filter is None or usage_id_filter ( usage_id ) ]
Return instantiated XBlocks for each of this blocks children .
234,782
def add_children_to_node ( self , node ) : if self . has_children : for child_id in self . children : child = self . runtime . get_block ( child_id ) self . runtime . add_block_as_child_node ( child , node )
Add children to etree . Element node .
234,783
def parse_xml ( cls , node , runtime , keys , id_generator ) : block = runtime . construct_xblock_from_class ( cls , keys ) for child in node : if child . tag is etree . Comment : continue qname = etree . QName ( child ) tag = qname . localname namespace = qname . namespace if namespace == XML_NAMESPACES [ "option" ] :...
Use node to construct a new block .
234,784
def add_xml_to_node ( self , node ) : node . tag = self . xml_element_name ( ) node . set ( 'xblock-family' , self . entry_point ) for field_name , field in self . fields . items ( ) : if field_name in ( 'children' , 'parent' , 'content' ) : continue if field . is_set_on ( self ) or field . force_export : self . _add_f...
For exporting set data on node from ourselves .
234,785
def _set_field_if_present ( cls , block , name , value , attrs ) : if name in block . fields : value = ( block . fields [ name ] ) . from_string ( value ) if "none" in attrs and attrs [ "none" ] == "true" : setattr ( block , name , None ) else : setattr ( block , name , value ) else : logging . warning ( "XBlock %s doe...
Sets the field block . name if block have such a field .
234,786
def _add_field ( self , node , field_name , field ) : value = field . to_string ( field . read_from ( self ) ) text_value = "" if value is None else value save_none_as_xml_attr = field . none_to_xml and value is None field_attrs = { "none" : "true" } if save_none_as_xml_attr else { } if save_none_as_xml_attr or field ....
Add xml representation of field to node .
234,787
def supports ( cls , * functionalities ) : def _decorator ( view ) : if not hasattr ( view , "_supports" ) : view . _supports = set ( ) for functionality in functionalities : view . _supports . add ( functionality ) return view return _decorator
A view decorator to indicate that an xBlock view has support for the given functionalities .
234,788
def rescore ( self , only_if_higher ) : _ = self . runtime . service ( self , 'i18n' ) . ugettext if not self . allows_rescore ( ) : raise TypeError ( _ ( 'Problem does not support rescoring: {}' ) . format ( self . location ) ) if not self . has_submitted_answer ( ) : raise ValueError ( _ ( 'Cannot rescore unanswered ...
Calculate a new raw score and save it to the block . If only_if_higher is True and the score didn t improve keep the existing score .
234,789
def _publish_grade ( self , score , only_if_higher = None ) : grade_dict = { 'value' : score . raw_earned , 'max_value' : score . raw_possible , 'only_if_higher' : only_if_higher , } self . runtime . publish ( self , 'grade' , grade_dict )
Publish a grade to the runtime .
234,790
def scope_key ( instance , xblock ) : scope_key_dict = { } scope_key_dict [ 'name' ] = instance . name if instance . scope . user == UserScope . NONE or instance . scope . user == UserScope . ALL : pass elif instance . scope . user == UserScope . ONE : scope_key_dict [ 'user' ] = six . text_type ( xblock . scope_ids . ...
Generate a unique key for a scope that can be used as a filename in a URL or in a KVS .
234,791
def default ( self ) : if self . MUTABLE : return copy . deepcopy ( self . _default ) else : return self . _default
Returns the static value that this defaults to .
234,792
def _set_cached_value ( self , xblock , value ) : if not hasattr ( xblock , '_field_data_cache' ) : xblock . _field_data_cache = { } xblock . _field_data_cache [ self . name ] = value
Store a value in the xblock s cache creating the cache if necessary .
234,793
def _del_cached_value ( self , xblock ) : if hasattr ( xblock , '_field_data_cache' ) and self . name in xblock . _field_data_cache : del xblock . _field_data_cache [ self . name ]
Remove a value from the xblock s cache if the cache exists .
234,794
def _mark_dirty ( self , xblock , value ) : if self not in xblock . _dirty_fields : xblock . _dirty_fields [ self ] = copy . deepcopy ( value )
Set this field to dirty on the xblock .
234,795
def _check_or_enforce_type ( self , value ) : if self . _enable_enforce_type : return self . enforce_type ( value ) try : new_value = self . enforce_type ( value ) except : message = "The value {!r} could not be enforced ({})" . format ( value , traceback . format_exc ( ) . splitlines ( ) [ - 1 ] ) warnings . warn ( me...
Depending on whether enforce_type is enabled call self . enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback
234,796
def _calculate_unique_id ( self , xblock ) : key = scope_key ( self , xblock ) return hashlib . sha1 ( key . encode ( 'utf-8' ) ) . hexdigest ( )
Provide a default value for fields with default = UNIQUE_ID .
234,797
def _get_default_value_to_cache ( self , xblock ) : try : return self . from_json ( xblock . _field_data . default ( xblock , self . name ) ) except KeyError : if self . _default is UNIQUE_ID : return self . _check_or_enforce_type ( self . _calculate_unique_id ( xblock ) ) else : return self . default
Perform special logic to provide a field s default value for caching .
234,798
def _warn_deprecated_outside_JSONField ( self ) : if not isinstance ( self , JSONField ) and not self . warned : warnings . warn ( "Deprecated. JSONifiable fields should derive from JSONField ({name})" . format ( name = self . name ) , DeprecationWarning , stacklevel = 3 ) self . warned = True
Certain methods will be moved to JSONField .
234,799
def to_string ( self , value ) : self . _warn_deprecated_outside_JSONField ( ) value = json . dumps ( self . to_json ( value ) , indent = 2 , sort_keys = True , separators = ( ',' , ': ' ) , ) return value
Return a JSON serialized string representation of the value .