repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.list_instances
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): """Retrieve a list of all virtual servers on the account. Example:: # Print out a list of hourly instances in the DAL05 data center. for vsi in mgr.list_instances(hourly=True, datacenter='dal05'): print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress'] # Using a custom object-mask. Will get ONLY what is specified object_mask = "mask[hostname,monitoringRobot[robotStatus]]" for vsi in mgr.list_instances(mask=object_mask,hourly=True): print vsi :param boolean hourly: include hourly instances :param boolean monthly: include monthly instances :param list tags: filter based on list of tags :param integer cpus: filter based on number of CPUS :param integer memory: filter based on amount of memory :param string hostname: filter based on hostname :param string domain: filter based on domain :param string local_disk: filter based on local_disk :param string datacenter: filter based on datacenter :param integer nic_speed: filter based on network speed (in MBPS) :param string public_ip: filter based on public ip address :param string private_ip: filter based on private ip address :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) :returns: Returns a list of dictionaries representing the matching virtual servers """ if 'mask' not in kwargs: items = [ 'id', 'globalIdentifier', 'hostname', 'domain', 'fullyQualifiedDomainName', 'primaryBackendIpAddress', 'primaryIpAddress', 'lastKnownPowerState.name', 'powerState', 'maxCpu', 'maxMemory', 'datacenter', 'activeTransaction.transactionStatus[friendlyName,name]', 'status', ] kwargs['mask'] = "mask[%s]" % ','.join(items) call = 'getVirtualGuests' if not all([hourly, monthly]): if hourly: call = 'getHourlyVirtualGuests' elif monthly: call = 'getMonthlyVirtualGuests' _filter = utils.NestedDict(kwargs.get('filter') or {}) if tags: _filter['virtualGuests']['tagReferences']['tag']['name'] = { 'operation': 'in', 'options': [{'name': 'data', 'value': tags}], } if cpus: _filter['virtualGuests']['maxCpu'] = utils.query_filter(cpus) if memory: _filter['virtualGuests']['maxMemory'] = utils.query_filter(memory) if hostname: _filter['virtualGuests']['hostname'] = utils.query_filter(hostname) if domain: _filter['virtualGuests']['domain'] = utils.query_filter(domain) if local_disk is not None: _filter['virtualGuests']['localDiskFlag'] = ( utils.query_filter(bool(local_disk))) if datacenter: _filter['virtualGuests']['datacenter']['name'] = ( utils.query_filter(datacenter)) if nic_speed: _filter['virtualGuests']['networkComponents']['maxSpeed'] = ( utils.query_filter(nic_speed)) if public_ip: _filter['virtualGuests']['primaryIpAddress'] = ( utils.query_filter(public_ip)) if private_ip: _filter['virtualGuests']['primaryBackendIpAddress'] = ( utils.query_filter(private_ip)) kwargs['filter'] = _filter.to_dict() kwargs['iter'] = True return self.client.call('Account', call, **kwargs)
python
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): """Retrieve a list of all virtual servers on the account. Example:: # Print out a list of hourly instances in the DAL05 data center. for vsi in mgr.list_instances(hourly=True, datacenter='dal05'): print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress'] # Using a custom object-mask. Will get ONLY what is specified object_mask = "mask[hostname,monitoringRobot[robotStatus]]" for vsi in mgr.list_instances(mask=object_mask,hourly=True): print vsi :param boolean hourly: include hourly instances :param boolean monthly: include monthly instances :param list tags: filter based on list of tags :param integer cpus: filter based on number of CPUS :param integer memory: filter based on amount of memory :param string hostname: filter based on hostname :param string domain: filter based on domain :param string local_disk: filter based on local_disk :param string datacenter: filter based on datacenter :param integer nic_speed: filter based on network speed (in MBPS) :param string public_ip: filter based on public ip address :param string private_ip: filter based on private ip address :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) :returns: Returns a list of dictionaries representing the matching virtual servers """ if 'mask' not in kwargs: items = [ 'id', 'globalIdentifier', 'hostname', 'domain', 'fullyQualifiedDomainName', 'primaryBackendIpAddress', 'primaryIpAddress', 'lastKnownPowerState.name', 'powerState', 'maxCpu', 'maxMemory', 'datacenter', 'activeTransaction.transactionStatus[friendlyName,name]', 'status', ] kwargs['mask'] = "mask[%s]" % ','.join(items) call = 'getVirtualGuests' if not all([hourly, monthly]): if hourly: call = 'getHourlyVirtualGuests' elif monthly: call = 'getMonthlyVirtualGuests' _filter = utils.NestedDict(kwargs.get('filter') or {}) if tags: _filter['virtualGuests']['tagReferences']['tag']['name'] = { 'operation': 'in', 'options': [{'name': 'data', 'value': tags}], } if cpus: _filter['virtualGuests']['maxCpu'] = utils.query_filter(cpus) if memory: _filter['virtualGuests']['maxMemory'] = utils.query_filter(memory) if hostname: _filter['virtualGuests']['hostname'] = utils.query_filter(hostname) if domain: _filter['virtualGuests']['domain'] = utils.query_filter(domain) if local_disk is not None: _filter['virtualGuests']['localDiskFlag'] = ( utils.query_filter(bool(local_disk))) if datacenter: _filter['virtualGuests']['datacenter']['name'] = ( utils.query_filter(datacenter)) if nic_speed: _filter['virtualGuests']['networkComponents']['maxSpeed'] = ( utils.query_filter(nic_speed)) if public_ip: _filter['virtualGuests']['primaryIpAddress'] = ( utils.query_filter(public_ip)) if private_ip: _filter['virtualGuests']['primaryBackendIpAddress'] = ( utils.query_filter(private_ip)) kwargs['filter'] = _filter.to_dict() kwargs['iter'] = True return self.client.call('Account', call, **kwargs)
[ "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'", ",", "'hostname'", ",", "'domain'", ",", "'fullyQualifiedDomainName'", ",", "'primaryBackendIpAddress'", ",", "'primaryIpAddress'", ",", "'lastKnownPowerState.name'", ",", "'powerState'", ",", "'maxCpu'", ",", "'maxMemory'", ",", "'datacenter'", ",", "'activeTransaction.transactionStatus[friendlyName,name]'", ",", "'status'", ",", "]", "kwargs", "[", "'mask'", "]", "=", "\"mask[%s]\"", "%", "','", ".", "join", "(", "items", ")", "call", "=", "'getVirtualGuests'", "if", "not", "all", "(", "[", "hourly", ",", "monthly", "]", ")", ":", "if", "hourly", ":", "call", "=", "'getHourlyVirtualGuests'", "elif", "monthly", ":", "call", "=", "'getMonthlyVirtualGuests'", "_filter", "=", "utils", ".", "NestedDict", "(", "kwargs", ".", "get", "(", "'filter'", ")", "or", "{", "}", ")", "if", "tags", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'tagReferences'", "]", "[", "'tag'", "]", "[", "'name'", "]", "=", "{", "'operation'", ":", "'in'", ",", "'options'", ":", "[", "{", "'name'", ":", "'data'", ",", "'value'", ":", "tags", "}", "]", ",", "}", "if", "cpus", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'maxCpu'", "]", "=", "utils", ".", "query_filter", "(", "cpus", ")", "if", "memory", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'maxMemory'", "]", "=", "utils", ".", "query_filter", "(", "memory", ")", "if", "hostname", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'hostname'", "]", "=", "utils", ".", "query_filter", "(", "hostname", ")", "if", "domain", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'domain'", "]", "=", "utils", ".", "query_filter", "(", "domain", ")", "if", "local_disk", "is", "not", "None", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'localDiskFlag'", "]", "=", "(", "utils", ".", "query_filter", "(", "bool", "(", "local_disk", ")", ")", ")", "if", "datacenter", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'datacenter'", "]", "[", "'name'", "]", "=", "(", "utils", ".", "query_filter", "(", "datacenter", ")", ")", "if", "nic_speed", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'networkComponents'", "]", "[", "'maxSpeed'", "]", "=", "(", "utils", ".", "query_filter", "(", "nic_speed", ")", ")", "if", "public_ip", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'primaryIpAddress'", "]", "=", "(", "utils", ".", "query_filter", "(", "public_ip", ")", ")", "if", "private_ip", ":", "_filter", "[", "'virtualGuests'", "]", "[", "'primaryBackendIpAddress'", "]", "=", "(", "utils", ".", "query_filter", "(", "private_ip", ")", ")", "kwargs", "[", "'filter'", "]", "=", "_filter", ".", "to_dict", "(", ")", "kwargs", "[", "'iter'", "]", "=", "True", "return", "self", ".", "client", ".", "call", "(", "'Account'", ",", "call", ",", "*", "*", "kwargs", ")" ]
Retrieve a list of all virtual servers on the account. Example:: # Print out a list of hourly instances in the DAL05 data center. for vsi in mgr.list_instances(hourly=True, datacenter='dal05'): print vsi['fullyQualifiedDomainName'], vsi['primaryIpAddress'] # Using a custom object-mask. Will get ONLY what is specified object_mask = "mask[hostname,monitoringRobot[robotStatus]]" for vsi in mgr.list_instances(mask=object_mask,hourly=True): print vsi :param boolean hourly: include hourly instances :param boolean monthly: include monthly instances :param list tags: filter based on list of tags :param integer cpus: filter based on number of CPUS :param integer memory: filter based on amount of memory :param string hostname: filter based on hostname :param string domain: filter based on domain :param string local_disk: filter based on local_disk :param string datacenter: filter based on datacenter :param integer nic_speed: filter based on network speed (in MBPS) :param string public_ip: filter based on public ip address :param string private_ip: filter based on private ip address :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) :returns: Returns a list of dictionaries representing the matching virtual servers
[ "Retrieve", "a", "list", "of", "all", "virtual", "servers", "on", "the", "account", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L61-L162
train
234,700
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.get_instance
def get_instance(self, instance_id, **kwargs): """Get details about a virtual server instance. :param integer instance_id: the instance ID :returns: A dictionary containing a large amount of information about the specified instance. Example:: # Print out instance ID 12345. vsi = mgr.get_instance(12345) print vsi # Print out only FQDN and primaryIP for instance 12345 object_mask = "mask[fullyQualifiedDomainName,primaryIpAddress]" vsi = mgr.get_instance(12345, mask=mask) print vsi """ if 'mask' not in kwargs: kwargs['mask'] = ( 'id,' 'globalIdentifier,' 'fullyQualifiedDomainName,' 'hostname,' 'domain,' 'createDate,' 'modifyDate,' 'provisionDate,' 'notes,' 'dedicatedAccountHostOnlyFlag,' 'privateNetworkOnlyFlag,' 'primaryBackendIpAddress,' 'primaryIpAddress,' '''networkComponents[id, status, speed, maxSpeed, name, macAddress, primaryIpAddress, port, primarySubnet[addressSpace], securityGroupBindings[ securityGroup[id, name]]],''' 'lastKnownPowerState.name,' 'powerState,' 'status,' 'maxCpu,' 'maxMemory,' 'datacenter,' 'activeTransaction[id, transactionStatus[friendlyName,name]],' 'lastTransaction[transactionStatus],' 'lastOperatingSystemReload.id,' 'blockDevices,' 'blockDeviceTemplateGroup[id, name, globalIdentifier],' 'postInstallScriptUri,' '''operatingSystem[passwords[username,password], softwareLicense.softwareDescription[ manufacturer,name,version, referenceCode]],''' '''softwareComponents[ passwords[username,password,notes], softwareLicense[softwareDescription[ manufacturer,name,version, referenceCode]]],''' 'hourlyBillingFlag,' 'userData,' '''billingItem[id,nextInvoiceTotalRecurringAmount, package[id,keyName], children[categoryCode,nextInvoiceTotalRecurringAmount], orderItem[id, order.userRecord[username], preset.keyName]],''' 'tagReferences[id,tag[name,id]],' 'networkVlans[id,vlanNumber,networkSpace],' 'dedicatedHost.id,' 'placementGroupId' ) return self.guest.getObject(id=instance_id, **kwargs)
python
def get_instance(self, instance_id, **kwargs): """Get details about a virtual server instance. :param integer instance_id: the instance ID :returns: A dictionary containing a large amount of information about the specified instance. Example:: # Print out instance ID 12345. vsi = mgr.get_instance(12345) print vsi # Print out only FQDN and primaryIP for instance 12345 object_mask = "mask[fullyQualifiedDomainName,primaryIpAddress]" vsi = mgr.get_instance(12345, mask=mask) print vsi """ if 'mask' not in kwargs: kwargs['mask'] = ( 'id,' 'globalIdentifier,' 'fullyQualifiedDomainName,' 'hostname,' 'domain,' 'createDate,' 'modifyDate,' 'provisionDate,' 'notes,' 'dedicatedAccountHostOnlyFlag,' 'privateNetworkOnlyFlag,' 'primaryBackendIpAddress,' 'primaryIpAddress,' '''networkComponents[id, status, speed, maxSpeed, name, macAddress, primaryIpAddress, port, primarySubnet[addressSpace], securityGroupBindings[ securityGroup[id, name]]],''' 'lastKnownPowerState.name,' 'powerState,' 'status,' 'maxCpu,' 'maxMemory,' 'datacenter,' 'activeTransaction[id, transactionStatus[friendlyName,name]],' 'lastTransaction[transactionStatus],' 'lastOperatingSystemReload.id,' 'blockDevices,' 'blockDeviceTemplateGroup[id, name, globalIdentifier],' 'postInstallScriptUri,' '''operatingSystem[passwords[username,password], softwareLicense.softwareDescription[ manufacturer,name,version, referenceCode]],''' '''softwareComponents[ passwords[username,password,notes], softwareLicense[softwareDescription[ manufacturer,name,version, referenceCode]]],''' 'hourlyBillingFlag,' 'userData,' '''billingItem[id,nextInvoiceTotalRecurringAmount, package[id,keyName], children[categoryCode,nextInvoiceTotalRecurringAmount], orderItem[id, order.userRecord[username], preset.keyName]],''' 'tagReferences[id,tag[name,id]],' 'networkVlans[id,vlanNumber,networkSpace],' 'dedicatedHost.id,' 'placementGroupId' ) return self.guest.getObject(id=instance_id, **kwargs)
[ "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,'", "'primaryIpAddress,'", "'''networkComponents[id, status, speed, maxSpeed, name,\n macAddress, primaryIpAddress, port,\n primarySubnet[addressSpace],\n securityGroupBindings[\n securityGroup[id, name]]],'''", "'lastKnownPowerState.name,'", "'powerState,'", "'status,'", "'maxCpu,'", "'maxMemory,'", "'datacenter,'", "'activeTransaction[id, transactionStatus[friendlyName,name]],'", "'lastTransaction[transactionStatus],'", "'lastOperatingSystemReload.id,'", "'blockDevices,'", "'blockDeviceTemplateGroup[id, name, globalIdentifier],'", "'postInstallScriptUri,'", "'''operatingSystem[passwords[username,password],\n softwareLicense.softwareDescription[\n manufacturer,name,version,\n referenceCode]],'''", "'''softwareComponents[\n passwords[username,password,notes],\n softwareLicense[softwareDescription[\n manufacturer,name,version,\n referenceCode]]],'''", "'hourlyBillingFlag,'", "'userData,'", "'''billingItem[id,nextInvoiceTotalRecurringAmount,\n package[id,keyName],\n children[categoryCode,nextInvoiceTotalRecurringAmount],\n orderItem[id,\n order.userRecord[username],\n preset.keyName]],'''", "'tagReferences[id,tag[name,id]],'", "'networkVlans[id,vlanNumber,networkSpace],'", "'dedicatedHost.id,'", "'placementGroupId'", ")", "return", "self", ".", "guest", ".", "getObject", "(", "id", "=", "instance_id", ",", "*", "*", "kwargs", ")" ]
Get details about a virtual server instance. :param integer instance_id: the instance ID :returns: A dictionary containing a large amount of information about the specified instance. Example:: # Print out instance ID 12345. vsi = mgr.get_instance(12345) print vsi # Print out only FQDN and primaryIP for instance 12345 object_mask = "mask[fullyQualifiedDomainName,primaryIpAddress]" vsi = mgr.get_instance(12345, mask=mask) print vsi
[ "Get", "details", "about", "a", "virtual", "server", "instance", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L165-L240
train
234,701
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.reload_instance
def reload_instance(self, instance_id, post_uri=None, ssh_keys=None, image_id=None): """Perform an OS reload of an instance. :param integer instance_id: the instance ID to reload :param string post_url: The URI of the post-install script to run after reload :param list ssh_keys: The SSH keys to add to the root user :param int image_id: The GUID of the image to load onto the server .. warning:: This will reformat the primary drive. Post-provision script MUST be HTTPS for it to be executed. Example:: # Reload instance ID 12345 then run a custom post-provision script. # Post-provision script MUST be HTTPS for it to be executed. post_uri = 'https://somehost.com/bootstrap.sh' vsi = mgr.reload_instance(12345, post_uri=post_url) """ 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.client.call('Virtual_Guest', 'reloadOperatingSystem', 'FORCE', config, id=instance_id)
python
def reload_instance(self, instance_id, post_uri=None, ssh_keys=None, image_id=None): """Perform an OS reload of an instance. :param integer instance_id: the instance ID to reload :param string post_url: The URI of the post-install script to run after reload :param list ssh_keys: The SSH keys to add to the root user :param int image_id: The GUID of the image to load onto the server .. warning:: This will reformat the primary drive. Post-provision script MUST be HTTPS for it to be executed. Example:: # Reload instance ID 12345 then run a custom post-provision script. # Post-provision script MUST be HTTPS for it to be executed. post_uri = 'https://somehost.com/bootstrap.sh' vsi = mgr.reload_instance(12345, post_uri=post_url) """ 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.client.call('Virtual_Guest', 'reloadOperatingSystem', 'FORCE', config, id=instance_id)
[ "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", ".", "client", ".", "call", "(", "'Virtual_Guest'", ",", "'reloadOperatingSystem'", ",", "'FORCE'", ",", "config", ",", "id", "=", "instance_id", ")" ]
Perform an OS reload of an instance. :param integer instance_id: the instance ID to reload :param string post_url: The URI of the post-install script to run after reload :param list ssh_keys: The SSH keys to add to the root user :param int image_id: The GUID of the image to load onto the server .. warning:: This will reformat the primary drive. Post-provision script MUST be HTTPS for it to be executed. Example:: # Reload instance ID 12345 then run a custom post-provision script. # Post-provision script MUST be HTTPS for it to be executed. post_uri = 'https://somehost.com/bootstrap.sh' vsi = mgr.reload_instance(12345, post_uri=post_url)
[ "Perform", "an", "OS", "reload", "of", "an", "instance", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L269-L305
train
234,702
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.wait_for_transaction
def wait_for_transaction(self, instance_id, limit, delay=10): """Waits on a VS transaction for the specified amount of time. This is really just a wrapper for wait_for_ready(pending=True). Provided for backwards compatibility. :param int instance_id: The instance ID with the pending transaction :param int limit: The maximum amount of time to wait. :param int delay: The number of seconds to sleep before checks. Defaults to 10. """ return self.wait_for_ready(instance_id, limit, delay=delay, pending=True)
python
def wait_for_transaction(self, instance_id, limit, delay=10): """Waits on a VS transaction for the specified amount of time. This is really just a wrapper for wait_for_ready(pending=True). Provided for backwards compatibility. :param int instance_id: The instance ID with the pending transaction :param int limit: The maximum amount of time to wait. :param int delay: The number of seconds to sleep before checks. Defaults to 10. """ return self.wait_for_ready(instance_id, limit, delay=delay, pending=True)
[ "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. This is really just a wrapper for wait_for_ready(pending=True). Provided for backwards compatibility. :param int instance_id: The instance ID with the pending transaction :param int limit: The maximum amount of time to wait. :param int delay: The number of seconds to sleep before checks. Defaults to 10.
[ "Waits", "on", "a", "VS", "transaction", "for", "the", "specified", "amount", "of", "time", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L442-L453
train
234,703
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.verify_create_instance
def verify_create_instance(self, **kwargs): """Verifies an instance creation command. Without actually placing an order. See :func:`create_instance` for a list of available options. Example:: new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } vsi = mgr.verify_create_instance(**new_vsi) # vsi will be a SoftLayer_Container_Product_Order_Virtual_Guest # if your order is correct. Otherwise you will get an exception print vsi """ kwargs.pop('tags', None) create_options = self._generate_create_dict(**kwargs) return self.guest.generateOrderTemplate(create_options)
python
def verify_create_instance(self, **kwargs): """Verifies an instance creation command. Without actually placing an order. See :func:`create_instance` for a list of available options. Example:: new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } vsi = mgr.verify_create_instance(**new_vsi) # vsi will be a SoftLayer_Container_Product_Order_Virtual_Guest # if your order is correct. Otherwise you will get an exception print vsi """ kwargs.pop('tags', None) create_options = self._generate_create_dict(**kwargs) return self.guest.generateOrderTemplate(create_options)
[ "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. Without actually placing an order. See :func:`create_instance` for a list of available options. Example:: new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } vsi = mgr.verify_create_instance(**new_vsi) # vsi will be a SoftLayer_Container_Product_Order_Virtual_Guest # if your order is correct. Otherwise you will get an exception print vsi
[ "Verifies", "an", "instance", "creation", "command", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L493-L524
train
234,704
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.create_instance
def create_instance(self, **kwargs): """Creates a new virtual server instance. .. warning:: This will add charges to your account Example:: new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } vsi = mgr.create_instance(**new_vsi) # vsi will have the newly created vsi details if done properly. print vsi :param int cpus: The number of virtual CPUs to include in the instance. :param int memory: The amount of RAM to order. :param bool hourly: Flag to indicate if this server should be billed hourly (default) or monthly. :param string hostname: The hostname to use for the new server. :param string domain: The domain to use for the new server. :param bool local_disk: Flag to indicate if this should be a local disk (default) or a SAN disk. :param string datacenter: The short name of the data center in which the VS should reside. :param string os_code: The operating system to use. Cannot be specified if image_id is specified. :param int image_id: The GUID of the image to load onto the server. Cannot be specified if os_code is specified. :param bool dedicated: Flag to indicate if this should be housed on adedicated or shared host (default). This will incur a fee on your account. :param int public_vlan: The ID of the public VLAN on which you want this VS placed. :param list public_security_groups: The list of security group IDs to apply to the public interface :param list private_security_groups: The list of security group IDs to apply to the private interface :param int private_vlan: The ID of the private VLAN on which you want this VS placed. :param list disks: A list of disk capacities for this server. :param string post_uri: The URI of the post-install script to run after reload :param bool private: If true, the VS will be provisioned only with access to the private network. Defaults to false :param list ssh_keys: The SSH keys to add to the root user :param int nic_speed: The port speed to set :param string tags: tags to set on the VS as a comma separated list :param string flavor: The key name of the public virtual server flavor being ordered. :param int host_id: The host id of a dedicated host to provision a dedicated host virtual server on. """ 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
python
def create_instance(self, **kwargs): """Creates a new virtual server instance. .. warning:: This will add charges to your account Example:: new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } vsi = mgr.create_instance(**new_vsi) # vsi will have the newly created vsi details if done properly. print vsi :param int cpus: The number of virtual CPUs to include in the instance. :param int memory: The amount of RAM to order. :param bool hourly: Flag to indicate if this server should be billed hourly (default) or monthly. :param string hostname: The hostname to use for the new server. :param string domain: The domain to use for the new server. :param bool local_disk: Flag to indicate if this should be a local disk (default) or a SAN disk. :param string datacenter: The short name of the data center in which the VS should reside. :param string os_code: The operating system to use. Cannot be specified if image_id is specified. :param int image_id: The GUID of the image to load onto the server. Cannot be specified if os_code is specified. :param bool dedicated: Flag to indicate if this should be housed on adedicated or shared host (default). This will incur a fee on your account. :param int public_vlan: The ID of the public VLAN on which you want this VS placed. :param list public_security_groups: The list of security group IDs to apply to the public interface :param list private_security_groups: The list of security group IDs to apply to the private interface :param int private_vlan: The ID of the private VLAN on which you want this VS placed. :param list disks: A list of disk capacities for this server. :param string post_uri: The URI of the post-install script to run after reload :param bool private: If true, the VS will be provisioned only with access to the private network. Defaults to false :param list ssh_keys: The SSH keys to add to the root user :param int nic_speed: The port speed to set :param string tags: tags to set on the VS as a comma separated list :param string flavor: The key name of the public virtual server flavor being ordered. :param int host_id: The host id of a dedicated host to provision a dedicated host virtual server on. """ 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
[ "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. .. warning:: This will add charges to your account Example:: new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } vsi = mgr.create_instance(**new_vsi) # vsi will have the newly created vsi details if done properly. print vsi :param int cpus: The number of virtual CPUs to include in the instance. :param int memory: The amount of RAM to order. :param bool hourly: Flag to indicate if this server should be billed hourly (default) or monthly. :param string hostname: The hostname to use for the new server. :param string domain: The domain to use for the new server. :param bool local_disk: Flag to indicate if this should be a local disk (default) or a SAN disk. :param string datacenter: The short name of the data center in which the VS should reside. :param string os_code: The operating system to use. Cannot be specified if image_id is specified. :param int image_id: The GUID of the image to load onto the server. Cannot be specified if os_code is specified. :param bool dedicated: Flag to indicate if this should be housed on adedicated or shared host (default). This will incur a fee on your account. :param int public_vlan: The ID of the public VLAN on which you want this VS placed. :param list public_security_groups: The list of security group IDs to apply to the public interface :param list private_security_groups: The list of security group IDs to apply to the private interface :param int private_vlan: The ID of the private VLAN on which you want this VS placed. :param list disks: A list of disk capacities for this server. :param string post_uri: The URI of the post-install script to run after reload :param bool private: If true, the VS will be provisioned only with access to the private network. Defaults to false :param list ssh_keys: The SSH keys to add to the root user :param int nic_speed: The port speed to set :param string tags: tags to set on the VS as a comma separated list :param string flavor: The key name of the public virtual server flavor being ordered. :param int host_id: The host id of a dedicated host to provision a dedicated host virtual server on.
[ "Creates", "a", "new", "virtual", "server", "instance", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L526-L584
train
234,705
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.set_tags
def set_tags(self, tags, guest_id): """Sets tags on a guest with a retry decorator Just calls guest.setTags, but if it fails from an APIError will retry """ self.guest.setTags(tags, id=guest_id)
python
def set_tags(self, tags, guest_id): """Sets tags on a guest with a retry decorator Just calls guest.setTags, but if it fails from an APIError will retry """ self.guest.setTags(tags, id=guest_id)
[ "def", "set_tags", "(", "self", ",", "tags", ",", "guest_id", ")", ":", "self", ".", "guest", ".", "setTags", "(", "tags", ",", "id", "=", "guest_id", ")" ]
Sets tags on a guest with a retry decorator Just calls guest.setTags, but if it fails from an APIError will retry
[ "Sets", "tags", "on", "a", "guest", "with", "a", "retry", "decorator" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L587-L592
train
234,706
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.create_instances
def create_instances(self, config_list): """Creates multiple virtual server instances. This takes a list of dictionaries using the same arguments as create_instance(). .. warning:: This will add charges to your account Example:: # Define the instance we want to create. new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } # using .copy() so we can make changes to individual nodes instances = [new_vsi.copy(), new_vsi.copy(), new_vsi.copy()] # give each its own hostname, not required. instances[0]['hostname'] = "multi-test01" instances[1]['hostname'] = "multi-test02" instances[2]['hostname'] = "multi-test03" vsi = mgr.create_instances(config_list=instances) #vsi will be a dictionary of all the new virtual servers print vsi """ 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=instance['id']) return resp
python
def create_instances(self, config_list): """Creates multiple virtual server instances. This takes a list of dictionaries using the same arguments as create_instance(). .. warning:: This will add charges to your account Example:: # Define the instance we want to create. new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } # using .copy() so we can make changes to individual nodes instances = [new_vsi.copy(), new_vsi.copy(), new_vsi.copy()] # give each its own hostname, not required. instances[0]['hostname'] = "multi-test01" instances[1]['hostname'] = "multi-test02" instances[2]['hostname'] = "multi-test03" vsi = mgr.create_instances(config_list=instances) #vsi will be a dictionary of all the new virtual servers print vsi """ 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=instance['id']) return resp
[ "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", "=", "instance", "[", "'id'", "]", ")", "return", "resp" ]
Creates multiple virtual server instances. This takes a list of dictionaries using the same arguments as create_instance(). .. warning:: This will add charges to your account Example:: # Define the instance we want to create. new_vsi = { 'domain': u'test01.labs.sftlyr.ws', 'hostname': u'minion05', 'datacenter': u'hkg02', 'flavor': 'BL1_1X2X100' 'dedicated': False, 'private': False, 'os_code' : u'UBUNTU_LATEST', 'hourly': True, 'ssh_keys': [1234], 'disks': ('100','25'), 'local_disk': True, 'tags': 'test, pleaseCancel', 'public_security_groups': [12, 15] } # using .copy() so we can make changes to individual nodes instances = [new_vsi.copy(), new_vsi.copy(), new_vsi.copy()] # give each its own hostname, not required. instances[0]['hostname'] = "multi-test01" instances[1]['hostname'] = "multi-test02" instances[2]['hostname'] = "multi-test03" vsi = mgr.create_instances(config_list=instances) #vsi will be a dictionary of all the new virtual servers print vsi
[ "Creates", "multiple", "virtual", "server", "instances", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L594-L644
train
234,707
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.change_port_speed
def change_port_speed(self, instance_id, public, speed): """Allows you to change the port speed of a virtual server's NICs. Example:: #change the Public interface to 10Mbps on instance 12345 result = mgr.change_port_speed(instance_id=12345, public=True, speed=10) # result will be True or an Exception :param int instance_id: The ID of the VS :param bool public: Flag to indicate which interface to change. True (default) means the public interface. False indicates the private interface. :param int speed: The port speed to set. .. warning:: A port speed of 0 will disable the interface. """ 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)
python
def change_port_speed(self, instance_id, public, speed): """Allows you to change the port speed of a virtual server's NICs. Example:: #change the Public interface to 10Mbps on instance 12345 result = mgr.change_port_speed(instance_id=12345, public=True, speed=10) # result will be True or an Exception :param int instance_id: The ID of the VS :param bool public: Flag to indicate which interface to change. True (default) means the public interface. False indicates the private interface. :param int speed: The port speed to set. .. warning:: A port speed of 0 will disable the interface. """ 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)
[ "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. Example:: #change the Public interface to 10Mbps on instance 12345 result = mgr.change_port_speed(instance_id=12345, public=True, speed=10) # result will be True or an Exception :param int instance_id: The ID of the VS :param bool public: Flag to indicate which interface to change. True (default) means the public interface. False indicates the private interface. :param int speed: The port speed to set. .. warning:: A port speed of 0 will disable the interface.
[ "Allows", "you", "to", "change", "the", "port", "speed", "of", "a", "virtual", "server", "s", "NICs", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L646-L670
train
234,708
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager._get_ids_from_hostname
def _get_ids_from_hostname(self, hostname): """List VS ids which match the given hostname.""" results = self.list_instances(hostname=hostname, mask="id") return [result['id'] for result in results]
python
def _get_ids_from_hostname(self, hostname): """List VS ids which match the given hostname.""" results = self.list_instances(hostname=hostname, mask="id") return [result['id'] for result in results]
[ "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.
[ "List", "VS", "ids", "which", "match", "the", "given", "hostname", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L672-L675
train
234,709
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager._get_ids_from_ip
def _get_ids_from_ip(self, ip_address): # pylint: disable=inconsistent-return-statements """List VS ids which match the given ip address.""" try: # Does it look like an ip address? socket.inet_aton(ip_address) except socket.error: return [] # Find the VS via ip address. First try public ip, then private 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="id") if results: return [result['id'] for result in results]
python
def _get_ids_from_ip(self, ip_address): # pylint: disable=inconsistent-return-statements """List VS ids which match the given ip address.""" try: # Does it look like an ip address? socket.inet_aton(ip_address) except socket.error: return [] # Find the VS via ip address. First try public ip, then private 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="id") if results: return [result['id'] for result in results]
[ "def", "_get_ids_from_ip", "(", "self", ",", "ip_address", ")", ":", "# pylint: disable=inconsistent-return-statements", "try", ":", "# Does it look like an ip address?", "socket", ".", "inet_aton", "(", "ip_address", ")", "except", "socket", ".", "error", ":", "return", "[", "]", "# Find the VS via ip address. First try public ip, then private", "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", "=", "\"id\"", ")", "if", "results", ":", "return", "[", "result", "[", "'id'", "]", "for", "result", "in", "results", "]" ]
List VS ids which match the given ip address.
[ "List", "VS", "ids", "which", "match", "the", "given", "ip", "address", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L677-L692
train
234,710
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager.upgrade
def upgrade(self, instance_id, cpus=None, memory=None, nic_speed=None, public=True, preset=None): """Upgrades a VS instance. Example:: # Upgrade instance 12345 to 4 CPUs and 4 GB of memory import SoftLayer client = SoftLayer.create_client_from_env() mgr = SoftLayer.VSManager(client) mgr.upgrade(12345, cpus=4, memory=4) :param int instance_id: Instance id of the VS to be upgraded :param int cpus: The number of virtual CPUs to upgrade to of a VS instance. :param string preset: preset assigned to the vsi :param int memory: RAM of the VS to be upgraded to. :param int nic_speed: The port speed to set :param bool public: CPU will be in Private/Public Node. :returns: bool """ 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 memory if you are using flavors") data['cpus'] = cpus if memory is not None and preset is not None: raise ValueError("Do not use memory, private or cpu if you are using flavors") data['memory'] = memory maintenance_window = datetime.datetime.now(utils.UTC()) order = { 'complexType': 'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade', 'properties': [{ 'name': 'MAINTENANCE_WINDOW', 'value': maintenance_window.strftime("%Y-%m-%d %H:%M:%S%z") }], 'virtualGuests': [{'id': int(instance_id)}], } for option, value in data.items(): if not value: continue price_id = self._get_price_id_for_upgrade_option(upgrade_prices, option, value, public) if not price_id: # Every option provided is expected to have a price raise exceptions.SoftLayerError( "Unable to find %s option with value %s" % (option, value)) prices.append({'id': price_id}) order['prices'] = prices if preset is not None: vs_object = self.get_instance(instance_id)['billingItem']['package'] order['presetId'] = self.ordering_manager.get_preset_by_key(vs_object['keyName'], preset)['id'] if prices or preset: self.client['Product_Order'].placeOrder(order) return True return False
python
def upgrade(self, instance_id, cpus=None, memory=None, nic_speed=None, public=True, preset=None): """Upgrades a VS instance. Example:: # Upgrade instance 12345 to 4 CPUs and 4 GB of memory import SoftLayer client = SoftLayer.create_client_from_env() mgr = SoftLayer.VSManager(client) mgr.upgrade(12345, cpus=4, memory=4) :param int instance_id: Instance id of the VS to be upgraded :param int cpus: The number of virtual CPUs to upgrade to of a VS instance. :param string preset: preset assigned to the vsi :param int memory: RAM of the VS to be upgraded to. :param int nic_speed: The port speed to set :param bool public: CPU will be in Private/Public Node. :returns: bool """ 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 memory if you are using flavors") data['cpus'] = cpus if memory is not None and preset is not None: raise ValueError("Do not use memory, private or cpu if you are using flavors") data['memory'] = memory maintenance_window = datetime.datetime.now(utils.UTC()) order = { 'complexType': 'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade', 'properties': [{ 'name': 'MAINTENANCE_WINDOW', 'value': maintenance_window.strftime("%Y-%m-%d %H:%M:%S%z") }], 'virtualGuests': [{'id': int(instance_id)}], } for option, value in data.items(): if not value: continue price_id = self._get_price_id_for_upgrade_option(upgrade_prices, option, value, public) if not price_id: # Every option provided is expected to have a price raise exceptions.SoftLayerError( "Unable to find %s option with value %s" % (option, value)) prices.append({'id': price_id}) order['prices'] = prices if preset is not None: vs_object = self.get_instance(instance_id)['billingItem']['package'] order['presetId'] = self.ordering_manager.get_preset_by_key(vs_object['keyName'], preset)['id'] if prices or preset: self.client['Product_Order'].placeOrder(order) return True return False
[ "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 memory if you are using flavors\"", ")", "data", "[", "'cpus'", "]", "=", "cpus", "if", "memory", "is", "not", "None", "and", "preset", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Do not use memory, private or cpu if you are using flavors\"", ")", "data", "[", "'memory'", "]", "=", "memory", "maintenance_window", "=", "datetime", ".", "datetime", ".", "now", "(", "utils", ".", "UTC", "(", ")", ")", "order", "=", "{", "'complexType'", ":", "'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade'", ",", "'properties'", ":", "[", "{", "'name'", ":", "'MAINTENANCE_WINDOW'", ",", "'value'", ":", "maintenance_window", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S%z\"", ")", "}", "]", ",", "'virtualGuests'", ":", "[", "{", "'id'", ":", "int", "(", "instance_id", ")", "}", "]", ",", "}", "for", "option", ",", "value", "in", "data", ".", "items", "(", ")", ":", "if", "not", "value", ":", "continue", "price_id", "=", "self", ".", "_get_price_id_for_upgrade_option", "(", "upgrade_prices", ",", "option", ",", "value", ",", "public", ")", "if", "not", "price_id", ":", "# Every option provided is expected to have a price", "raise", "exceptions", ".", "SoftLayerError", "(", "\"Unable to find %s option with value %s\"", "%", "(", "option", ",", "value", ")", ")", "prices", ".", "append", "(", "{", "'id'", ":", "price_id", "}", ")", "order", "[", "'prices'", "]", "=", "prices", "if", "preset", "is", "not", "None", ":", "vs_object", "=", "self", ".", "get_instance", "(", "instance_id", ")", "[", "'billingItem'", "]", "[", "'package'", "]", "order", "[", "'presetId'", "]", "=", "self", ".", "ordering_manager", ".", "get_preset_by_key", "(", "vs_object", "[", "'keyName'", "]", ",", "preset", ")", "[", "'id'", "]", "if", "prices", "or", "preset", ":", "self", ".", "client", "[", "'Product_Order'", "]", ".", "placeOrder", "(", "order", ")", "return", "True", "return", "False" ]
Upgrades a VS instance. Example:: # Upgrade instance 12345 to 4 CPUs and 4 GB of memory import SoftLayer client = SoftLayer.create_client_from_env() mgr = SoftLayer.VSManager(client) mgr.upgrade(12345, cpus=4, memory=4) :param int instance_id: Instance id of the VS to be upgraded :param int cpus: The number of virtual CPUs to upgrade to of a VS instance. :param string preset: preset assigned to the vsi :param int memory: RAM of the VS to be upgraded to. :param int nic_speed: The port speed to set :param bool public: CPU will be in Private/Public Node. :returns: bool
[ "Upgrades", "a", "VS", "instance", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L801-L867
train
234,711
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager._get_package_items
def _get_package_items(self): """Following Method gets all the item ids related to VS. Deprecated in favor of _get_upgrade_prices() """ 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.ordering_manager.get_package_by_key(package_keyname) package_service = self.client['Product_Package'] return package_service.getItems(id=package['id'], mask=mask)
python
def _get_package_items(self): """Following Method gets all the item ids related to VS. Deprecated in favor of _get_upgrade_prices() """ 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.ordering_manager.get_package_by_key(package_keyname) package_service = self.client['Product_Package'] return package_service.getItems(id=package['id'], mask=mask)
[ "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", ".", "ordering_manager", ".", "get_package_by_key", "(", "package_keyname", ")", "package_service", "=", "self", ".", "client", "[", "'Product_Package'", "]", "return", "package_service", ".", "getItems", "(", "id", "=", "package", "[", "'id'", "]", ",", "mask", "=", "mask", ")" ]
Following Method gets all the item ids related to VS. Deprecated in favor of _get_upgrade_prices()
[ "Following", "Method", "gets", "all", "the", "item", "ids", "related", "to", "VS", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L927-L946
train
234,712
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager._get_upgrade_prices
def _get_upgrade_prices(self, instance_id, include_downgrade_options=True): """Following Method gets all the price ids related to upgrading a VS. :param int instance_id: Instance id of the VS to be upgraded :returns: list """ 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_id, mask=mask)
python
def _get_upgrade_prices(self, instance_id, include_downgrade_options=True): """Following Method gets all the price ids related to upgrading a VS. :param int instance_id: Instance id of the VS to be upgraded :returns: list """ 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_id, mask=mask)
[ "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_id", ",", "mask", "=", "mask", ")" ]
Following Method gets all the price ids related to upgrading a VS. :param int instance_id: Instance id of the VS to be upgraded :returns: list
[ "Following", "Method", "gets", "all", "the", "price", "ids", "related", "to", "upgrading", "a", "VS", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L948-L962
train
234,713
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager._get_price_id_for_upgrade_option
def _get_price_id_for_upgrade_option(self, upgrade_prices, option, value, public=True): """Find the price id for the option and value to upgrade. This :param list upgrade_prices: Contains all the prices related to a VS upgrade :param string option: Describes type of parameter to be upgraded :param int value: The value of the parameter to be upgraded :param bool public: CPU will be in Private/Public Node. """ 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.get('item') is None: continue product = price.get('item') is_private = (product.get('units') == 'PRIVATE_CORE' or product.get('units') == 'DEDICATED_CORE') for category in price.get('categories'): if not (category.get('categoryCode') == category_code and str(product.get('capacity')) == str(value)): continue if option == 'cpus': # Public upgrade and public guest_core price if public and not is_private: return price.get('id') # Private upgrade and private guest_core price elif not public and is_private: return price.get('id') elif option == 'nic_speed': if 'Public' in product.get('description'): return price.get('id') else: return price.get('id')
python
def _get_price_id_for_upgrade_option(self, upgrade_prices, option, value, public=True): """Find the price id for the option and value to upgrade. This :param list upgrade_prices: Contains all the prices related to a VS upgrade :param string option: Describes type of parameter to be upgraded :param int value: The value of the parameter to be upgraded :param bool public: CPU will be in Private/Public Node. """ 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.get('item') is None: continue product = price.get('item') is_private = (product.get('units') == 'PRIVATE_CORE' or product.get('units') == 'DEDICATED_CORE') for category in price.get('categories'): if not (category.get('categoryCode') == category_code and str(product.get('capacity')) == str(value)): continue if option == 'cpus': # Public upgrade and public guest_core price if public and not is_private: return price.get('id') # Private upgrade and private guest_core price elif not public and is_private: return price.get('id') elif option == 'nic_speed': if 'Public' in product.get('description'): return price.get('id') else: return price.get('id')
[ "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", ".", "get", "(", "'item'", ")", "is", "None", ":", "continue", "product", "=", "price", ".", "get", "(", "'item'", ")", "is_private", "=", "(", "product", ".", "get", "(", "'units'", ")", "==", "'PRIVATE_CORE'", "or", "product", ".", "get", "(", "'units'", ")", "==", "'DEDICATED_CORE'", ")", "for", "category", "in", "price", ".", "get", "(", "'categories'", ")", ":", "if", "not", "(", "category", ".", "get", "(", "'categoryCode'", ")", "==", "category_code", "and", "str", "(", "product", ".", "get", "(", "'capacity'", ")", ")", "==", "str", "(", "value", ")", ")", ":", "continue", "if", "option", "==", "'cpus'", ":", "# Public upgrade and public guest_core price", "if", "public", "and", "not", "is_private", ":", "return", "price", ".", "get", "(", "'id'", ")", "# Private upgrade and private guest_core price", "elif", "not", "public", "and", "is_private", ":", "return", "price", ".", "get", "(", "'id'", ")", "elif", "option", "==", "'nic_speed'", ":", "if", "'Public'", "in", "product", ".", "get", "(", "'description'", ")", ":", "return", "price", ".", "get", "(", "'id'", ")", "else", ":", "return", "price", ".", "get", "(", "'id'", ")" ]
Find the price id for the option and value to upgrade. This :param list upgrade_prices: Contains all the prices related to a VS upgrade :param string option: Describes type of parameter to be upgraded :param int value: The value of the parameter to be upgraded :param bool public: CPU will be in Private/Public Node.
[ "Find", "the", "price", "id", "for", "the", "option", "and", "value", "to", "upgrade", ".", "This" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L965-L1003
train
234,714
softlayer/softlayer-python
SoftLayer/managers/vs.py
VSManager._get_price_id_for_upgrade
def _get_price_id_for_upgrade(self, package_items, option, value, public=True): """Find the price id for the option and value to upgrade. Deprecated in favor of _get_price_id_for_upgrade_option() :param list package_items: Contains all the items related to an VS :param string option: Describes type of parameter to be upgraded :param int value: The value of the parameter to be upgraded :param bool public: CPU will be in Private/Public Node. """ 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 item in package_items: is_private = (item.get('units') == 'PRIVATE_CORE') for price in item['prices']: if 'locationGroupId' in price and price['locationGroupId']: # Skip location based prices continue if 'categories' not in price: continue categories = price['categories'] for category in categories: if not (category['categoryCode'] == category_code and str(item['capacity']) == str(value)): continue if option == 'cpus': if public and not is_private: return price['id'] elif not public and is_private: return price['id'] elif option == 'nic_speed': if 'Public' in item['description']: return price['id'] else: return price['id']
python
def _get_price_id_for_upgrade(self, package_items, option, value, public=True): """Find the price id for the option and value to upgrade. Deprecated in favor of _get_price_id_for_upgrade_option() :param list package_items: Contains all the items related to an VS :param string option: Describes type of parameter to be upgraded :param int value: The value of the parameter to be upgraded :param bool public: CPU will be in Private/Public Node. """ 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 item in package_items: is_private = (item.get('units') == 'PRIVATE_CORE') for price in item['prices']: if 'locationGroupId' in price and price['locationGroupId']: # Skip location based prices continue if 'categories' not in price: continue categories = price['categories'] for category in categories: if not (category['categoryCode'] == category_code and str(item['capacity']) == str(value)): continue if option == 'cpus': if public and not is_private: return price['id'] elif not public and is_private: return price['id'] elif option == 'nic_speed': if 'Public' in item['description']: return price['id'] else: return price['id']
[ "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", "item", "in", "package_items", ":", "is_private", "=", "(", "item", ".", "get", "(", "'units'", ")", "==", "'PRIVATE_CORE'", ")", "for", "price", "in", "item", "[", "'prices'", "]", ":", "if", "'locationGroupId'", "in", "price", "and", "price", "[", "'locationGroupId'", "]", ":", "# Skip location based prices", "continue", "if", "'categories'", "not", "in", "price", ":", "continue", "categories", "=", "price", "[", "'categories'", "]", "for", "category", "in", "categories", ":", "if", "not", "(", "category", "[", "'categoryCode'", "]", "==", "category_code", "and", "str", "(", "item", "[", "'capacity'", "]", ")", "==", "str", "(", "value", ")", ")", ":", "continue", "if", "option", "==", "'cpus'", ":", "if", "public", "and", "not", "is_private", ":", "return", "price", "[", "'id'", "]", "elif", "not", "public", "and", "is_private", ":", "return", "price", "[", "'id'", "]", "elif", "option", "==", "'nic_speed'", ":", "if", "'Public'", "in", "item", "[", "'description'", "]", ":", "return", "price", "[", "'id'", "]", "else", ":", "return", "price", "[", "'id'", "]" ]
Find the price id for the option and value to upgrade. Deprecated in favor of _get_price_id_for_upgrade_option() :param list package_items: Contains all the items related to an VS :param string option: Describes type of parameter to be upgraded :param int value: The value of the parameter to be upgraded :param bool public: CPU will be in Private/Public Node.
[ "Find", "the", "price", "id", "for", "the", "option", "and", "value", "to", "upgrade", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L1006-L1048
train
234,715
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/interface.py
interface_list
def interface_list(env, securitygroup_id, sortby): """List interfaces associated with security groups.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby mask = ( '''networkComponentBindings[ networkComponentId, networkComponent[ id, port, guest[ id, hostname, primaryBackendIpAddress, primaryIpAddress ] ] ]''' ) secgroup = mgr.get_securitygroup(securitygroup_id, mask=mask) for binding in secgroup.get('networkComponentBindings', []): interface_id = binding['networkComponentId'] try: interface = binding['networkComponent'] vsi = interface['guest'] vsi_id = vsi['id'] hostname = vsi['hostname'] priv_pub = 'PRIVATE' if interface['port'] == 0 else 'PUBLIC' ip_address = (vsi['primaryBackendIpAddress'] if interface['port'] == 0 else vsi['primaryIpAddress']) except KeyError: vsi_id = "N/A" hostname = "Not enough permission to view" priv_pub = "N/A" ip_address = "N/A" table.add_row([ interface_id, vsi_id, hostname, priv_pub, ip_address ]) env.fout(table)
python
def interface_list(env, securitygroup_id, sortby): """List interfaces associated with security groups.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby mask = ( '''networkComponentBindings[ networkComponentId, networkComponent[ id, port, guest[ id, hostname, primaryBackendIpAddress, primaryIpAddress ] ] ]''' ) secgroup = mgr.get_securitygroup(securitygroup_id, mask=mask) for binding in secgroup.get('networkComponentBindings', []): interface_id = binding['networkComponentId'] try: interface = binding['networkComponent'] vsi = interface['guest'] vsi_id = vsi['id'] hostname = vsi['hostname'] priv_pub = 'PRIVATE' if interface['port'] == 0 else 'PUBLIC' ip_address = (vsi['primaryBackendIpAddress'] if interface['port'] == 0 else vsi['primaryIpAddress']) except KeyError: vsi_id = "N/A" hostname = "Not enough permission to view" priv_pub = "N/A" ip_address = "N/A" table.add_row([ interface_id, vsi_id, hostname, priv_pub, ip_address ]) env.fout(table)
[ "def", "interface_list", "(", "env", ",", "securitygroup_id", ",", "sortby", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "mask", "=", "(", "'''networkComponentBindings[\n networkComponentId,\n networkComponent[\n id,\n port,\n guest[\n id,\n hostname,\n primaryBackendIpAddress,\n primaryIpAddress\n ]\n ]\n ]'''", ")", "secgroup", "=", "mgr", ".", "get_securitygroup", "(", "securitygroup_id", ",", "mask", "=", "mask", ")", "for", "binding", "in", "secgroup", ".", "get", "(", "'networkComponentBindings'", ",", "[", "]", ")", ":", "interface_id", "=", "binding", "[", "'networkComponentId'", "]", "try", ":", "interface", "=", "binding", "[", "'networkComponent'", "]", "vsi", "=", "interface", "[", "'guest'", "]", "vsi_id", "=", "vsi", "[", "'id'", "]", "hostname", "=", "vsi", "[", "'hostname'", "]", "priv_pub", "=", "'PRIVATE'", "if", "interface", "[", "'port'", "]", "==", "0", "else", "'PUBLIC'", "ip_address", "=", "(", "vsi", "[", "'primaryBackendIpAddress'", "]", "if", "interface", "[", "'port'", "]", "==", "0", "else", "vsi", "[", "'primaryIpAddress'", "]", ")", "except", "KeyError", ":", "vsi_id", "=", "\"N/A\"", "hostname", "=", "\"Not enough permission to view\"", "priv_pub", "=", "\"N/A\"", "ip_address", "=", "\"N/A\"", "table", ".", "add_row", "(", "[", "interface_id", ",", "vsi_id", ",", "hostname", ",", "priv_pub", ",", "ip_address", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List interfaces associated with security groups.
[ "List", "interfaces", "associated", "with", "security", "groups", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/interface.py#L26-L75
train
234,716
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/interface.py
add
def add(env, securitygroup_id, network_component, server, interface): """Attach an interface to a security group.""" _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(securitygroup_id, component_id) if not ret: raise exceptions.CLIAbort("Could not attach network component") table = formatting.Table(REQUEST_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
python
def add(env, securitygroup_id, network_component, server, interface): """Attach an interface to a security group.""" _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(securitygroup_id, component_id) if not ret: raise exceptions.CLIAbort("Could not attach network component") table = formatting.Table(REQUEST_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
[ "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", "(", "securitygroup_id", ",", "component_id", ")", "if", "not", "ret", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Could not attach network component\"", ")", "table", "=", "formatting", ".", "Table", "(", "REQUEST_COLUMNS", ")", "table", ".", "add_row", "(", "[", "ret", "[", "'requestId'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Attach an interface to a security group.
[ "Attach", "an", "interface", "to", "a", "security", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/interface.py#L88-L103
train
234,717
edx/XBlock
xblock/plugin.py
default_select
def default_select(identifier, all_entry_points): # pylint: disable=inconsistent-return-statements """ Raise an exception when we have ambiguous 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)
python
def default_select(identifier, all_entry_points): # pylint: disable=inconsistent-return-statements """ Raise an exception when we have ambiguous 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)
[ "def", "default_select", "(", "identifier", ",", "all_entry_points", ")", ":", "# pylint: disable=inconsistent-return-statements", "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.
[ "Raise", "an", "exception", "when", "we", "have", "ambiguous", "entry", "points", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/plugin.py#L34-L46
train
234,718
edx/XBlock
xblock/plugin.py
Plugin._load_class_entry_point
def _load_class_entry_point(cls, entry_point): """ Load `entry_point`, and set the `entry_point.name` as the attribute `plugin_name` on the loaded object """ class_ = entry_point.load() setattr(class_, 'plugin_name', entry_point.name) return class_
python
def _load_class_entry_point(cls, entry_point): """ Load `entry_point`, and set the `entry_point.name` as the attribute `plugin_name` on the loaded object """ class_ = entry_point.load() setattr(class_, 'plugin_name', entry_point.name) return class_
[ "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
[ "Load", "entry_point", "and", "set", "the", "entry_point", ".", "name", "as", "the", "attribute", "plugin_name", "on", "the", "loaded", "object" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/plugin.py#L70-L77
train
234,719
edx/XBlock
xblock/plugin.py
Plugin.load_class
def load_class(cls, identifier, default=None, select=None): """Load a single class specified by identifier. If `identifier` specifies more than a single class, and `select` is not None, then call `select` on the list of entry_points. Otherwise, choose the first one and log a warning. If `default` is provided, return it if no entry_point matching `identifier` is found. Otherwise, will raise a PluginMissingError If `select` is provided, it should be a callable of the form:: def select(identifier, all_entry_points): # ... return an_entry_point The `all_entry_points` argument will be a list of all entry_points matching `identifier` that were found, and `select` should return one of those entry_points to be loaded. `select` should raise `PluginMissingError` if no plugin is found, or `AmbiguousPluginError` if too many plugins are found """ 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)) for extra_identifier, extra_entry_point in cls.extra_entry_points: if identifier == extra_identifier: all_entry_points.append(extra_entry_point) try: selected_entry_point = select(identifier, all_entry_points) except PluginMissingError: if default is not None: return default raise PLUGIN_CACHE[key] = cls._load_class_entry_point(selected_entry_point) return PLUGIN_CACHE[key]
python
def load_class(cls, identifier, default=None, select=None): """Load a single class specified by identifier. If `identifier` specifies more than a single class, and `select` is not None, then call `select` on the list of entry_points. Otherwise, choose the first one and log a warning. If `default` is provided, return it if no entry_point matching `identifier` is found. Otherwise, will raise a PluginMissingError If `select` is provided, it should be a callable of the form:: def select(identifier, all_entry_points): # ... return an_entry_point The `all_entry_points` argument will be a list of all entry_points matching `identifier` that were found, and `select` should return one of those entry_points to be loaded. `select` should raise `PluginMissingError` if no plugin is found, or `AmbiguousPluginError` if too many plugins are found """ 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)) for extra_identifier, extra_entry_point in cls.extra_entry_points: if identifier == extra_identifier: all_entry_points.append(extra_entry_point) try: selected_entry_point = select(identifier, all_entry_points) except PluginMissingError: if default is not None: return default raise PLUGIN_CACHE[key] = cls._load_class_entry_point(selected_entry_point) return PLUGIN_CACHE[key]
[ "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", ")", ")", "for", "extra_identifier", ",", "extra_entry_point", "in", "cls", ".", "extra_entry_points", ":", "if", "identifier", "==", "extra_identifier", ":", "all_entry_points", ".", "append", "(", "extra_entry_point", ")", "try", ":", "selected_entry_point", "=", "select", "(", "identifier", ",", "all_entry_points", ")", "except", "PluginMissingError", ":", "if", "default", "is", "not", "None", ":", "return", "default", "raise", "PLUGIN_CACHE", "[", "key", "]", "=", "cls", ".", "_load_class_entry_point", "(", "selected_entry_point", ")", "return", "PLUGIN_CACHE", "[", "key", "]" ]
Load a single class specified by identifier. If `identifier` specifies more than a single class, and `select` is not None, then call `select` on the list of entry_points. Otherwise, choose the first one and log a warning. If `default` is provided, return it if no entry_point matching `identifier` is found. Otherwise, will raise a PluginMissingError If `select` is provided, it should be a callable of the form:: def select(identifier, all_entry_points): # ... return an_entry_point The `all_entry_points` argument will be a list of all entry_points matching `identifier` that were found, and `select` should return one of those entry_points to be loaded. `select` should raise `PluginMissingError` if no plugin is found, or `AmbiguousPluginError` if too many plugins are found
[ "Load", "a", "single", "class", "specified", "by", "identifier", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/plugin.py#L80-L122
train
234,720
edx/XBlock
xblock/plugin.py
Plugin.load_classes
def load_classes(cls, fail_silently=True): """Load all the classes for a plugin. Produces a sequence containing the identifiers and their corresponding classes for all of the available instances of this plugin. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is disagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag. """ 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_)) except Exception: # pylint: disable=broad-except if fail_silently: log.warning('Unable to load %s %r', cls.__name__, class_.name, exc_info=True) else: raise
python
def load_classes(cls, fail_silently=True): """Load all the classes for a plugin. Produces a sequence containing the identifiers and their corresponding classes for all of the available instances of this plugin. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is disagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag. """ 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_)) except Exception: # pylint: disable=broad-except if fail_silently: log.warning('Unable to load %s %r', cls.__name__, class_.name, exc_info=True) else: raise
[ "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_", ")", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "if", "fail_silently", ":", "log", ".", "warning", "(", "'Unable to load %s %r'", ",", "cls", ".", "__name__", ",", "class_", ".", "name", ",", "exc_info", "=", "True", ")", "else", ":", "raise" ]
Load all the classes for a plugin. Produces a sequence containing the identifiers and their corresponding classes for all of the available instances of this plugin. fail_silently causes the code to simply log warnings if a plugin cannot import. The goal is to be able to use part of libraries from an XBlock (and thus have it installed), even if the overall XBlock cannot be used (e.g. depends on Django in a non-Django application). There is disagreement about whether this is a good idea, or whether we should see failures early (e.g. on startup or first page load), and in what contexts. Hence, the flag.
[ "Load", "all", "the", "classes", "for", "a", "plugin", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/plugin.py#L125-L151
train
234,721
edx/XBlock
xblock/plugin.py
Plugin.register_temp_plugin
def register_temp_plugin(cls, class_, identifier=None, dist='xblock'): """Decorate a function to run with a temporary plugin available. Use it like this in tests:: @register_temp_plugin(MyXBlockClass): def test_the_thing(): # Here I can load MyXBlockClass by name. """ 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): # pylint: disable=C0111 @functools.wraps(func) def _inner(*args, **kwargs): # pylint: disable=C0111 global PLUGIN_CACHE # pylint: disable=global-statement old = list(cls.extra_entry_points) old_cache = PLUGIN_CACHE cls.extra_entry_points.append((identifier, entry_point)) PLUGIN_CACHE = {} try: return func(*args, **kwargs) finally: cls.extra_entry_points = old PLUGIN_CACHE = old_cache return _inner return _decorator
python
def register_temp_plugin(cls, class_, identifier=None, dist='xblock'): """Decorate a function to run with a temporary plugin available. Use it like this in tests:: @register_temp_plugin(MyXBlockClass): def test_the_thing(): # Here I can load MyXBlockClass by name. """ 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): # pylint: disable=C0111 @functools.wraps(func) def _inner(*args, **kwargs): # pylint: disable=C0111 global PLUGIN_CACHE # pylint: disable=global-statement old = list(cls.extra_entry_points) old_cache = PLUGIN_CACHE cls.extra_entry_points.append((identifier, entry_point)) PLUGIN_CACHE = {} try: return func(*args, **kwargs) finally: cls.extra_entry_points = old PLUGIN_CACHE = old_cache return _inner return _decorator
[ "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", ")", ":", "# pylint: disable=C0111", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=C0111", "global", "PLUGIN_CACHE", "# pylint: disable=global-statement", "old", "=", "list", "(", "cls", ".", "extra_entry_points", ")", "old_cache", "=", "PLUGIN_CACHE", "cls", ".", "extra_entry_points", ".", "append", "(", "(", "identifier", ",", "entry_point", ")", ")", "PLUGIN_CACHE", "=", "{", "}", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "cls", ".", "extra_entry_points", "=", "old", "PLUGIN_CACHE", "=", "old_cache", "return", "_inner", "return", "_decorator" ]
Decorate a function to run with a temporary plugin available. Use it like this in tests:: @register_temp_plugin(MyXBlockClass): def test_the_thing(): # Here I can load MyXBlockClass by name.
[ "Decorate", "a", "function", "to", "run", "with", "a", "temporary", "plugin", "available", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/plugin.py#L154-L192
train
234,722
edx/XBlock
xblock/django/request.py
webob_to_django_response
def webob_to_django_response(webob_response): """Returns a django response to the `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] = value return django_response
python
def webob_to_django_response(webob_response): """Returns a django response to the `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] = value return django_response
[ "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", "]", "=", "value", "return", "django_response" ]
Returns a django response to the `webob_response`
[ "Returns", "a", "django", "response", "to", "the", "webob_response" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/django/request.py#L14-L24
train
234,723
edx/XBlock
xblock/django/request.py
querydict_to_multidict
def querydict_to_multidict(query_dict, wrap=None): """ Returns a new `webob.MultiDict` from a `django.http.QueryDict`. If `wrap` is provided, it's used to wrap the values. """ 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) ))
python
def querydict_to_multidict(query_dict, wrap=None): """ Returns a new `webob.MultiDict` from a `django.http.QueryDict`. If `wrap` is provided, it's used to wrap the values. """ 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) ))
[ "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`. If `wrap` is provided, it's used to wrap the values.
[ "Returns", "a", "new", "webob", ".", "MultiDict", "from", "a", "django", ".", "http", ".", "QueryDict", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/django/request.py#L76-L87
train
234,724
edx/XBlock
xblock/django/request.py
HeaderDict._meta_name
def _meta_name(self, name): """ Translate HTTP header names to the format used by Django request objects. See https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpRequest.META """ name = name.upper().replace('-', '_') if name not in self.UNPREFIXED_HEADERS: name = 'HTTP_' + name return name
python
def _meta_name(self, name): """ Translate HTTP header names to the format used by Django request objects. See https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpRequest.META """ name = name.upper().replace('-', '_') if name not in self.UNPREFIXED_HEADERS: name = 'HTTP_' + name return name
[ "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. See https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpRequest.META
[ "Translate", "HTTP", "header", "names", "to", "the", "format", "used", "by", "Django", "request", "objects", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/django/request.py#L39-L48
train
234,725
edx/XBlock
xblock/django/request.py
HeaderDict._un_meta_name
def _un_meta_name(self, name): """ Reverse of _meta_name """ if name.startswith('HTTP_'): name = name[5:] return name.replace('_', '-').title()
python
def _un_meta_name(self, name): """ Reverse of _meta_name """ if name.startswith('HTTP_'): name = name[5:] return name.replace('_', '-').title()
[ "def", "_un_meta_name", "(", "self", ",", "name", ")", ":", "if", "name", ".", "startswith", "(", "'HTTP_'", ")", ":", "name", "=", "name", "[", "5", ":", "]", "return", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", ".", "title", "(", ")" ]
Reverse of _meta_name
[ "Reverse", "of", "_meta_name" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/django/request.py#L50-L56
train
234,726
edx/XBlock
xblock/django/request.py
DjangoWebobRequest.environ
def environ(self): """ Add path_info to the request's META dictionary. """ environ = dict(self._request.META) environ['PATH_INFO'] = self._request.path_info return environ
python
def environ(self): """ Add path_info to the request's META dictionary. """ environ = dict(self._request.META) environ['PATH_INFO'] = self._request.path_info return environ
[ "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.
[ "Add", "path_info", "to", "the", "request", "s", "META", "dictionary", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/django/request.py#L119-L127
train
234,727
edx/XBlock
xblock/runtime.py
KvsFieldData._getfield
def _getfield(self, block, name): """ Return the field with the given `name` from `block`. If no field with `name` exists in any namespace, raises a KeyError. :param block: xblock to retrieve the field from :type block: :class:`~xblock.core.XBlock` :param name: name of the field to retrieve :type name: str :raises KeyError: when no field with `name` exists in any namespace """ # First, get the field from the class, if defined block_field = getattr(block.__class__, name, None) if block_field is not None and isinstance(block_field, Field): return block_field # Not in the class, so name # really doesn't name a field raise KeyError(name)
python
def _getfield(self, block, name): """ Return the field with the given `name` from `block`. If no field with `name` exists in any namespace, raises a KeyError. :param block: xblock to retrieve the field from :type block: :class:`~xblock.core.XBlock` :param name: name of the field to retrieve :type name: str :raises KeyError: when no field with `name` exists in any namespace """ # First, get the field from the class, if defined block_field = getattr(block.__class__, name, None) if block_field is not None and isinstance(block_field, Field): return block_field # Not in the class, so name # really doesn't name a field raise KeyError(name)
[ "def", "_getfield", "(", "self", ",", "block", ",", "name", ")", ":", "# First, get the field from the class, if defined", "block_field", "=", "getattr", "(", "block", ".", "__class__", ",", "name", ",", "None", ")", "if", "block_field", "is", "not", "None", "and", "isinstance", "(", "block_field", ",", "Field", ")", ":", "return", "block_field", "# Not in the class, so name", "# really doesn't name a 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. :param block: xblock to retrieve the field from :type block: :class:`~xblock.core.XBlock` :param name: name of the field to retrieve :type name: str :raises KeyError: when no field with `name` exists in any namespace
[ "Return", "the", "field", "with", "the", "given", "name", "from", "block", ".", "If", "no", "field", "with", "name", "exists", "in", "any", "namespace", "raises", "a", "KeyError", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L130-L149
train
234,728
edx/XBlock
xblock/runtime.py
KvsFieldData.get
def get(self, block, name): """ Retrieve the value for the field named `name`. If a value is provided for `default`, then it will be returned if no value is set """ return self._kvs.get(self._key(block, name))
python
def get(self, block, name): """ Retrieve the value for the field named `name`. If a value is provided for `default`, then it will be returned if no value is set """ return self._kvs.get(self._key(block, name))
[ "def", "get", "(", "self", ",", "block", ",", "name", ")", ":", "return", "self", ".", "_kvs", ".", "get", "(", "self", ".", "_key", "(", "block", ",", "name", ")", ")" ]
Retrieve the value for the field named `name`. If a value is provided for `default`, then it will be returned if no value is set
[ "Retrieve", "the", "value", "for", "the", "field", "named", "name", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L193-L200
train
234,729
edx/XBlock
xblock/runtime.py
KvsFieldData.set
def set(self, block, name, value): """ Set the value of the field named `name` """ self._kvs.set(self._key(block, name), value)
python
def set(self, block, name, value): """ Set the value of the field named `name` """ self._kvs.set(self._key(block, name), value)
[ "def", "set", "(", "self", ",", "block", ",", "name", ",", "value", ")", ":", "self", ".", "_kvs", ".", "set", "(", "self", ".", "_key", "(", "block", ",", "name", ")", ",", "value", ")" ]
Set the value of the field named `name`
[ "Set", "the", "value", "of", "the", "field", "named", "name" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L202-L206
train
234,730
edx/XBlock
xblock/runtime.py
KvsFieldData.delete
def delete(self, block, name): """ Reset the value of the field named `name` to the default """ self._kvs.delete(self._key(block, name))
python
def delete(self, block, name): """ Reset the value of the field named `name` to the default """ self._kvs.delete(self._key(block, name))
[ "def", "delete", "(", "self", ",", "block", ",", "name", ")", ":", "self", ".", "_kvs", ".", "delete", "(", "self", ".", "_key", "(", "block", ",", "name", ")", ")" ]
Reset the value of the field named `name` to the default
[ "Reset", "the", "value", "of", "the", "field", "named", "name", "to", "the", "default" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L208-L212
train
234,731
edx/XBlock
xblock/runtime.py
KvsFieldData.has
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value """ try: return self._kvs.has(self._key(block, name)) except KeyError: return False
python
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value """ try: return self._kvs.has(self._key(block, name)) except KeyError: return False
[ "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
[ "Return", "whether", "or", "not", "the", "field", "named", "name", "has", "a", "non", "-", "default", "value" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L214-L221
train
234,732
edx/XBlock
xblock/runtime.py
KvsFieldData.set_many
def set_many(self, block, update_dict): """Update the underlying model with the correct values.""" updated_dict = {} # Generate a new dict with the correct mappings. for (key, value) in six.iteritems(update_dict): updated_dict[self._key(block, key)] = value self._kvs.set_many(updated_dict)
python
def set_many(self, block, update_dict): """Update the underlying model with the correct values.""" updated_dict = {} # Generate a new dict with the correct mappings. for (key, value) in six.iteritems(update_dict): updated_dict[self._key(block, key)] = value self._kvs.set_many(updated_dict)
[ "def", "set_many", "(", "self", ",", "block", ",", "update_dict", ")", ":", "updated_dict", "=", "{", "}", "# Generate a new dict with the correct mappings.", "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.
[ "Update", "the", "underlying", "model", "with", "the", "correct", "values", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L223-L231
train
234,733
edx/XBlock
xblock/runtime.py
MemoryIdManager.create_aside
def create_aside(self, definition_id, usage_id, aside_type): """Create the aside.""" return ( self.ASIDE_DEFINITION_ID(definition_id, aside_type), self.ASIDE_USAGE_ID(usage_id, aside_type), )
python
def create_aside(self, definition_id, usage_id, aside_type): """Create the aside.""" return ( self.ASIDE_DEFINITION_ID(definition_id, aside_type), self.ASIDE_USAGE_ID(usage_id, aside_type), )
[ "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.
[ "Create", "the", "aside", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L385-L390
train
234,734
edx/XBlock
xblock/runtime.py
MemoryIdManager.create_usage
def create_usage(self, def_id): """Make a usage, storing its definition id.""" usage_id = self._next_id("u") self._usages[usage_id] = def_id return usage_id
python
def create_usage(self, def_id): """Make a usage, storing its definition id.""" usage_id = self._next_id("u") self._usages[usage_id] = def_id return usage_id
[ "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.
[ "Make", "a", "usage", "storing", "its", "definition", "id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L400-L404
train
234,735
edx/XBlock
xblock/runtime.py
MemoryIdManager.get_definition_id
def get_definition_id(self, usage_id): """Get a definition_id by its usage id.""" try: return self._usages[usage_id] except KeyError: raise NoSuchUsage(repr(usage_id))
python
def get_definition_id(self, usage_id): """Get a definition_id by its usage id.""" try: return self._usages[usage_id] except KeyError: raise NoSuchUsage(repr(usage_id))
[ "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.
[ "Get", "a", "definition_id", "by", "its", "usage", "id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L406-L411
train
234,736
edx/XBlock
xblock/runtime.py
MemoryIdManager.create_definition
def create_definition(self, block_type, slug=None): """Make a definition, storing its block type.""" prefix = "d" if slug: prefix += "_" + slug def_id = self._next_id(prefix) self._definitions[def_id] = block_type return def_id
python
def create_definition(self, block_type, slug=None): """Make a definition, storing its block type.""" prefix = "d" if slug: prefix += "_" + slug def_id = self._next_id(prefix) self._definitions[def_id] = block_type return def_id
[ "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.
[ "Make", "a", "definition", "storing", "its", "block", "type", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L413-L420
train
234,737
edx/XBlock
xblock/runtime.py
MemoryIdManager.get_block_type
def get_block_type(self, def_id): """Get a block_type by its definition id.""" try: return self._definitions[def_id] except KeyError: try: return def_id.aside_type except AttributeError: raise NoSuchDefinition(repr(def_id))
python
def get_block_type(self, def_id): """Get a block_type by its definition id.""" try: return self._definitions[def_id] except KeyError: try: return def_id.aside_type except AttributeError: raise NoSuchDefinition(repr(def_id))
[ "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.
[ "Get", "a", "block_type", "by", "its", "definition", "id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L422-L430
train
234,738
edx/XBlock
xblock/runtime.py
Runtime.field_data
def field_data(self, field_data): """ Set field_data. Deprecated in favor of a 'field-data' service. """ warnings.warn("Runtime.field_data is deprecated", FieldDataDeprecationWarning, stacklevel=2) self._deprecated_per_instance_field_data = field_data
python
def field_data(self, field_data): """ Set field_data. Deprecated in favor of a 'field-data' service. """ warnings.warn("Runtime.field_data is deprecated", FieldDataDeprecationWarning, stacklevel=2) self._deprecated_per_instance_field_data = field_data
[ "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. Deprecated in favor of a 'field-data' service.
[ "Set", "field_data", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L593-L600
train
234,739
edx/XBlock
xblock/runtime.py
Runtime.construct_xblock_from_class
def construct_xblock_from_class(self, cls, scope_ids, field_data=None, *args, **kwargs): """ Construct a new xblock of type cls, mixing in the mixins defined for this application. """ return self.mixologist.mix(cls)( runtime=self, field_data=field_data, scope_ids=scope_ids, *args, **kwargs )
python
def construct_xblock_from_class(self, cls, scope_ids, field_data=None, *args, **kwargs): """ Construct a new xblock of type cls, mixing in the mixins defined for this application. """ return self.mixologist.mix(cls)( runtime=self, field_data=field_data, scope_ids=scope_ids, *args, **kwargs )
[ "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.
[ "Construct", "a", "new", "xblock", "of", "type", "cls", "mixing", "in", "the", "mixins", "defined", "for", "this", "application", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L626-L636
train
234,740
edx/XBlock
xblock/runtime.py
Runtime.get_block
def get_block(self, usage_id, for_parent=None): """ Create an XBlock instance in this runtime. The `usage_id` is used to find the XBlock class and data. """ 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 = self.construct_xblock(block_type, keys, for_parent=for_parent) return block
python
def get_block(self, usage_id, for_parent=None): """ Create an XBlock instance in this runtime. The `usage_id` is used to find the XBlock class and data. """ 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 = self.construct_xblock(block_type, keys, for_parent=for_parent) return block
[ "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", "=", "self", ".", "construct_xblock", "(", "block_type", ",", "keys", ",", "for_parent", "=", "for_parent", ")", "return", "block" ]
Create an XBlock instance in this runtime. The `usage_id` is used to find the XBlock class and data.
[ "Create", "an", "XBlock", "instance", "in", "this", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L638-L651
train
234,741
edx/XBlock
xblock/runtime.py
Runtime.get_aside
def get_aside(self, aside_usage_id): """ Create an XBlockAside in this runtime. The `aside_usage_id` is used to find the Aside class and data. """ 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.create_aside(xblock_def, xblock_usage, aside_type) keys = ScopeIds(self.user_id, aside_type, aside_def_id, aside_usage_id) block = self.create_aside(aside_type, keys) return block
python
def get_aside(self, aside_usage_id): """ Create an XBlockAside in this runtime. The `aside_usage_id` is used to find the Aside class and data. """ 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.create_aside(xblock_def, xblock_usage, aside_type) keys = ScopeIds(self.user_id, aside_type, aside_def_id, aside_usage_id) block = self.create_aside(aside_type, keys) return block
[ "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", ".", "create_aside", "(", "xblock_def", ",", "xblock_usage", ",", "aside_type", ")", "keys", "=", "ScopeIds", "(", "self", ".", "user_id", ",", "aside_type", ",", "aside_def_id", ",", "aside_usage_id", ")", "block", "=", "self", ".", "create_aside", "(", "aside_type", ",", "keys", ")", "return", "block" ]
Create an XBlockAside in this runtime. The `aside_usage_id` is used to find the Aside class and data.
[ "Create", "an", "XBlockAside", "in", "this", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L653-L666
train
234,742
edx/XBlock
xblock/runtime.py
Runtime.parse_xml_string
def parse_xml_string(self, xml, id_generator=None): """Parse a string of XML, returning a usage id.""" 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 isinstance(xml, six.binary_type): io_type = BytesIO else: io_type = StringIO return self.parse_xml_file(io_type(xml), id_generator)
python
def parse_xml_string(self, xml, id_generator=None): """Parse a string of XML, returning a usage id.""" 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 isinstance(xml, six.binary_type): io_type = BytesIO else: io_type = StringIO return self.parse_xml_file(io_type(xml), id_generator)
[ "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", "isinstance", "(", "xml", ",", "six", ".", "binary_type", ")", ":", "io_type", "=", "BytesIO", "else", ":", "io_type", "=", "StringIO", "return", "self", ".", "parse_xml_file", "(", "io_type", "(", "xml", ")", ",", "id_generator", ")" ]
Parse a string of XML, returning a usage id.
[ "Parse", "a", "string", "of", "XML", "returning", "a", "usage", "id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L670-L685
train
234,743
edx/XBlock
xblock/runtime.py
Runtime.parse_xml_file
def parse_xml_file(self, fileobj, id_generator=None): """Parse an open XML file, returning a usage id.""" root = etree.parse(fileobj).getroot() usage_id = self._usage_id_from_node(root, None, id_generator) return usage_id
python
def parse_xml_file(self, fileobj, id_generator=None): """Parse an open XML file, returning a usage id.""" root = etree.parse(fileobj).getroot() usage_id = self._usage_id_from_node(root, None, id_generator) return usage_id
[ "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.
[ "Parse", "an", "open", "XML", "file", "returning", "a", "usage", "id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L687-L691
train
234,744
edx/XBlock
xblock/runtime.py
Runtime._usage_id_from_node
def _usage_id_from_node(self, node, parent_id, id_generator=None): """Create a new usage id from an XML dom node. Args: node (lxml.etree.Element): The DOM node to interpret. parent_id: The usage ID of the parent block id_generator (IdGenerator): The :class:`.IdGenerator` to use for creating ids """ 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_generator block_type = node.tag # remove xblock-family from elements node.attrib.pop('xblock-family', None) # TODO: a way for this node to be a usage to an existing definition? def_id = id_generator.create_definition(block_type) usage_id = id_generator.create_usage(def_id) keys = ScopeIds(None, block_type, def_id, usage_id) block_class = self.mixologist.mix(self.load_block_type(block_type)) # pull the asides out of the xml payload aside_children = [] for child in node.iterchildren(): # get xblock-family from node xblock_family = child.attrib.pop('xblock-family', None) if xblock_family: xblock_family = self._family_id_to_superclass(xblock_family) if issubclass(xblock_family, XBlockAside): aside_children.append(child) # now process them & remove them from the xml payload for child in aside_children: self._aside_from_xml(child, def_id, usage_id, id_generator) node.remove(child) block = block_class.parse_xml(node, self, keys, id_generator) block.parent = parent_id block.save() return usage_id
python
def _usage_id_from_node(self, node, parent_id, id_generator=None): """Create a new usage id from an XML dom node. Args: node (lxml.etree.Element): The DOM node to interpret. parent_id: The usage ID of the parent block id_generator (IdGenerator): The :class:`.IdGenerator` to use for creating ids """ 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_generator block_type = node.tag # remove xblock-family from elements node.attrib.pop('xblock-family', None) # TODO: a way for this node to be a usage to an existing definition? def_id = id_generator.create_definition(block_type) usage_id = id_generator.create_usage(def_id) keys = ScopeIds(None, block_type, def_id, usage_id) block_class = self.mixologist.mix(self.load_block_type(block_type)) # pull the asides out of the xml payload aside_children = [] for child in node.iterchildren(): # get xblock-family from node xblock_family = child.attrib.pop('xblock-family', None) if xblock_family: xblock_family = self._family_id_to_superclass(xblock_family) if issubclass(xblock_family, XBlockAside): aside_children.append(child) # now process them & remove them from the xml payload for child in aside_children: self._aside_from_xml(child, def_id, usage_id, id_generator) node.remove(child) block = block_class.parse_xml(node, self, keys, id_generator) block.parent = parent_id block.save() return usage_id
[ "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_generator", "block_type", "=", "node", ".", "tag", "# remove xblock-family from elements", "node", ".", "attrib", ".", "pop", "(", "'xblock-family'", ",", "None", ")", "# TODO: a way for this node to be a usage to an existing definition?", "def_id", "=", "id_generator", ".", "create_definition", "(", "block_type", ")", "usage_id", "=", "id_generator", ".", "create_usage", "(", "def_id", ")", "keys", "=", "ScopeIds", "(", "None", ",", "block_type", ",", "def_id", ",", "usage_id", ")", "block_class", "=", "self", ".", "mixologist", ".", "mix", "(", "self", ".", "load_block_type", "(", "block_type", ")", ")", "# pull the asides out of the xml payload", "aside_children", "=", "[", "]", "for", "child", "in", "node", ".", "iterchildren", "(", ")", ":", "# get xblock-family from node", "xblock_family", "=", "child", ".", "attrib", ".", "pop", "(", "'xblock-family'", ",", "None", ")", "if", "xblock_family", ":", "xblock_family", "=", "self", ".", "_family_id_to_superclass", "(", "xblock_family", ")", "if", "issubclass", "(", "xblock_family", ",", "XBlockAside", ")", ":", "aside_children", ".", "append", "(", "child", ")", "# now process them & remove them from the xml payload", "for", "child", "in", "aside_children", ":", "self", ".", "_aside_from_xml", "(", "child", ",", "def_id", ",", "usage_id", ",", "id_generator", ")", "node", ".", "remove", "(", "child", ")", "block", "=", "block_class", ".", "parse_xml", "(", "node", ",", "self", ",", "keys", ",", "id_generator", ")", "block", ".", "parent", "=", "parent_id", "block", ".", "save", "(", ")", "return", "usage_id" ]
Create a new usage id from an XML dom node. Args: node (lxml.etree.Element): The DOM node to interpret. parent_id: The usage ID of the parent block id_generator (IdGenerator): The :class:`.IdGenerator` to use for creating ids
[ "Create", "a", "new", "usage", "id", "from", "an", "XML", "dom", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L693-L736
train
234,745
edx/XBlock
xblock/runtime.py
Runtime._aside_from_xml
def _aside_from_xml(self, node, block_def_id, block_usage_id, id_generator): """ Create an aside from the xml and attach it to the given block """ 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) keys = ScopeIds(None, aside_type, aside_def_id, aside_usage_id) aside = aside_class.parse_xml(node, self, keys, id_generator) aside.save()
python
def _aside_from_xml(self, node, block_def_id, block_usage_id, id_generator): """ Create an aside from the xml and attach it to the given block """ 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) keys = ScopeIds(None, aside_type, aside_def_id, aside_usage_id) aside = aside_class.parse_xml(node, self, keys, id_generator) aside.save()
[ "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", ")", "keys", "=", "ScopeIds", "(", "None", ",", "aside_type", ",", "aside_def_id", ",", "aside_usage_id", ")", "aside", "=", "aside_class", ".", "parse_xml", "(", "node", ",", "self", ",", "keys", ",", "id_generator", ")", "aside", ".", "save", "(", ")" ]
Create an aside from the xml and attach it to the given block
[ "Create", "an", "aside", "from", "the", "xml", "and", "attach", "it", "to", "the", "given", "block" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L738-L749
train
234,746
edx/XBlock
xblock/runtime.py
Runtime.add_node_as_child
def add_node_as_child(self, block, node, id_generator=None): """ Called by XBlock.parse_xml to treat a child node as a child block. """ usage_id = self._usage_id_from_node(node, block.scope_ids.usage_id, id_generator) block.children.append(usage_id)
python
def add_node_as_child(self, block, node, id_generator=None): """ Called by XBlock.parse_xml to treat a child node as a child block. """ usage_id = self._usage_id_from_node(node, block.scope_ids.usage_id, id_generator) block.children.append(usage_id)
[ "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.
[ "Called", "by", "XBlock", ".", "parse_xml", "to", "treat", "a", "child", "node", "as", "a", "child", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L751-L756
train
234,747
edx/XBlock
xblock/runtime.py
Runtime.export_to_xml
def export_to_xml(self, block, xmlfile): """ Export the block to XML, writing the XML to `xmlfile`. """ root = etree.Element("unknown_root", nsmap=XML_NAMESPACES) tree = etree.ElementTree(root) block.add_xml_to_node(root) # write asides as children for aside in self.get_asides(block): if aside.needs_serialization(): aside_node = etree.Element("unknown_root", nsmap=XML_NAMESPACES) aside.add_xml_to_node(aside_node) block.append(aside_node) tree.write(xmlfile, xml_declaration=True, pretty_print=True, encoding='utf-8')
python
def export_to_xml(self, block, xmlfile): """ Export the block to XML, writing the XML to `xmlfile`. """ root = etree.Element("unknown_root", nsmap=XML_NAMESPACES) tree = etree.ElementTree(root) block.add_xml_to_node(root) # write asides as children for aside in self.get_asides(block): if aside.needs_serialization(): aside_node = etree.Element("unknown_root", nsmap=XML_NAMESPACES) aside.add_xml_to_node(aside_node) block.append(aside_node) tree.write(xmlfile, xml_declaration=True, pretty_print=True, encoding='utf-8')
[ "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", ")", "# write asides as children", "for", "aside", "in", "self", ".", "get_asides", "(", "block", ")", ":", "if", "aside", ".", "needs_serialization", "(", ")", ":", "aside_node", "=", "etree", ".", "Element", "(", "\"unknown_root\"", ",", "nsmap", "=", "XML_NAMESPACES", ")", "aside", ".", "add_xml_to_node", "(", "aside_node", ")", "block", ".", "append", "(", "aside_node", ")", "tree", ".", "write", "(", "xmlfile", ",", "xml_declaration", "=", "True", ",", "pretty_print", "=", "True", ",", "encoding", "=", "'utf-8'", ")" ]
Export the block to XML, writing the XML to `xmlfile`.
[ "Export", "the", "block", "to", "XML", "writing", "the", "XML", "to", "xmlfile", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L760-L773
train
234,748
edx/XBlock
xblock/runtime.py
Runtime.add_block_as_child_node
def add_block_as_child_node(self, block, node): """ Export `block` as a child node of `node`. """ child = etree.SubElement(node, "unknown") block.add_xml_to_node(child)
python
def add_block_as_child_node(self, block, node): """ Export `block` as a child node of `node`. """ child = etree.SubElement(node, "unknown") block.add_xml_to_node(child)
[ "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`.
[ "Export", "block", "as", "a", "child", "node", "of", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L775-L780
train
234,749
edx/XBlock
xblock/runtime.py
Runtime.render
def render(self, block, view_name, context=None): """ Render a block by invoking its view. Finds the view named `view_name` on `block`. The default view will be used if a specific view hasn't be registered. If there is no default view, an exception will be raised. The view is invoked, passing it `context`. The value returned by the view is returned, with possible modifications by the runtime to integrate it into a larger whole. """ # Set the active view so that :function:`render_child` can use it # as a default 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_fn = functools.partial(view_fn, view_name) frag = view_fn(context) # Explicitly save because render action may have changed state block.save() updated_frag = self.wrap_xblock(block, view_name, frag, context) return self.render_asides(block, view_name, updated_frag, context) finally: # Reset the active view to what it was before entering this method self._view_name = old_view_name
python
def render(self, block, view_name, context=None): """ Render a block by invoking its view. Finds the view named `view_name` on `block`. The default view will be used if a specific view hasn't be registered. If there is no default view, an exception will be raised. The view is invoked, passing it `context`. The value returned by the view is returned, with possible modifications by the runtime to integrate it into a larger whole. """ # Set the active view so that :function:`render_child` can use it # as a default 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_fn = functools.partial(view_fn, view_name) frag = view_fn(context) # Explicitly save because render action may have changed state block.save() updated_frag = self.wrap_xblock(block, view_name, frag, context) return self.render_asides(block, view_name, updated_frag, context) finally: # Reset the active view to what it was before entering this method self._view_name = old_view_name
[ "def", "render", "(", "self", ",", "block", ",", "view_name", ",", "context", "=", "None", ")", ":", "# Set the active view so that :function:`render_child` can use it", "# as a default", "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_fn", "=", "functools", ".", "partial", "(", "view_fn", ",", "view_name", ")", "frag", "=", "view_fn", "(", "context", ")", "# Explicitly save because render action may have changed state", "block", ".", "save", "(", ")", "updated_frag", "=", "self", ".", "wrap_xblock", "(", "block", ",", "view_name", ",", "frag", ",", "context", ")", "return", "self", ".", "render_asides", "(", "block", ",", "view_name", ",", "updated_frag", ",", "context", ")", "finally", ":", "# Reset the active view to what it was before entering this method", "self", ".", "_view_name", "=", "old_view_name" ]
Render a block by invoking its view. Finds the view named `view_name` on `block`. The default view will be used if a specific view hasn't be registered. If there is no default view, an exception will be raised. The view is invoked, passing it `context`. The value returned by the view is returned, with possible modifications by the runtime to integrate it into a larger whole.
[ "Render", "a", "block", "by", "invoking", "its", "view", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L784-L818
train
234,750
edx/XBlock
xblock/runtime.py
Runtime.render_child
def render_child(self, child, view_name=None, context=None): """A shortcut to render a child block. Use this method to render your children from your own view function. If `view_name` is not provided, it will default to the view name you're being rendered with. Returns the same value as :func:`render`. """ return child.render(view_name or self._view_name, context)
python
def render_child(self, child, view_name=None, context=None): """A shortcut to render a child block. Use this method to render your children from your own view function. If `view_name` is not provided, it will default to the view name you're being rendered with. Returns the same value as :func:`render`. """ return child.render(view_name or self._view_name, context)
[ "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. Use this method to render your children from your own view function. If `view_name` is not provided, it will default to the view name you're being rendered with. Returns the same value as :func:`render`.
[ "A", "shortcut", "to", "render", "a", "child", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L820-L831
train
234,751
edx/XBlock
xblock/runtime.py
Runtime.render_children
def render_children(self, block, view_name=None, context=None): """Render a block's children, returning a list of results. Each child of `block` will be rendered, just as :func:`render_child` does. Returns a list of values, each as provided by :func:`render`. """ 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
python
def render_children(self, block, view_name=None, context=None): """Render a block's children, returning a list of results. Each child of `block` will be rendered, just as :func:`render_child` does. Returns a list of values, each as provided by :func:`render`. """ 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
[ "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. Each child of `block` will be rendered, just as :func:`render_child` does. Returns a list of values, each as provided by :func:`render`.
[ "Render", "a", "block", "s", "children", "returning", "a", "list", "of", "results", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L833-L846
train
234,752
edx/XBlock
xblock/runtime.py
Runtime.wrap_xblock
def wrap_xblock(self, block, view, frag, context): # pylint: disable=W0613 """ Creates a div which identifies the xblock and writes out the json_init_args into a script tag. If there's a `wrap_child` method, it calls that with a deprecation warning. The default implementation creates a frag to wraps frag w/ a div identifying the xblock. If you have javascript, you'll need to override this impl """ 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) # pylint: disable=no-member extra_data = {'name': block.name} if block.name else {} return self._wrap_ele(block, view, frag, extra_data)
python
def wrap_xblock(self, block, view, frag, context): # pylint: disable=W0613 """ Creates a div which identifies the xblock and writes out the json_init_args into a script tag. If there's a `wrap_child` method, it calls that with a deprecation warning. The default implementation creates a frag to wraps frag w/ a div identifying the xblock. If you have javascript, you'll need to override this impl """ 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) # pylint: disable=no-member extra_data = {'name': block.name} if block.name else {} return self._wrap_ele(block, view, frag, extra_data)
[ "def", "wrap_xblock", "(", "self", ",", "block", ",", "view", ",", "frag", ",", "context", ")", ":", "# pylint: disable=W0613", "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", ")", "# pylint: disable=no-member", "extra_data", "=", "{", "'name'", ":", "block", ".", "name", "}", "if", "block", ".", "name", "else", "{", "}", "return", "self", ".", "_wrap_ele", "(", "block", ",", "view", ",", "frag", ",", "extra_data", ")" ]
Creates a div which identifies the xblock and writes out the json_init_args into a script tag. If there's a `wrap_child` method, it calls that with a deprecation warning. The default implementation creates a frag to wraps frag w/ a div identifying the xblock. If you have javascript, you'll need to override this impl
[ "Creates", "a", "div", "which", "identifies", "the", "xblock", "and", "writes", "out", "the", "json_init_args", "into", "a", "script", "tag", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L848-L862
train
234,753
edx/XBlock
xblock/runtime.py
Runtime.wrap_aside
def wrap_aside(self, block, aside, view, frag, context): # pylint: disable=unused-argument """ Creates a div which identifies the aside, points to the original block, and writes out the json_init_args into a script tag. The default implementation creates a frag to wraps frag w/ a div identifying the xblock. If you have javascript, you'll need to override this impl """ return self._wrap_ele( aside, view, frag, { 'block_id': block.scope_ids.usage_id, 'url_selector': 'asideBaseUrl', })
python
def wrap_aside(self, block, aside, view, frag, context): # pylint: disable=unused-argument """ Creates a div which identifies the aside, points to the original block, and writes out the json_init_args into a script tag. The default implementation creates a frag to wraps frag w/ a div identifying the xblock. If you have javascript, you'll need to override this impl """ return self._wrap_ele( aside, view, frag, { 'block_id': block.scope_ids.usage_id, 'url_selector': 'asideBaseUrl', })
[ "def", "wrap_aside", "(", "self", ",", "block", ",", "aside", ",", "view", ",", "frag", ",", "context", ")", ":", "# pylint: disable=unused-argument", "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. The default implementation creates a frag to wraps frag w/ a div identifying the xblock. If you have javascript, you'll need to override this impl
[ "Creates", "a", "div", "which", "identifies", "the", "aside", "points", "to", "the", "original", "block", "and", "writes", "out", "the", "json_init_args", "into", "a", "script", "tag", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L864-L876
train
234,754
edx/XBlock
xblock/runtime.py
Runtime._wrap_ele
def _wrap_ele(self, block, view, frag, extra_data=None): """ 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. """ 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_init_version json_init = "" # TODO/Note: We eventually want to remove: hasattr(frag, 'json_init_args') # However, I'd like to maintain backwards-compatibility with older XBlock # for at least a little while so as not to adversely effect developers. # pmitros/Jun 28, 2014. if hasattr(frag, 'json_init_args') and frag.json_init_args is not None: json_init = ( '<script type="json/xblock-args" class="xblock_json_init_args">' '{data}</script>' ).format(data=json.dumps(frag.json_init_args)) block_css_entrypoint = block.entry_point.replace('.', '-') css_classes = [ block_css_entrypoint, '{}-{}'.format(block_css_entrypoint, view), ] html = "<div class='{}'{properties}>{body}{js}</div>".format( markupsafe.escape(' '.join(css_classes)), properties="".join(" data-%s='%s'" % item for item in list(data.items())), body=frag.body_html(), js=json_init) wrapped.add_content(html) wrapped.add_fragment_resources(frag) return wrapped
python
def _wrap_ele(self, block, view, frag, extra_data=None): """ 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. """ 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_init_version json_init = "" # TODO/Note: We eventually want to remove: hasattr(frag, 'json_init_args') # However, I'd like to maintain backwards-compatibility with older XBlock # for at least a little while so as not to adversely effect developers. # pmitros/Jun 28, 2014. if hasattr(frag, 'json_init_args') and frag.json_init_args is not None: json_init = ( '<script type="json/xblock-args" class="xblock_json_init_args">' '{data}</script>' ).format(data=json.dumps(frag.json_init_args)) block_css_entrypoint = block.entry_point.replace('.', '-') css_classes = [ block_css_entrypoint, '{}-{}'.format(block_css_entrypoint, view), ] html = "<div class='{}'{properties}>{body}{js}</div>".format( markupsafe.escape(' '.join(css_classes)), properties="".join(" data-%s='%s'" % item for item in list(data.items())), body=frag.body_html(), js=json_init) wrapped.add_content(html) wrapped.add_fragment_resources(frag) return wrapped
[ "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_init_version", "json_init", "=", "\"\"", "# TODO/Note: We eventually want to remove: hasattr(frag, 'json_init_args')", "# However, I'd like to maintain backwards-compatibility with older XBlock", "# for at least a little while so as not to adversely effect developers.", "# pmitros/Jun 28, 2014.", "if", "hasattr", "(", "frag", ",", "'json_init_args'", ")", "and", "frag", ".", "json_init_args", "is", "not", "None", ":", "json_init", "=", "(", "'<script type=\"json/xblock-args\" class=\"xblock_json_init_args\">'", "'{data}</script>'", ")", ".", "format", "(", "data", "=", "json", ".", "dumps", "(", "frag", ".", "json_init_args", ")", ")", "block_css_entrypoint", "=", "block", ".", "entry_point", ".", "replace", "(", "'.'", ",", "'-'", ")", "css_classes", "=", "[", "block_css_entrypoint", ",", "'{}-{}'", ".", "format", "(", "block_css_entrypoint", ",", "view", ")", ",", "]", "html", "=", "\"<div class='{}'{properties}>{body}{js}</div>\"", ".", "format", "(", "markupsafe", ".", "escape", "(", "' '", ".", "join", "(", "css_classes", ")", ")", ",", "properties", "=", "\"\"", ".", "join", "(", "\" data-%s='%s'\"", "%", "item", "for", "item", "in", "list", "(", "data", ".", "items", "(", ")", ")", ")", ",", "body", "=", "frag", ".", "body_html", "(", ")", ",", "js", "=", "json_init", ")", "wrapped", ".", "add_content", "(", "html", ")", "wrapped", ".", "add_fragment_resources", "(", "frag", ")", "return", "wrapped" ]
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.
[ "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", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L878-L919
train
234,755
edx/XBlock
xblock/runtime.py
Runtime.get_asides
def get_asides(self, block): """ Return instances for all of the asides that will decorate this `block`. Arguments: block (:class:`.XBlock`): The block to render retrieve asides for. Returns: List of XBlockAside instances """ 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) ]
python
def get_asides(self, block): """ Return instances for all of the asides that will decorate this `block`. Arguments: block (:class:`.XBlock`): The block to render retrieve asides for. Returns: List of XBlockAside instances """ 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) ]
[ "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`. Arguments: block (:class:`.XBlock`): The block to render retrieve asides for. Returns: List of XBlockAside instances
[ "Return", "instances", "for", "all", "of", "the", "asides", "that", "will", "decorate", "this", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L930-L947
train
234,756
edx/XBlock
xblock/runtime.py
Runtime.get_aside_of_type
def get_aside_of_type(self, block, aside_type): """ Return the aside of the given aside_type which might be decorating this `block`. Arguments: block (:class:`.XBlock`): The block to retrieve asides for. aside_type (`str`): the type of the aside """ # TODO: This function will need to be extended if we want to allow: # a) XBlockAsides to statically indicated which types of blocks they can comment on # b) XBlockRuntimes to limit the selection of asides to a subset of the installed asides # c) Optimize by only loading asides that actually decorate a particular view 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(usage_id) aside_def_id, aside_usage_id = self.id_generator.create_aside(definition_id, usage_id, aside_type) scope_ids = ScopeIds(self.user_id, aside_type, aside_def_id, aside_usage_id) return aside_cls(runtime=self, scope_ids=scope_ids)
python
def get_aside_of_type(self, block, aside_type): """ Return the aside of the given aside_type which might be decorating this `block`. Arguments: block (:class:`.XBlock`): The block to retrieve asides for. aside_type (`str`): the type of the aside """ # TODO: This function will need to be extended if we want to allow: # a) XBlockAsides to statically indicated which types of blocks they can comment on # b) XBlockRuntimes to limit the selection of asides to a subset of the installed asides # c) Optimize by only loading asides that actually decorate a particular view 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(usage_id) aside_def_id, aside_usage_id = self.id_generator.create_aside(definition_id, usage_id, aside_type) scope_ids = ScopeIds(self.user_id, aside_type, aside_def_id, aside_usage_id) return aside_cls(runtime=self, scope_ids=scope_ids)
[ "def", "get_aside_of_type", "(", "self", ",", "block", ",", "aside_type", ")", ":", "# TODO: This function will need to be extended if we want to allow:", "# a) XBlockAsides to statically indicated which types of blocks they can comment on", "# b) XBlockRuntimes to limit the selection of asides to a subset of the installed asides", "# c) Optimize by only loading asides that actually decorate a particular view", "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", "(", "usage_id", ")", "aside_def_id", ",", "aside_usage_id", "=", "self", ".", "id_generator", ".", "create_aside", "(", "definition_id", ",", "usage_id", ",", "aside_type", ")", "scope_ids", "=", "ScopeIds", "(", "self", ".", "user_id", ",", "aside_type", ",", "aside_def_id", ",", "aside_usage_id", ")", "return", "aside_cls", "(", "runtime", "=", "self", ",", "scope_ids", "=", "scope_ids", ")" ]
Return the aside of the given aside_type which might be decorating this `block`. Arguments: block (:class:`.XBlock`): The block to retrieve asides for. aside_type (`str`): the type of the aside
[ "Return", "the", "aside", "of", "the", "given", "aside_type", "which", "might", "be", "decorating", "this", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L958-L980
train
234,757
edx/XBlock
xblock/runtime.py
Runtime.render_asides
def render_asides(self, block, view_name, frag, context): """ Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering. """ 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: # layout (overideable by other runtimes) return self.layout_asides(block, context, frag, view_name, aside_frag_fns) return frag
python
def render_asides(self, block, view_name, frag, context): """ Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering. """ 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: # layout (overideable by other runtimes) return self.layout_asides(block, context, frag, view_name, aside_frag_fns) return frag
[ "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", ":", "# layout (overideable by other runtimes)", "return", "self", ".", "layout_asides", "(", "block", ",", "context", ",", "frag", ",", "view_name", ",", "aside_frag_fns", ")", "return", "frag" ]
Collect all of the asides' add ons and format them into the frag. The frag already has the given block's rendering.
[ "Collect", "all", "of", "the", "asides", "add", "ons", "and", "format", "them", "into", "the", "frag", ".", "The", "frag", "already", "has", "the", "given", "block", "s", "rendering", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L982-L995
train
234,758
edx/XBlock
xblock/runtime.py
Runtime.layout_asides
def layout_asides(self, block, context, frag, view_name, aside_frag_fns): """ 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 This default method appends the aside_frags after frag. If you override this, you must call wrap_aside around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call """ 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() result.add_content(aside_frag.content) result.add_fragment_resources(aside_frag) return result
python
def layout_asides(self, block, context, frag, view_name, aside_frag_fns): """ 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 This default method appends the aside_frags after frag. If you override this, you must call wrap_aside around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call """ 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() result.add_content(aside_frag.content) result.add_fragment_resources(aside_frag) return result
[ "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", "(", ")", "result", ".", "add_content", "(", "aside_frag", ".", "content", ")", "result", ".", "add_fragment_resources", "(", "aside_frag", ")", "return", "result" ]
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 This default method appends the aside_frags after frag. If you override this, you must call wrap_aside around each aside as per this function. Args: block (XBlock): the block being rendered frag (html): The result from rendering the block aside_frag_fns list((aside, aside_fn)): The asides and closures for rendering to call
[ "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" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L997-L1019
train
234,759
edx/XBlock
xblock/runtime.py
Runtime.handle
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available """ handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) # Write out dirty fields block.save() return results
python
def handle(self, block, handler_name, request, suffix=''): """ Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available """ handler = getattr(block, handler_name, None) if handler and getattr(handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = handler(request, suffix) else: fallback_handler = getattr(block, "fallback_handler", None) if fallback_handler and getattr(fallback_handler, '_is_xblock_handler', False): # Cache results of the handler call for later saving results = fallback_handler(handler_name, request, suffix) else: raise NoSuchHandlerError("Couldn't find handler %r for %r" % (handler_name, block)) # Write out dirty fields block.save() return results
[ "def", "handle", "(", "self", ",", "block", ",", "handler_name", ",", "request", ",", "suffix", "=", "''", ")", ":", "handler", "=", "getattr", "(", "block", ",", "handler_name", ",", "None", ")", "if", "handler", "and", "getattr", "(", "handler", ",", "'_is_xblock_handler'", ",", "False", ")", ":", "# Cache results of the handler call for later saving", "results", "=", "handler", "(", "request", ",", "suffix", ")", "else", ":", "fallback_handler", "=", "getattr", "(", "block", ",", "\"fallback_handler\"", ",", "None", ")", "if", "fallback_handler", "and", "getattr", "(", "fallback_handler", ",", "'_is_xblock_handler'", ",", "False", ")", ":", "# Cache results of the handler call for later saving", "results", "=", "fallback_handler", "(", "handler_name", ",", "request", ",", "suffix", ")", "else", ":", "raise", "NoSuchHandlerError", "(", "\"Couldn't find handler %r for %r\"", "%", "(", "handler_name", ",", "block", ")", ")", "# Write out dirty fields", "block", ".", "save", "(", ")", "return", "results" ]
Handles any calls to the specified `handler_name`. Provides a fallback handler if the specified handler isn't found. :param handler_name: The name of the handler to call :param request: The request to handle :type request: webob.Request :param suffix: The remainder of the url, after the handler url prefix, if available
[ "Handles", "any", "calls", "to", "the", "specified", "handler_name", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1023-L1048
train
234,760
edx/XBlock
xblock/runtime.py
Runtime.service
def service(self, block, service_name): """Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. XBlocks must announce their intention to request services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None. """ 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": raise NoSuchServiceError("Service {!r} is not available.".format(service_name)) return service
python
def service(self, block, service_name): """Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. XBlocks must announce their intention to request services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None. """ 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": raise NoSuchServiceError("Service {!r} is not available.".format(service_name)) return service
[ "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\"", ":", "raise", "NoSuchServiceError", "(", "\"Service {!r} is not available.\"", ".", "format", "(", "service_name", ")", ")", "return", "service" ]
Return a service, or None. Services are objects implementing arbitrary other interfaces. They are requested by agreed-upon names, see [XXX TODO] for a list of possible services. The object returned depends on the service requested. XBlocks must announce their intention to request services with the `XBlock.needs` or `XBlock.wants` decorators. Use `needs` if you assume that the service is available, or `wants` if your code is flexible and can accept a None from this method. Runtimes can override this method if they have different techniques for finding and delivering services. Arguments: block (XBlock): this block's class will be examined for service decorators. service_name (str): the name of the service requested. Returns: An object implementing the requested service, or None.
[ "Return", "a", "service", "or", "None", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1052-L1082
train
234,761
edx/XBlock
xblock/runtime.py
Runtime.querypath
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: disable=C0103 state = ROOT lexer = RegexLexer( ("dotdot", r"\.\."), ("dot", r"\."), ("slashslash", r"//"), ("slash", r"/"), ("atword", r"@\w+"), ("word", r"\w+"), ("err", r"."), ) for tokname, toktext in lexer.lex(path): if state == FINAL: # Shouldn't be any tokens after a last token. raise BadPath() if tokname == "dotdot": # .. (parent) if state == WORD: raise BadPath() results = results.parent() state = WORD elif tokname == "dot": # . (current node) if state == WORD: raise BadPath() state = WORD elif tokname == "slashslash": # // (descendants) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() results = results.descendants() state = SEP elif tokname == "slash": # / (here) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() state = SEP elif tokname == "atword": # @xxx (attribute access) if state != SEP: raise BadPath() results = results.attr(toktext[1:]) state = FINAL elif tokname == "word": # xxx (tag selection) if state != SEP: raise BadPath() results = results.children().tagged(toktext) state = WORD else: raise BadPath("Invalid thing: %r" % toktext) return results
python
def querypath(self, block, path): """An XPath-like interface to `query`.""" class BadPath(Exception): """Bad path exception thrown when path cannot be found.""" pass results = self.query(block) ROOT, SEP, WORD, FINAL = six.moves.range(4) # pylint: disable=C0103 state = ROOT lexer = RegexLexer( ("dotdot", r"\.\."), ("dot", r"\."), ("slashslash", r"//"), ("slash", r"/"), ("atword", r"@\w+"), ("word", r"\w+"), ("err", r"."), ) for tokname, toktext in lexer.lex(path): if state == FINAL: # Shouldn't be any tokens after a last token. raise BadPath() if tokname == "dotdot": # .. (parent) if state == WORD: raise BadPath() results = results.parent() state = WORD elif tokname == "dot": # . (current node) if state == WORD: raise BadPath() state = WORD elif tokname == "slashslash": # // (descendants) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() results = results.descendants() state = SEP elif tokname == "slash": # / (here) if state == SEP: raise BadPath() if state == ROOT: raise NotImplementedError() state = SEP elif tokname == "atword": # @xxx (attribute access) if state != SEP: raise BadPath() results = results.attr(toktext[1:]) state = FINAL elif tokname == "word": # xxx (tag selection) if state != SEP: raise BadPath() results = results.children().tagged(toktext) state = WORD else: raise BadPath("Invalid thing: %r" % toktext) return results
[ "def", "querypath", "(", "self", ",", "block", ",", "path", ")", ":", "class", "BadPath", "(", "Exception", ")", ":", "\"\"\"Bad path exception thrown when path cannot be found.\"\"\"", "pass", "results", "=", "self", ".", "query", "(", "block", ")", "ROOT", ",", "SEP", ",", "WORD", ",", "FINAL", "=", "six", ".", "moves", ".", "range", "(", "4", ")", "# pylint: disable=C0103", "state", "=", "ROOT", "lexer", "=", "RegexLexer", "(", "(", "\"dotdot\"", ",", "r\"\\.\\.\"", ")", ",", "(", "\"dot\"", ",", "r\"\\.\"", ")", ",", "(", "\"slashslash\"", ",", "r\"//\"", ")", ",", "(", "\"slash\"", ",", "r\"/\"", ")", ",", "(", "\"atword\"", ",", "r\"@\\w+\"", ")", ",", "(", "\"word\"", ",", "r\"\\w+\"", ")", ",", "(", "\"err\"", ",", "r\".\"", ")", ",", ")", "for", "tokname", ",", "toktext", "in", "lexer", ".", "lex", "(", "path", ")", ":", "if", "state", "==", "FINAL", ":", "# Shouldn't be any tokens after a last token.", "raise", "BadPath", "(", ")", "if", "tokname", "==", "\"dotdot\"", ":", "# .. (parent)", "if", "state", "==", "WORD", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "parent", "(", ")", "state", "=", "WORD", "elif", "tokname", "==", "\"dot\"", ":", "# . (current node)", "if", "state", "==", "WORD", ":", "raise", "BadPath", "(", ")", "state", "=", "WORD", "elif", "tokname", "==", "\"slashslash\"", ":", "# // (descendants)", "if", "state", "==", "SEP", ":", "raise", "BadPath", "(", ")", "if", "state", "==", "ROOT", ":", "raise", "NotImplementedError", "(", ")", "results", "=", "results", ".", "descendants", "(", ")", "state", "=", "SEP", "elif", "tokname", "==", "\"slash\"", ":", "# / (here)", "if", "state", "==", "SEP", ":", "raise", "BadPath", "(", ")", "if", "state", "==", "ROOT", ":", "raise", "NotImplementedError", "(", ")", "state", "=", "SEP", "elif", "tokname", "==", "\"atword\"", ":", "# @xxx (attribute access)", "if", "state", "!=", "SEP", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "attr", "(", "toktext", "[", "1", ":", "]", ")", "state", "=", "FINAL", "elif", "tokname", "==", "\"word\"", ":", "# xxx (tag selection)", "if", "state", "!=", "SEP", ":", "raise", "BadPath", "(", ")", "results", "=", "results", ".", "children", "(", ")", ".", "tagged", "(", "toktext", ")", "state", "=", "WORD", "else", ":", "raise", "BadPath", "(", "\"Invalid thing: %r\"", "%", "toktext", ")", "return", "results" ]
An XPath-like interface to `query`.
[ "An", "XPath", "-", "like", "interface", "to", "query", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1095-L1156
train
234,762
edx/XBlock
xblock/runtime.py
ObjectAggregator._object_with_attr
def _object_with_attr(self, name): """ Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute """ for obj in self._objects: if hasattr(obj, name): return obj raise AttributeError("No object has attribute {!r}".format(name))
python
def _object_with_attr(self, name): """ Returns the first object that has the attribute `name` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute """ for obj in self._objects: if hasattr(obj, name): return obj raise AttributeError("No object has attribute {!r}".format(name))
[ "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` :param name: the attribute to filter by :type name: `str` :raises AttributeError: when no object has the named attribute
[ "Returns", "the", "first", "object", "that", "has", "the", "attribute", "name" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1179-L1191
train
234,763
edx/XBlock
xblock/runtime.py
Mixologist.mix
def mix(self, cls): """ Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class` """ if hasattr(cls, 'unmixed_class'): base_class = cls.unmixed_class old_mixins = cls.__bases__[1:] # Skip the original unmixed class 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_key not in _CLASS_CACHE: # Only lock if we're about to make a new class with _CLASS_CACHE_LOCK: # Use setdefault so that if someone else has already # created a class before we got the lock, we don't # overwrite it return _CLASS_CACHE.setdefault(mixin_key, type( base_class.__name__ + str('WithMixins'), # type() requires native str (base_class, ) + mixins, {'unmixed_class': base_class} )) else: return _CLASS_CACHE[mixin_key]
python
def mix(self, cls): """ Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class` """ if hasattr(cls, 'unmixed_class'): base_class = cls.unmixed_class old_mixins = cls.__bases__[1:] # Skip the original unmixed class 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_key not in _CLASS_CACHE: # Only lock if we're about to make a new class with _CLASS_CACHE_LOCK: # Use setdefault so that if someone else has already # created a class before we got the lock, we don't # overwrite it return _CLASS_CACHE.setdefault(mixin_key, type( base_class.__name__ + str('WithMixins'), # type() requires native str (base_class, ) + mixins, {'unmixed_class': base_class} )) else: return _CLASS_CACHE[mixin_key]
[ "def", "mix", "(", "self", ",", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'unmixed_class'", ")", ":", "base_class", "=", "cls", ".", "unmixed_class", "old_mixins", "=", "cls", ".", "__bases__", "[", "1", ":", "]", "# Skip the original unmixed class", "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_key", "not", "in", "_CLASS_CACHE", ":", "# Only lock if we're about to make a new class", "with", "_CLASS_CACHE_LOCK", ":", "# Use setdefault so that if someone else has already", "# created a class before we got the lock, we don't", "# overwrite it", "return", "_CLASS_CACHE", ".", "setdefault", "(", "mixin_key", ",", "type", "(", "base_class", ".", "__name__", "+", "str", "(", "'WithMixins'", ")", ",", "# type() requires native str", "(", "base_class", ",", ")", "+", "mixins", ",", "{", "'unmixed_class'", ":", "base_class", "}", ")", ")", "else", ":", "return", "_CLASS_CACHE", "[", "mixin_key", "]" ]
Returns a subclass of `cls` mixed with `self.mixins`. :param cls: The base class to mix into :type cls: `class`
[ "Returns", "a", "subclass", "of", "cls", "mixed", "with", "self", ".", "mixins", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1219-L1253
train
234,764
edx/XBlock
xblock/runtime.py
RegexLexer.lex
def lex(self, text): """Iterator that tokenizes `text` and yields up tokens as they are found""" for match in self.regex.finditer(text): name = match.lastgroup yield (name, match.group(name))
python
def lex(self, text): """Iterator that tokenizes `text` and yields up tokens as they are found""" for match in self.regex.finditer(text): name = match.lastgroup yield (name, match.group(name))
[ "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
[ "Iterator", "that", "tokenizes", "text", "and", "yields", "up", "tokens", "as", "they", "are", "found" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1264-L1268
train
234,765
edx/XBlock
xblock/runtime.py
NullI18nService.strftime
def strftime(self, dtime, format): # pylint: disable=redefined-builtin """ Locale-aware strftime, with format short-cuts. """ 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 timestring
python
def strftime(self, dtime, format): # pylint: disable=redefined-builtin """ Locale-aware strftime, with format short-cuts. """ 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 timestring
[ "def", "strftime", "(", "self", ",", "dtime", ",", "format", ")", ":", "# pylint: disable=redefined-builtin", "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", "timestring" ]
Locale-aware strftime, with format short-cuts.
[ "Locale", "-", "aware", "strftime", "with", "format", "short", "-", "cuts", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1288-L1298
train
234,766
edx/XBlock
xblock/runtime.py
NullI18nService.ugettext
def ugettext(self): """ Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ugettext else: return self._translations.gettext
python
def ugettext(self): """ Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ugettext else: return self._translations.gettext
[ "def", "ugettext", "(", "self", ")", ":", "# pylint: disable=no-member", "if", "six", ".", "PY2", ":", "return", "self", ".", "_translations", ".", "ugettext", "else", ":", "return", "self", ".", "_translations", ".", "gettext" ]
Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings.
[ "Dispatch", "to", "the", "appropriate", "gettext", "method", "to", "handle", "text", "objects", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1301-L1312
train
234,767
edx/XBlock
xblock/runtime.py
NullI18nService.ungettext
def ungettext(self): """ Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ungettext else: return self._translations.ngettext
python
def ungettext(self): """ Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if six.PY2: return self._translations.ungettext else: return self._translations.ngettext
[ "def", "ungettext", "(", "self", ")", ":", "# pylint: disable=no-member", "if", "six", ".", "PY2", ":", "return", "self", ".", "_translations", ".", "ungettext", "else", ":", "return", "self", ".", "_translations", ".", "ngettext" ]
Dispatch to the appropriate ngettext method to handle text objects. Note that under python 3, this uses `ngettext()`, while under python 2, it uses `ungettext()`. This should not be used with bytestrings.
[ "Dispatch", "to", "the", "appropriate", "ngettext", "method", "to", "handle", "text", "objects", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1315-L1326
train
234,768
edx/XBlock
xblock/reference/plugins.py
FSService.load
def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. """ # TODO: Get xblock from context, once the plumbing is piped through if djpyfs: return djpyfs.get_filesystem(scope_key(instance, xblock)) else: # The reference implementation relies on djpyfs # https://github.com/edx/django-pyfs # For Django runtimes, you may use this reference # implementation. Otherwise, you will need to # patch pyfilesystem yourself to implement get_url. raise NotImplementedError("djpyfs not available")
python
def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. """ # TODO: Get xblock from context, once the plumbing is piped through if djpyfs: return djpyfs.get_filesystem(scope_key(instance, xblock)) else: # The reference implementation relies on djpyfs # https://github.com/edx/django-pyfs # For Django runtimes, you may use this reference # implementation. Otherwise, you will need to # patch pyfilesystem yourself to implement get_url. raise NotImplementedError("djpyfs not available")
[ "def", "load", "(", "self", ",", "instance", ",", "xblock", ")", ":", "# TODO: Get xblock from context, once the plumbing is piped through", "if", "djpyfs", ":", "return", "djpyfs", ".", "get_filesystem", "(", "scope_key", "(", "instance", ",", "xblock", ")", ")", "else", ":", "# The reference implementation relies on djpyfs", "# https://github.com/edx/django-pyfs", "# For Django runtimes, you may use this reference", "# implementation. Otherwise, you will need to", "# patch pyfilesystem yourself to implement get_url.", "raise", "NotImplementedError", "(", "\"djpyfs not available\"", ")" ]
Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped.
[ "Get", "the", "filesystem", "for", "the", "field", "specified", "in", "instance", "and", "the", "xblock", "in", "xblock", "It", "is", "locally", "scoped", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/reference/plugins.py#L190-L205
train
234,769
edx/XBlock
xblock/completable.py
CompletableXBlockMixin.emit_completion
def emit_completion(self, completion_percent): """ Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None """ 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 `completion_mode == 'completable'` (was {})".format( self.has_custom_completion, completion_mode, ) ) if completion_percent is None or not 0.0 <= completion_percent <= 1.0: raise ValueError("Completion percent must be in [0.0; 1.0] interval, {} given".format(completion_percent)) self.runtime.publish( self, 'completion', {'completion': completion_percent}, )
python
def emit_completion(self, completion_percent): """ Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None """ 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 `completion_mode == 'completable'` (was {})".format( self.has_custom_completion, completion_mode, ) ) if completion_percent is None or not 0.0 <= completion_percent <= 1.0: raise ValueError("Completion percent must be in [0.0; 1.0] interval, {} given".format(completion_percent)) self.runtime.publish( self, 'completion', {'completion': completion_percent}, )
[ "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 `completion_mode == 'completable'` (was {})\"", ".", "format", "(", "self", ".", "has_custom_completion", ",", "completion_mode", ",", ")", ")", "if", "completion_percent", "is", "None", "or", "not", "0.0", "<=", "completion_percent", "<=", "1.0", ":", "raise", "ValueError", "(", "\"Completion percent must be in [0.0; 1.0] interval, {} given\"", ".", "format", "(", "completion_percent", ")", ")", "self", ".", "runtime", ".", "publish", "(", "self", ",", "'completion'", ",", "{", "'completion'", ":", "completion_percent", "}", ",", ")" ]
Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), where 0.0 means the block is not completed, 1.0 means the block is fully completed. Returns: None
[ "Emits", "completion", "event", "through", "Completion", "API", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/completable.py#L35-L65
train
234,770
edx/XBlock
xblock/field_data.py
FieldData.has
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str """ try: self.get(block, name) return True except KeyError: return False
python
def has(self, block, name): """ Return whether or not the field named `name` has a non-default value for the XBlock `block`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str """ try: self.get(block, name) return True except KeyError: return False
[ "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`. :param block: block to check :type block: :class:`~xblock.core.XBlock` :param name: field name :type name: str
[ "Return", "whether", "or", "not", "the", "field", "named", "name", "has", "a", "non", "-", "default", "value", "for", "the", "XBlock", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L69-L82
train
234,771
edx/XBlock
xblock/field_data.py
FieldData.set_many
def set_many(self, block, update_dict): """ Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict """ for key, value in six.iteritems(update_dict): self.set(block, key, value)
python
def set_many(self, block, update_dict): """ Update many fields on an XBlock simultaneously. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict """ for key, value in six.iteritems(update_dict): self.set(block, key, value)
[ "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. :param block: the block to update :type block: :class:`~xblock.core.XBlock` :param update_dict: A map of field names to their new values :type update_dict: dict
[ "Update", "many", "fields", "on", "an", "XBlock", "simultaneously", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/field_data.py#L84-L94
train
234,772
edx/XBlock
xblock/exceptions.py
JsonHandlerError.get_response
def get_response(self, **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. """ return Response( json.dumps({"error": self.message}), # pylint: disable=exception-message-attribute status_code=self.status_code, content_type="application/json", charset="utf-8", **kwargs )
python
def get_response(self, **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. """ return Response( json.dumps({"error": self.message}), # pylint: disable=exception-message-attribute status_code=self.status_code, content_type="application/json", charset="utf-8", **kwargs )
[ "def", "get_response", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "Response", "(", "json", ".", "dumps", "(", "{", "\"error\"", ":", "self", ".", "message", "}", ")", ",", "# pylint: disable=exception-message-attribute", "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.
[ "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", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/exceptions.py#L126-L139
train
234,773
edx/XBlock
xblock/mixins.py
HandlersMixin.json_handler
def json_handler(cls, func): """ Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON. """ @cls.handler @functools.wraps(func) def wrapper(self, request, suffix=''): """The wrapper function `json_handler` returns.""" if request.method != "POST": return JsonHandlerError(405, "Method must be POST").get_response(allow=["POST"]) try: request_json = json.loads(request.body) except ValueError: return JsonHandlerError(400, "Invalid JSON").get_response() try: response = func(self, request_json, suffix) except JsonHandlerError as err: return err.get_response() if isinstance(response, Response): return response else: return Response(json.dumps(response), content_type='application/json', charset='utf8') return wrapper
python
def json_handler(cls, func): """ Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON. """ @cls.handler @functools.wraps(func) def wrapper(self, request, suffix=''): """The wrapper function `json_handler` returns.""" if request.method != "POST": return JsonHandlerError(405, "Method must be POST").get_response(allow=["POST"]) try: request_json = json.loads(request.body) except ValueError: return JsonHandlerError(400, "Invalid JSON").get_response() try: response = func(self, request_json, suffix) except JsonHandlerError as err: return err.get_response() if isinstance(response, Response): return response else: return Response(json.dumps(response), content_type='application/json', charset='utf8') return wrapper
[ "def", "json_handler", "(", "cls", ",", "func", ")", ":", "@", "cls", ".", "handler", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "request", ",", "suffix", "=", "''", ")", ":", "\"\"\"The wrapper function `json_handler` returns.\"\"\"", "if", "request", ".", "method", "!=", "\"POST\"", ":", "return", "JsonHandlerError", "(", "405", ",", "\"Method must be POST\"", ")", ".", "get_response", "(", "allow", "=", "[", "\"POST\"", "]", ")", "try", ":", "request_json", "=", "json", ".", "loads", "(", "request", ".", "body", ")", "except", "ValueError", ":", "return", "JsonHandlerError", "(", "400", ",", "\"Invalid JSON\"", ")", ".", "get_response", "(", ")", "try", ":", "response", "=", "func", "(", "self", ",", "request_json", ",", "suffix", ")", "except", "JsonHandlerError", "as", "err", ":", "return", "err", ".", "get_response", "(", ")", "if", "isinstance", "(", "response", ",", "Response", ")", ":", "return", "response", "else", ":", "return", "Response", "(", "json", ".", "dumps", "(", "response", ")", ",", "content_type", "=", "'application/json'", ",", "charset", "=", "'utf8'", ")", "return", "wrapper" ]
Wrap a handler to consume and produce JSON. Rather than a Request object, the method will now be passed the JSON-decoded body of the request. The request should be a POST request in order to use this method. Any data returned by the function will be JSON-encoded and returned as the response. The wrapped function can raise JsonHandlerError to return an error response with a non-200 status code. This decorator will return a 405 HTTP status code if the method is not POST. This decorator will return a 400 status code if the body contains invalid JSON.
[ "Wrap", "a", "handler", "to", "consume", "and", "produce", "JSON", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L40-L75
train
234,774
edx/XBlock
xblock/mixins.py
HandlersMixin.handle
def handle(self, handler_name, request, suffix=''): """Handle `request` with this block's runtime.""" return self.runtime.handle(self, handler_name, request, suffix)
python
def handle(self, handler_name, request, suffix=''): """Handle `request` with this block's runtime.""" return self.runtime.handle(self, handler_name, request, suffix)
[ "def", "handle", "(", "self", ",", "handler_name", ",", "request", ",", "suffix", "=", "''", ")", ":", "return", "self", ".", "runtime", ".", "handle", "(", "self", ",", "handler_name", ",", "request", ",", "suffix", ")" ]
Handle `request` with this block's runtime.
[ "Handle", "request", "with", "this", "block", "s", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L87-L89
train
234,775
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin._combined_services
def _combined_services(cls): # pylint: disable=no-self-argument """ A dictionary that collects all _services_requested by all ancestors of this XBlock class. """ # The class declares what services it desires. To deal with subclasses, # especially mixins, properly, we have to walk up the inheritance # hierarchy, and combine all the declared services into one dictionary. combined = {} for parent in reversed(cls.mro()): combined.update(getattr(parent, "_services_requested", {})) return combined
python
def _combined_services(cls): # pylint: disable=no-self-argument """ A dictionary that collects all _services_requested by all ancestors of this XBlock class. """ # The class declares what services it desires. To deal with subclasses, # especially mixins, properly, we have to walk up the inheritance # hierarchy, and combine all the declared services into one dictionary. combined = {} for parent in reversed(cls.mro()): combined.update(getattr(parent, "_services_requested", {})) return combined
[ "def", "_combined_services", "(", "cls", ")", ":", "# pylint: disable=no-self-argument", "# The class declares what services it desires. To deal with subclasses,", "# especially mixins, properly, we have to walk up the inheritance", "# hierarchy, and combine all the declared services into one dictionary.", "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.
[ "A", "dictionary", "that", "collects", "all", "_services_requested", "by", "all", "ancestors", "of", "this", "XBlock", "class", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L104-L114
train
234,776
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin.needs
def needs(cls, *service_names): """A class decorator to indicate that an XBlock class needs particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "need" # pylint: disable=protected-access return cls_ return _decorator
python
def needs(cls, *service_names): """A class decorator to indicate that an XBlock class needs particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "need" # pylint: disable=protected-access return cls_ return _decorator
[ "def", "needs", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "=", "\"need\"", "# pylint: disable=protected-access", "return", "cls_", "return", "_decorator" ]
A class decorator to indicate that an XBlock class needs particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "needs", "particular", "services", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L127-L133
train
234,777
edx/XBlock
xblock/mixins.py
RuntimeServicesMixin.wants
def wants(cls, *service_names): """A class decorator to indicate that an XBlock class wants particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "want" # pylint: disable=protected-access return cls_ return _decorator
python
def wants(cls, *service_names): """A class decorator to indicate that an XBlock class wants particular services.""" def _decorator(cls_): # pylint: disable=missing-docstring for service_name in service_names: cls_._services_requested[service_name] = "want" # pylint: disable=protected-access return cls_ return _decorator
[ "def", "wants", "(", "cls", ",", "*", "service_names", ")", ":", "def", "_decorator", "(", "cls_", ")", ":", "# pylint: disable=missing-docstring", "for", "service_name", "in", "service_names", ":", "cls_", ".", "_services_requested", "[", "service_name", "]", "=", "\"want\"", "# pylint: disable=protected-access", "return", "cls_", "return", "_decorator" ]
A class decorator to indicate that an XBlock class wants particular services.
[ "A", "class", "decorator", "to", "indicate", "that", "an", "XBlock", "class", "wants", "particular", "services", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L136-L142
train
234,778
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_parent
def get_parent(self): """Return the parent block of this block, or None if there isn't one.""" 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
python
def get_parent(self): """Return the parent block of this block, or None if there isn't one.""" 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
[ "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.
[ "Return", "the", "parent", "block", "of", "this", "block", "or", "None", "if", "there", "isn", "t", "one", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L373-L381
train
234,779
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_child
def get_child(self, usage_id): """Return the child identified by ``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
python
def get_child(self, usage_id): """Return the child identified by ``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
[ "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``.
[ "Return", "the", "child", "identified", "by", "usage_id", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L388-L395
train
234,780
edx/XBlock
xblock/mixins.py
HierarchyMixin.get_children
def get_children(self, usage_id_filter=None): """ Return instantiated XBlocks for each of this blocks ``children``. """ 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) ]
python
def get_children(self, usage_id_filter=None): """ Return instantiated XBlocks for each of this blocks ``children``. """ 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) ]
[ "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``.
[ "Return", "instantiated", "XBlocks", "for", "each", "of", "this", "blocks", "children", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L397-L408
train
234,781
edx/XBlock
xblock/mixins.py
HierarchyMixin.add_children_to_node
def add_children_to_node(self, node): """ Add children to etree.Element `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)
python
def add_children_to_node(self, node): """ Add children to etree.Element `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)
[ "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`.
[ "Add", "children", "to", "etree", ".", "Element", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L416-L423
train
234,782
edx/XBlock
xblock/mixins.py
XmlSerializationMixin.parse_xml
def parse_xml(cls, node, runtime, keys, id_generator): """ Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. keys (:class:`.ScopeIds`): The keys identifying where this block will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block. """ block = runtime.construct_xblock_from_class(cls, keys) # The base implementation: child nodes become child blocks. # Or fields, if they belong to the right namespace. 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"]: cls._set_field_if_present(block, tag, child.text, child.attrib) else: block.runtime.add_node_as_child(block, child, id_generator) # Attributes become fields. for name, value in node.items(): # lxml has no iteritems cls._set_field_if_present(block, name, value, {}) # Text content becomes "content", if such a field exists. if "content" in block.fields and block.fields["content"].scope == Scope.content: text = node.text if text: text = text.strip() if text: block.content = text return block
python
def parse_xml(cls, node, runtime, keys, id_generator): """ Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. keys (:class:`.ScopeIds`): The keys identifying where this block will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block. """ block = runtime.construct_xblock_from_class(cls, keys) # The base implementation: child nodes become child blocks. # Or fields, if they belong to the right namespace. 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"]: cls._set_field_if_present(block, tag, child.text, child.attrib) else: block.runtime.add_node_as_child(block, child, id_generator) # Attributes become fields. for name, value in node.items(): # lxml has no iteritems cls._set_field_if_present(block, name, value, {}) # Text content becomes "content", if such a field exists. if "content" in block.fields and block.fields["content"].scope == Scope.content: text = node.text if text: text = text.strip() if text: block.content = text return block
[ "def", "parse_xml", "(", "cls", ",", "node", ",", "runtime", ",", "keys", ",", "id_generator", ")", ":", "block", "=", "runtime", ".", "construct_xblock_from_class", "(", "cls", ",", "keys", ")", "# The base implementation: child nodes become child blocks.", "# Or fields, if they belong to the right namespace.", "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\"", "]", ":", "cls", ".", "_set_field_if_present", "(", "block", ",", "tag", ",", "child", ".", "text", ",", "child", ".", "attrib", ")", "else", ":", "block", ".", "runtime", ".", "add_node_as_child", "(", "block", ",", "child", ",", "id_generator", ")", "# Attributes become fields.", "for", "name", ",", "value", "in", "node", ".", "items", "(", ")", ":", "# lxml has no iteritems", "cls", ".", "_set_field_if_present", "(", "block", ",", "name", ",", "value", ",", "{", "}", ")", "# Text content becomes \"content\", if such a field exists.", "if", "\"content\"", "in", "block", ".", "fields", "and", "block", ".", "fields", "[", "\"content\"", "]", ".", "scope", "==", "Scope", ".", "content", ":", "text", "=", "node", ".", "text", "if", "text", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "text", ":", "block", ".", "content", "=", "text", "return", "block" ]
Use `node` to construct a new block. Arguments: node (:class:`~xml.etree.ElementTree.Element`): The xml node to parse into an xblock. runtime (:class:`.Runtime`): The runtime to use while parsing. keys (:class:`.ScopeIds`): The keys identifying where this block will store its data. id_generator (:class:`.IdGenerator`): An object that will allow the runtime to generate correct definition and usage ids for children of this block.
[ "Use", "node", "to", "construct", "a", "new", "block", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L432-L477
train
234,783
edx/XBlock
xblock/mixins.py
XmlSerializationMixin.add_xml_to_node
def add_xml_to_node(self, node): """ For exporting, set data on `node` from ourselves. """ # pylint: disable=E1101 # Set node.tag based on our class name. node.tag = self.xml_element_name() node.set('xblock-family', self.entry_point) # Set node attributes based on our fields. 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_field(node, field_name, field) # A content field becomes text content. text = self.xml_text_content() if text is not None: node.text = text
python
def add_xml_to_node(self, node): """ For exporting, set data on `node` from ourselves. """ # pylint: disable=E1101 # Set node.tag based on our class name. node.tag = self.xml_element_name() node.set('xblock-family', self.entry_point) # Set node attributes based on our fields. 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_field(node, field_name, field) # A content field becomes text content. text = self.xml_text_content() if text is not None: node.text = text
[ "def", "add_xml_to_node", "(", "self", ",", "node", ")", ":", "# pylint: disable=E1101", "# Set node.tag based on our class name.", "node", ".", "tag", "=", "self", ".", "xml_element_name", "(", ")", "node", ".", "set", "(", "'xblock-family'", ",", "self", ".", "entry_point", ")", "# Set node attributes based on our fields.", "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_field", "(", "node", ",", "field_name", ",", "field", ")", "# A content field becomes text content.", "text", "=", "self", ".", "xml_text_content", "(", ")", "if", "text", "is", "not", "None", ":", "node", ".", "text", "=", "text" ]
For exporting, set data on `node` from ourselves.
[ "For", "exporting", "set", "data", "on", "node", "from", "ourselves", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L479-L498
train
234,784
edx/XBlock
xblock/mixins.py
XmlSerializationMixin._set_field_if_present
def _set_field_if_present(cls, block, name, value, attrs): """Sets the field block.name, if block have such a field.""" 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 does not contain field %s", type(block), name)
python
def _set_field_if_present(cls, block, name, value, attrs): """Sets the field block.name, if block have such a field.""" 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 does not contain field %s", type(block), name)
[ "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 does not contain field %s\"", ",", "type", "(", "block", ")", ",", "name", ")" ]
Sets the field block.name, if block have such a field.
[ "Sets", "the", "field", "block", ".", "name", "if", "block", "have", "such", "a", "field", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L513-L522
train
234,785
edx/XBlock
xblock/mixins.py
XmlSerializationMixin._add_field
def _add_field(self, node, field_name, field): """ Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node. """ value = field.to_string(field.read_from(self)) text_value = "" if value is None else value # Is the field type supposed to serialize the fact that the value is None to XML? 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.xml_node: # Field will be output to XML as an separate element. tag = etree.QName(XML_NAMESPACES["option"], field_name) elem = etree.SubElement(node, tag, field_attrs) if field.xml_node: # Only set the value if forced via xml_node; # in all other cases, the value is None. # Avoids an unnecessary XML end tag. elem.text = text_value else: # Field will be output to XML as an attribute on the node. node.set(field_name, text_value)
python
def _add_field(self, node, field_name, field): """ Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node. """ value = field.to_string(field.read_from(self)) text_value = "" if value is None else value # Is the field type supposed to serialize the fact that the value is None to XML? 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.xml_node: # Field will be output to XML as an separate element. tag = etree.QName(XML_NAMESPACES["option"], field_name) elem = etree.SubElement(node, tag, field_attrs) if field.xml_node: # Only set the value if forced via xml_node; # in all other cases, the value is None. # Avoids an unnecessary XML end tag. elem.text = text_value else: # Field will be output to XML as an attribute on the node. node.set(field_name, text_value)
[ "def", "_add_field", "(", "self", ",", "node", ",", "field_name", ",", "field", ")", ":", "value", "=", "field", ".", "to_string", "(", "field", ".", "read_from", "(", "self", ")", ")", "text_value", "=", "\"\"", "if", "value", "is", "None", "else", "value", "# Is the field type supposed to serialize the fact that the value is None to XML?", "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", ".", "xml_node", ":", "# Field will be output to XML as an separate element.", "tag", "=", "etree", ".", "QName", "(", "XML_NAMESPACES", "[", "\"option\"", "]", ",", "field_name", ")", "elem", "=", "etree", ".", "SubElement", "(", "node", ",", "tag", ",", "field_attrs", ")", "if", "field", ".", "xml_node", ":", "# Only set the value if forced via xml_node;", "# in all other cases, the value is None.", "# Avoids an unnecessary XML end tag.", "elem", ".", "text", "=", "text_value", "else", ":", "# Field will be output to XML as an attribute on the node.", "node", ".", "set", "(", "field_name", ",", "text_value", ")" ]
Add xml representation of field to node. Depending on settings, it either stores the value of field as an xml attribute or creates a separate child node.
[ "Add", "xml", "representation", "of", "field", "to", "node", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L524-L549
train
234,786
edx/XBlock
xblock/mixins.py
ViewsMixin.supports
def supports(cls, *functionalities): """ A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device". """ def _decorator(view): """ Internal decorator that updates the given view's list of supported functionalities. """ # pylint: disable=protected-access if not hasattr(view, "_supports"): view._supports = set() for functionality in functionalities: view._supports.add(functionality) return view return _decorator
python
def supports(cls, *functionalities): """ A view decorator to indicate that an xBlock view has support for the given functionalities. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device". """ def _decorator(view): """ Internal decorator that updates the given view's list of supported functionalities. """ # pylint: disable=protected-access if not hasattr(view, "_supports"): view._supports = set() for functionality in functionalities: view._supports.add(functionality) return view return _decorator
[ "def", "supports", "(", "cls", ",", "*", "functionalities", ")", ":", "def", "_decorator", "(", "view", ")", ":", "\"\"\"\n Internal decorator that updates the given view's list of supported\n functionalities.\n \"\"\"", "# pylint: disable=protected-access", "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. Arguments: functionalities: String identifiers for the functionalities of the view. For example: "multi_device".
[ "A", "view", "decorator", "to", "indicate", "that", "an", "xBlock", "view", "has", "support", "for", "the", "given", "functionalities", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L572-L592
train
234,787
edx/XBlock
xblock/scorable.py
ScorableXBlockMixin.rescore
def rescore(self, only_if_higher): """ 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. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed the problem. May also raise other errors in self.calculate_score(). Currently unconstrained. """ _ = 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 problem: {}').format(self.location)) new_score = self.calculate_score() self._publish_grade(new_score, only_if_higher)
python
def rescore(self, only_if_higher): """ 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. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed the problem. May also raise other errors in self.calculate_score(). Currently unconstrained. """ _ = 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 problem: {}').format(self.location)) new_score = self.calculate_score() self._publish_grade(new_score, only_if_higher)
[ "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 problem: {}'", ")", ".", "format", "(", "self", ".", "location", ")", ")", "new_score", "=", "self", ".", "calculate_score", "(", ")", "self", ".", "_publish_grade", "(", "new_score", ",", "only_if_higher", ")" ]
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. Raises a TypeError if the block cannot be scored. Raises a ValueError if the user has not yet completed the problem. May also raise other errors in self.calculate_score(). Currently unconstrained.
[ "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", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L34-L55
train
234,788
edx/XBlock
xblock/scorable.py
ScorableXBlockMixin._publish_grade
def _publish_grade(self, score, only_if_higher=None): """ Publish a grade to the runtime. """ grade_dict = { 'value': score.raw_earned, 'max_value': score.raw_possible, 'only_if_higher': only_if_higher, } self.runtime.publish(self, 'grade', grade_dict)
python
def _publish_grade(self, score, only_if_higher=None): """ Publish a grade to the runtime. """ grade_dict = { 'value': score.raw_earned, 'max_value': score.raw_possible, 'only_if_higher': only_if_higher, } self.runtime.publish(self, 'grade', grade_dict)
[ "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.
[ "Publish", "a", "grade", "to", "the", "runtime", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/scorable.py#L108-L117
train
234,789
edx/XBlock
xblock/fields.py
scope_key
def scope_key(instance, xblock): """Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posix allows [A-Z][a-z][0-9]._- We'd like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a """ 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.user_id) else: raise NotImplementedError() if instance.scope.block == BlockScope.TYPE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.block_type) elif instance.scope.block == BlockScope.USAGE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.usage_id) elif instance.scope.block == BlockScope.DEFINITION: scope_key_dict['block'] = six.text_type(xblock.scope_ids.def_id) elif instance.scope.block == BlockScope.ALL: pass else: raise NotImplementedError() replacements = itertools.product("._-", "._-") substitution_list = dict(six.moves.zip("./\\,_ +:-", ("".join(x) for x in replacements))) # Above runs in 4.7us, and generates a list of common substitutions: # {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\': '.-', '_': '__'} key_list = [] def encode(char): """ Replace all non-alphanumeric characters with -n- where n is their Unicode codepoint. TODO: Test for UTF8 which is not ASCII """ if char.isalnum(): return char elif char in substitution_list: return substitution_list[char] else: return "_{}_".format(ord(char)) for item in ['block', 'name', 'user']: if item in scope_key_dict: field = scope_key_dict[item] # Prevent injection of "..", hidden files, or similar. # First part adds a prefix. Second part guarantees # continued uniqueness. if field.startswith(".") or field.startswith("_"): field = "_" + field field = "".join(encode(char) for char in field) else: field = "NONE.NONE" key_list.append(field) key = "/".join(key_list) return key
python
def scope_key(instance, xblock): """Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posix allows [A-Z][a-z][0-9]._- We'd like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a """ 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.user_id) else: raise NotImplementedError() if instance.scope.block == BlockScope.TYPE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.block_type) elif instance.scope.block == BlockScope.USAGE: scope_key_dict['block'] = six.text_type(xblock.scope_ids.usage_id) elif instance.scope.block == BlockScope.DEFINITION: scope_key_dict['block'] = six.text_type(xblock.scope_ids.def_id) elif instance.scope.block == BlockScope.ALL: pass else: raise NotImplementedError() replacements = itertools.product("._-", "._-") substitution_list = dict(six.moves.zip("./\\,_ +:-", ("".join(x) for x in replacements))) # Above runs in 4.7us, and generates a list of common substitutions: # {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\': '.-', '_': '__'} key_list = [] def encode(char): """ Replace all non-alphanumeric characters with -n- where n is their Unicode codepoint. TODO: Test for UTF8 which is not ASCII """ if char.isalnum(): return char elif char in substitution_list: return substitution_list[char] else: return "_{}_".format(ord(char)) for item in ['block', 'name', 'user']: if item in scope_key_dict: field = scope_key_dict[item] # Prevent injection of "..", hidden files, or similar. # First part adds a prefix. Second part guarantees # continued uniqueness. if field.startswith(".") or field.startswith("_"): field = "_" + field field = "".join(encode(char) for char in field) else: field = "NONE.NONE" key_list.append(field) key = "/".join(key_list) return key
[ "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", ".", "user_id", ")", "else", ":", "raise", "NotImplementedError", "(", ")", "if", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "TYPE", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "block_type", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "USAGE", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "usage_id", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "DEFINITION", ":", "scope_key_dict", "[", "'block'", "]", "=", "six", ".", "text_type", "(", "xblock", ".", "scope_ids", ".", "def_id", ")", "elif", "instance", ".", "scope", ".", "block", "==", "BlockScope", ".", "ALL", ":", "pass", "else", ":", "raise", "NotImplementedError", "(", ")", "replacements", "=", "itertools", ".", "product", "(", "\"._-\"", ",", "\"._-\"", ")", "substitution_list", "=", "dict", "(", "six", ".", "moves", ".", "zip", "(", "\"./\\\\,_ +:-\"", ",", "(", "\"\"", ".", "join", "(", "x", ")", "for", "x", "in", "replacements", ")", ")", ")", "# Above runs in 4.7us, and generates a list of common substitutions:", "# {' ': '_-', '+': '-.', '-': '--', ',': '_.', '/': '._', '.': '..', ':': '-_', '\\\\': '.-', '_': '__'}", "key_list", "=", "[", "]", "def", "encode", "(", "char", ")", ":", "\"\"\"\n Replace all non-alphanumeric characters with -n- where n\n is their Unicode codepoint.\n TODO: Test for UTF8 which is not ASCII\n \"\"\"", "if", "char", ".", "isalnum", "(", ")", ":", "return", "char", "elif", "char", "in", "substitution_list", ":", "return", "substitution_list", "[", "char", "]", "else", ":", "return", "\"_{}_\"", ".", "format", "(", "ord", "(", "char", ")", ")", "for", "item", "in", "[", "'block'", ",", "'name'", ",", "'user'", "]", ":", "if", "item", "in", "scope_key_dict", ":", "field", "=", "scope_key_dict", "[", "item", "]", "# Prevent injection of \"..\", hidden files, or similar.", "# First part adds a prefix. Second part guarantees", "# continued uniqueness.", "if", "field", ".", "startswith", "(", "\".\"", ")", "or", "field", ".", "startswith", "(", "\"_\"", ")", ":", "field", "=", "\"_\"", "+", "field", "field", "=", "\"\"", ".", "join", "(", "encode", "(", "char", ")", "for", "char", "in", "field", ")", "else", ":", "field", "=", "\"NONE.NONE\"", "key_list", ".", "append", "(", "field", ")", "key", "=", "\"/\"", ".", "join", "(", "key_list", ")", "return", "key" ]
Generate a unique key for a scope that can be used as a filename, in a URL, or in a KVS. Our goal is to have a pretty, human-readable 1:1 encoding. This encoding is as good as we can do. It's reversible, but not trivial to reverse. Encoding scheme: Posix allows [A-Z][a-z][0-9]._- We'd like to have a _concise_ representation for common punctuation We're okay with a _non-concise_ representation for repeated or uncommon characters We keep [A-z][a-z][0-9] as is. We encode other common punctuation as pairs of ._-. This gives a total of 3*3=9 combinations. We're pretty careful to keep this nice. Where possible, we double characters. The most common other character (' ' and ':') are encoded as _- and -_ We separate field portions with /. This gives a natural directory tree. This is nice in URLs and filenames (although not so nice in urls.py) If a field starts with punctuatation, we prefix a _. This prevents hidden files. Uncommon characters, we encode as their ordinal value, surrounded by -. For example, tilde would be -126-. If a field is not used, we call it NONE.NONE. This does not conflict with fields with the same name, since they are escaped to NONE..NONE. Sample keys: Settings scope: animationxblock..animation..d0..u0/settings__fs/NONE.NONE User summary scope: animationxblock..animation..d0..u0/uss__fs/NONE.NONE User preferences, username is Aan.!a animation/pref__fs/Aan.._33_a
[ "Generate", "a", "unique", "key", "for", "a", "scope", "that", "can", "be", "used", "as", "a", "filename", "in", "a", "URL", "or", "in", "a", "KVS", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L1045-L1138
train
234,790
edx/XBlock
xblock/fields.py
Field.default
def default(self): """Returns the static value that this defaults to.""" if self.MUTABLE: return copy.deepcopy(self._default) else: return self._default
python
def default(self): """Returns the static value that this defaults to.""" if self.MUTABLE: return copy.deepcopy(self._default) else: return self._default
[ "def", "default", "(", "self", ")", ":", "if", "self", ".", "MUTABLE", ":", "return", "copy", ".", "deepcopy", "(", "self", ".", "_default", ")", "else", ":", "return", "self", ".", "_default" ]
Returns the static value that this defaults to.
[ "Returns", "the", "static", "value", "that", "this", "defaults", "to", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L342-L347
train
234,791
edx/XBlock
xblock/fields.py
Field._set_cached_value
def _set_cached_value(self, xblock, value): """Store a value in the xblock's cache, creating the cache if necessary.""" # pylint: disable=protected-access if not hasattr(xblock, '_field_data_cache'): xblock._field_data_cache = {} xblock._field_data_cache[self.name] = value
python
def _set_cached_value(self, xblock, value): """Store a value in the xblock's cache, creating the cache if necessary.""" # pylint: disable=protected-access if not hasattr(xblock, '_field_data_cache'): xblock._field_data_cache = {} xblock._field_data_cache[self.name] = value
[ "def", "_set_cached_value", "(", "self", ",", "xblock", ",", "value", ")", ":", "# pylint: disable=protected-access", "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.
[ "Store", "a", "value", "in", "the", "xblock", "s", "cache", "creating", "the", "cache", "if", "necessary", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L404-L409
train
234,792
edx/XBlock
xblock/fields.py
Field._del_cached_value
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
python
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
[ "def", "_del_cached_value", "(", "self", ",", "xblock", ")", ":", "# pylint: disable=protected-access", "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.
[ "Remove", "a", "value", "from", "the", "xblock", "s", "cache", "if", "the", "cache", "exists", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L411-L415
train
234,793
edx/XBlock
xblock/fields.py
Field._mark_dirty
def _mark_dirty(self, xblock, value): """Set this field to dirty on the xblock.""" # pylint: disable=protected-access # Deep copy the value being marked as dirty, so that there # is a baseline to check against when saving later if self not in xblock._dirty_fields: xblock._dirty_fields[self] = copy.deepcopy(value)
python
def _mark_dirty(self, xblock, value): """Set this field to dirty on the xblock.""" # pylint: disable=protected-access # Deep copy the value being marked as dirty, so that there # is a baseline to check against when saving later if self not in xblock._dirty_fields: xblock._dirty_fields[self] = copy.deepcopy(value)
[ "def", "_mark_dirty", "(", "self", ",", "xblock", ",", "value", ")", ":", "# pylint: disable=protected-access", "# Deep copy the value being marked as dirty, so that there", "# is a baseline to check against when saving later", "if", "self", "not", "in", "xblock", ".", "_dirty_fields", ":", "xblock", ".", "_dirty_fields", "[", "self", "]", "=", "copy", ".", "deepcopy", "(", "value", ")" ]
Set this field to dirty on the xblock.
[ "Set", "this", "field", "to", "dirty", "on", "the", "xblock", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L417-L424
train
234,794
edx/XBlock
xblock/fields.py
Field._check_or_enforce_type
def _check_or_enforce_type(self, value): """ 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 To aid with migration, enable the warnings with: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning) """ if self._enable_enforce_type: return self.enforce_type(value) try: new_value = self.enforce_type(value) except: # pylint: disable=bare-except message = "The value {!r} could not be enforced ({})".format( value, traceback.format_exc().splitlines()[-1]) warnings.warn(message, FailingEnforceTypeWarning, stacklevel=3) else: try: equal = value == new_value except TypeError: equal = False if not equal: message = "The value {!r} would be enforced to {!r}".format( value, new_value) warnings.warn(message, ModifyingEnforceTypeWarning, stacklevel=3) return value
python
def _check_or_enforce_type(self, value): """ 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 To aid with migration, enable the warnings with: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning) """ if self._enable_enforce_type: return self.enforce_type(value) try: new_value = self.enforce_type(value) except: # pylint: disable=bare-except message = "The value {!r} could not be enforced ({})".format( value, traceback.format_exc().splitlines()[-1]) warnings.warn(message, FailingEnforceTypeWarning, stacklevel=3) else: try: equal = value == new_value except TypeError: equal = False if not equal: message = "The value {!r} would be enforced to {!r}".format( value, new_value) warnings.warn(message, ModifyingEnforceTypeWarning, stacklevel=3) return value
[ "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", ":", "# pylint: disable=bare-except", "message", "=", "\"The value {!r} could not be enforced ({})\"", ".", "format", "(", "value", ",", "traceback", ".", "format_exc", "(", ")", ".", "splitlines", "(", ")", "[", "-", "1", "]", ")", "warnings", ".", "warn", "(", "message", ",", "FailingEnforceTypeWarning", ",", "stacklevel", "=", "3", ")", "else", ":", "try", ":", "equal", "=", "value", "==", "new_value", "except", "TypeError", ":", "equal", "=", "False", "if", "not", "equal", ":", "message", "=", "\"The value {!r} would be enforced to {!r}\"", ".", "format", "(", "value", ",", "new_value", ")", "warnings", ".", "warn", "(", "message", ",", "ModifyingEnforceTypeWarning", ",", "stacklevel", "=", "3", ")", "return", "value" ]
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 To aid with migration, enable the warnings with: warnings.simplefilter("always", FailingEnforceTypeWarning) warnings.simplefilter("always", ModifyingEnforceTypeWarning)
[ "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" ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L443-L472
train
234,795
edx/XBlock
xblock/fields.py
Field._calculate_unique_id
def _calculate_unique_id(self, xblock): """ Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope. """ key = scope_key(self, xblock) return hashlib.sha1(key.encode('utf-8')).hexdigest()
python
def _calculate_unique_id(self, xblock): """ Provide a default value for fields with `default=UNIQUE_ID`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope. """ key = scope_key(self, xblock) return hashlib.sha1(key.encode('utf-8')).hexdigest()
[ "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`. Returned string is a SHA1 hex digest that is deterministically calculated for the field in its given scope.
[ "Provide", "a", "default", "value", "for", "fields", "with", "default", "=", "UNIQUE_ID", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L474-L482
train
234,796
edx/XBlock
xblock/fields.py
Field._get_default_value_to_cache
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access 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
python
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access 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
[ "def", "_get_default_value_to_cache", "(", "self", ",", "xblock", ")", ":", "try", ":", "# pylint: disable=protected-access", "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.
[ "Perform", "special", "logic", "to", "provide", "a", "field", "s", "default", "value", "for", "caching", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L484-L495
train
234,797
edx/XBlock
xblock/fields.py
Field._warn_deprecated_outside_JSONField
def _warn_deprecated_outside_JSONField(self): # pylint: disable=invalid-name """Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class. """ 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
python
def _warn_deprecated_outside_JSONField(self): # pylint: disable=invalid-name """Certain methods will be moved to JSONField. This warning marks calls when the object is not derived from that class. """ 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
[ "def", "_warn_deprecated_outside_JSONField", "(", "self", ")", ":", "# pylint: disable=invalid-name", "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. This warning marks calls when the object is not derived from that class.
[ "Certain", "methods", "will", "be", "moved", "to", "JSONField", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L589-L601
train
234,798
edx/XBlock
xblock/fields.py
Field.to_string
def to_string(self, value): """ Return a JSON serialized string representation of the value. """ self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ) return value
python
def to_string(self, value): """ Return a JSON serialized string representation of the value. """ self._warn_deprecated_outside_JSONField() value = json.dumps( self.to_json(value), indent=2, sort_keys=True, separators=(',', ': '), ) return value
[ "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.
[ "Return", "a", "JSON", "serialized", "string", "representation", "of", "the", "value", "." ]
368bf46e2c0ee69bbb21817f428c4684936e18ee
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L624-L635
train
234,799