id
int32 0
252k
| 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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
1,800 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.get_create_options | def get_create_options(self):
"""Returns valid options for ordering hardware."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# Sizes
sizes = []
for preset in package['activePresets'] + package['accountRestrictedActivePresets']:
sizes.append({
'name': preset['description'],
'key': preset['keyName']
})
# Operating systems
operating_systems = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == 'os':
operating_systems.append({
'name': item['softwareDescription']['longDescription'],
'key': item['softwareDescription']['referenceCode'],
})
# Port speeds
port_speeds = []
for item in package['items']:
if all([item['itemCategory']['categoryCode'] == 'port_speed',
# Hide private options
not _is_private_port_speed_item(item),
# Hide unbonded options
_is_bonded(item)]):
port_speeds.append({
'name': item['description'],
'key': item['capacity'],
})
# Extras
extras = []
for item in package['items']:
if item['itemCategory']['categoryCode'] in EXTRA_CATEGORIES:
extras.append({
'name': item['description'],
'key': item['keyName']
})
return {
'locations': locations,
'sizes': sizes,
'operating_systems': operating_systems,
'port_speeds': port_speeds,
'extras': extras,
} | python | def get_create_options(self):
"""Returns valid options for ordering hardware."""
package = self._get_package()
# Locations
locations = []
for region in package['regions']:
locations.append({
'name': region['location']['location']['longName'],
'key': region['location']['location']['name'],
})
# Sizes
sizes = []
for preset in package['activePresets'] + package['accountRestrictedActivePresets']:
sizes.append({
'name': preset['description'],
'key': preset['keyName']
})
# Operating systems
operating_systems = []
for item in package['items']:
if item['itemCategory']['categoryCode'] == 'os':
operating_systems.append({
'name': item['softwareDescription']['longDescription'],
'key': item['softwareDescription']['referenceCode'],
})
# Port speeds
port_speeds = []
for item in package['items']:
if all([item['itemCategory']['categoryCode'] == 'port_speed',
# Hide private options
not _is_private_port_speed_item(item),
# Hide unbonded options
_is_bonded(item)]):
port_speeds.append({
'name': item['description'],
'key': item['capacity'],
})
# Extras
extras = []
for item in package['items']:
if item['itemCategory']['categoryCode'] in EXTRA_CATEGORIES:
extras.append({
'name': item['description'],
'key': item['keyName']
})
return {
'locations': locations,
'sizes': sizes,
'operating_systems': operating_systems,
'port_speeds': port_speeds,
'extras': extras,
} | [
"def",
"get_create_options",
"(",
"self",
")",
":",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"# Locations",
"locations",
"=",
"[",
"]",
"for",
"region",
"in",
"package",
"[",
"'regions'",
"]",
":",
"locations",
".",
"append",
"(",
"{",
"'name'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'longName'",
"]",
",",
"'key'",
":",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'name'",
"]",
",",
"}",
")",
"# Sizes",
"sizes",
"=",
"[",
"]",
"for",
"preset",
"in",
"package",
"[",
"'activePresets'",
"]",
"+",
"package",
"[",
"'accountRestrictedActivePresets'",
"]",
":",
"sizes",
".",
"append",
"(",
"{",
"'name'",
":",
"preset",
"[",
"'description'",
"]",
",",
"'key'",
":",
"preset",
"[",
"'keyName'",
"]",
"}",
")",
"# Operating systems",
"operating_systems",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"==",
"'os'",
":",
"operating_systems",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'softwareDescription'",
"]",
"[",
"'longDescription'",
"]",
",",
"'key'",
":",
"item",
"[",
"'softwareDescription'",
"]",
"[",
"'referenceCode'",
"]",
",",
"}",
")",
"# Port speeds",
"port_speeds",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"all",
"(",
"[",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"==",
"'port_speed'",
",",
"# Hide private options",
"not",
"_is_private_port_speed_item",
"(",
"item",
")",
",",
"# Hide unbonded options",
"_is_bonded",
"(",
"item",
")",
"]",
")",
":",
"port_speeds",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'description'",
"]",
",",
"'key'",
":",
"item",
"[",
"'capacity'",
"]",
",",
"}",
")",
"# Extras",
"extras",
"=",
"[",
"]",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
"in",
"EXTRA_CATEGORIES",
":",
"extras",
".",
"append",
"(",
"{",
"'name'",
":",
"item",
"[",
"'description'",
"]",
",",
"'key'",
":",
"item",
"[",
"'keyName'",
"]",
"}",
")",
"return",
"{",
"'locations'",
":",
"locations",
",",
"'sizes'",
":",
"sizes",
",",
"'operating_systems'",
":",
"operating_systems",
",",
"'port_speeds'",
":",
"port_speeds",
",",
"'extras'",
":",
"extras",
",",
"}"
] | Returns valid options for ordering hardware. | [
"Returns",
"valid",
"options",
"for",
"ordering",
"hardware",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L377-L435 |
1,801 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._get_package | def _get_package(self):
"""Get the package related to simple hardware ordering."""
mask = '''
items[
keyName,
capacity,
description,
attributes[id,attributeTypeKeyName],
itemCategory[id,categoryCode],
softwareDescription[id,referenceCode,longDescription],
prices
],
activePresets,
accountRestrictedActivePresets,
regions[location[location[priceGroups]]]
'''
package_keyname = 'BARE_METAL_SERVER'
package = self.ordering_manager.get_package_by_key(package_keyname, mask=mask)
return package | python | def _get_package(self):
"""Get the package related to simple hardware ordering."""
mask = '''
items[
keyName,
capacity,
description,
attributes[id,attributeTypeKeyName],
itemCategory[id,categoryCode],
softwareDescription[id,referenceCode,longDescription],
prices
],
activePresets,
accountRestrictedActivePresets,
regions[location[location[priceGroups]]]
'''
package_keyname = 'BARE_METAL_SERVER'
package = self.ordering_manager.get_package_by_key(package_keyname, mask=mask)
return package | [
"def",
"_get_package",
"(",
"self",
")",
":",
"mask",
"=",
"'''\n items[\n keyName,\n capacity,\n description,\n attributes[id,attributeTypeKeyName],\n itemCategory[id,categoryCode],\n softwareDescription[id,referenceCode,longDescription],\n prices\n ],\n activePresets,\n accountRestrictedActivePresets,\n regions[location[location[priceGroups]]]\n '''",
"package_keyname",
"=",
"'BARE_METAL_SERVER'",
"package",
"=",
"self",
".",
"ordering_manager",
".",
"get_package_by_key",
"(",
"package_keyname",
",",
"mask",
"=",
"mask",
")",
"return",
"package"
] | Get the package related to simple hardware ordering. | [
"Get",
"the",
"package",
"related",
"to",
"simple",
"hardware",
"ordering",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L438-L457 |
1,802 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._generate_create_dict | def _generate_create_dict(self,
size=None,
hostname=None,
domain=None,
location=None,
os=None,
port_speed=None,
ssh_keys=None,
post_uri=None,
hourly=True,
no_public=False,
extras=None):
"""Translates arguments into a dictionary for creating a server."""
extras = extras or []
package = self._get_package()
location = _get_location(package, location)
prices = []
for category in ['pri_ip_addresses',
'vpn_management',
'remote_management']:
prices.append(_get_default_price_id(package['items'],
option=category,
hourly=hourly,
location=location))
prices.append(_get_os_price_id(package['items'], os,
location=location))
prices.append(_get_bandwidth_price_id(package['items'],
hourly=hourly,
no_public=no_public,
location=location))
prices.append(_get_port_speed_price_id(package['items'],
port_speed,
no_public,
location=location))
for extra in extras:
prices.append(_get_extra_price_id(package['items'],
extra, hourly,
location=location))
hardware = {
'hostname': hostname,
'domain': domain,
}
order = {
'hardware': [hardware],
'location': location['keyname'],
'prices': [{'id': price} for price in prices],
'packageId': package['id'],
'presetId': _get_preset_id(package, size),
'useHourlyPricing': hourly,
}
if post_uri:
order['provisionScripts'] = [post_uri]
if ssh_keys:
order['sshKeys'] = [{'sshKeyIds': ssh_keys}]
return order | python | def _generate_create_dict(self,
size=None,
hostname=None,
domain=None,
location=None,
os=None,
port_speed=None,
ssh_keys=None,
post_uri=None,
hourly=True,
no_public=False,
extras=None):
"""Translates arguments into a dictionary for creating a server."""
extras = extras or []
package = self._get_package()
location = _get_location(package, location)
prices = []
for category in ['pri_ip_addresses',
'vpn_management',
'remote_management']:
prices.append(_get_default_price_id(package['items'],
option=category,
hourly=hourly,
location=location))
prices.append(_get_os_price_id(package['items'], os,
location=location))
prices.append(_get_bandwidth_price_id(package['items'],
hourly=hourly,
no_public=no_public,
location=location))
prices.append(_get_port_speed_price_id(package['items'],
port_speed,
no_public,
location=location))
for extra in extras:
prices.append(_get_extra_price_id(package['items'],
extra, hourly,
location=location))
hardware = {
'hostname': hostname,
'domain': domain,
}
order = {
'hardware': [hardware],
'location': location['keyname'],
'prices': [{'id': price} for price in prices],
'packageId': package['id'],
'presetId': _get_preset_id(package, size),
'useHourlyPricing': hourly,
}
if post_uri:
order['provisionScripts'] = [post_uri]
if ssh_keys:
order['sshKeys'] = [{'sshKeyIds': ssh_keys}]
return order | [
"def",
"_generate_create_dict",
"(",
"self",
",",
"size",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"location",
"=",
"None",
",",
"os",
"=",
"None",
",",
"port_speed",
"=",
"None",
",",
"ssh_keys",
"=",
"None",
",",
"post_uri",
"=",
"None",
",",
"hourly",
"=",
"True",
",",
"no_public",
"=",
"False",
",",
"extras",
"=",
"None",
")",
":",
"extras",
"=",
"extras",
"or",
"[",
"]",
"package",
"=",
"self",
".",
"_get_package",
"(",
")",
"location",
"=",
"_get_location",
"(",
"package",
",",
"location",
")",
"prices",
"=",
"[",
"]",
"for",
"category",
"in",
"[",
"'pri_ip_addresses'",
",",
"'vpn_management'",
",",
"'remote_management'",
"]",
":",
"prices",
".",
"append",
"(",
"_get_default_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"option",
"=",
"category",
",",
"hourly",
"=",
"hourly",
",",
"location",
"=",
"location",
")",
")",
"prices",
".",
"append",
"(",
"_get_os_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"os",
",",
"location",
"=",
"location",
")",
")",
"prices",
".",
"append",
"(",
"_get_bandwidth_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"hourly",
"=",
"hourly",
",",
"no_public",
"=",
"no_public",
",",
"location",
"=",
"location",
")",
")",
"prices",
".",
"append",
"(",
"_get_port_speed_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"port_speed",
",",
"no_public",
",",
"location",
"=",
"location",
")",
")",
"for",
"extra",
"in",
"extras",
":",
"prices",
".",
"append",
"(",
"_get_extra_price_id",
"(",
"package",
"[",
"'items'",
"]",
",",
"extra",
",",
"hourly",
",",
"location",
"=",
"location",
")",
")",
"hardware",
"=",
"{",
"'hostname'",
":",
"hostname",
",",
"'domain'",
":",
"domain",
",",
"}",
"order",
"=",
"{",
"'hardware'",
":",
"[",
"hardware",
"]",
",",
"'location'",
":",
"location",
"[",
"'keyname'",
"]",
",",
"'prices'",
":",
"[",
"{",
"'id'",
":",
"price",
"}",
"for",
"price",
"in",
"prices",
"]",
",",
"'packageId'",
":",
"package",
"[",
"'id'",
"]",
",",
"'presetId'",
":",
"_get_preset_id",
"(",
"package",
",",
"size",
")",
",",
"'useHourlyPricing'",
":",
"hourly",
",",
"}",
"if",
"post_uri",
":",
"order",
"[",
"'provisionScripts'",
"]",
"=",
"[",
"post_uri",
"]",
"if",
"ssh_keys",
":",
"order",
"[",
"'sshKeys'",
"]",
"=",
"[",
"{",
"'sshKeyIds'",
":",
"ssh_keys",
"}",
"]",
"return",
"order"
] | Translates arguments into a dictionary for creating a server. | [
"Translates",
"arguments",
"into",
"a",
"dictionary",
"for",
"creating",
"a",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L459-L523 |
1,803 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._get_ids_from_hostname | def _get_ids_from_hostname(self, hostname):
"""Returns list of matching hardware IDs for a given hostname."""
results = self.list_hardware(hostname=hostname, mask="id")
return [result['id'] for result in results] | python | def _get_ids_from_hostname(self, hostname):
"""Returns list of matching hardware IDs for a given hostname."""
results = self.list_hardware(hostname=hostname, mask="id")
return [result['id'] for result in results] | [
"def",
"_get_ids_from_hostname",
"(",
"self",
",",
"hostname",
")",
":",
"results",
"=",
"self",
".",
"list_hardware",
"(",
"hostname",
"=",
"hostname",
",",
"mask",
"=",
"\"id\"",
")",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"]"
] | Returns list of matching hardware IDs for a given hostname. | [
"Returns",
"list",
"of",
"matching",
"hardware",
"IDs",
"for",
"a",
"given",
"hostname",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L525-L528 |
1,804 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager._get_ids_from_ip | def _get_ids_from_ip(self, ip): # pylint: disable=inconsistent-return-statements
"""Returns list of matching hardware IDs for a given ip address."""
try:
# Does it look like an ip address?
socket.inet_aton(ip)
except socket.error:
return []
# Find the server via ip address. First try public ip, then private
results = self.list_hardware(public_ip=ip, mask="id")
if results:
return [result['id'] for result in results]
results = self.list_hardware(private_ip=ip, mask="id")
if results:
return [result['id'] for result in results] | python | def _get_ids_from_ip(self, ip): # pylint: disable=inconsistent-return-statements
"""Returns list of matching hardware IDs for a given ip address."""
try:
# Does it look like an ip address?
socket.inet_aton(ip)
except socket.error:
return []
# Find the server via ip address. First try public ip, then private
results = self.list_hardware(public_ip=ip, mask="id")
if results:
return [result['id'] for result in results]
results = self.list_hardware(private_ip=ip, mask="id")
if results:
return [result['id'] for result in results] | [
"def",
"_get_ids_from_ip",
"(",
"self",
",",
"ip",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"try",
":",
"# Does it look like an ip address?",
"socket",
".",
"inet_aton",
"(",
"ip",
")",
"except",
"socket",
".",
"error",
":",
"return",
"[",
"]",
"# Find the server via ip address. First try public ip, then private",
"results",
"=",
"self",
".",
"list_hardware",
"(",
"public_ip",
"=",
"ip",
",",
"mask",
"=",
"\"id\"",
")",
"if",
"results",
":",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"]",
"results",
"=",
"self",
".",
"list_hardware",
"(",
"private_ip",
"=",
"ip",
",",
"mask",
"=",
"\"id\"",
")",
"if",
"results",
":",
"return",
"[",
"result",
"[",
"'id'",
"]",
"for",
"result",
"in",
"results",
"]"
] | Returns list of matching hardware IDs for a given ip address. | [
"Returns",
"list",
"of",
"matching",
"hardware",
"IDs",
"for",
"a",
"given",
"ip",
"address",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L530-L545 |
1,805 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.edit | def edit(self, hardware_id, userdata=None, hostname=None, domain=None,
notes=None, tags=None):
"""Edit hostname, domain name, notes, user data of the hardware.
Parameters set to None will be ignored and not attempted to be updated.
:param integer hardware_id: the instance ID to edit
:param string userdata: user data on the hardware to edit.
If none exist it will be created
:param string hostname: valid hostname
:param string domain: valid domain name
:param string notes: notes about this particular hardware
:param string tags: tags to set on the hardware as a comma separated
list. Use the empty string to remove all tags.
Example::
# Change the hostname on instance 12345 to 'something'
result = mgr.edit(hardware_id=12345 , hostname="something")
#result will be True or an Exception
"""
obj = {}
if userdata:
self.hardware.setUserMetadata([userdata], id=hardware_id)
if tags is not None:
self.hardware.setTags(tags, id=hardware_id)
if hostname:
obj['hostname'] = hostname
if domain:
obj['domain'] = domain
if notes:
obj['notes'] = notes
if not obj:
return True
return self.hardware.editObject(obj, id=hardware_id) | python | def edit(self, hardware_id, userdata=None, hostname=None, domain=None,
notes=None, tags=None):
"""Edit hostname, domain name, notes, user data of the hardware.
Parameters set to None will be ignored and not attempted to be updated.
:param integer hardware_id: the instance ID to edit
:param string userdata: user data on the hardware to edit.
If none exist it will be created
:param string hostname: valid hostname
:param string domain: valid domain name
:param string notes: notes about this particular hardware
:param string tags: tags to set on the hardware as a comma separated
list. Use the empty string to remove all tags.
Example::
# Change the hostname on instance 12345 to 'something'
result = mgr.edit(hardware_id=12345 , hostname="something")
#result will be True or an Exception
"""
obj = {}
if userdata:
self.hardware.setUserMetadata([userdata], id=hardware_id)
if tags is not None:
self.hardware.setTags(tags, id=hardware_id)
if hostname:
obj['hostname'] = hostname
if domain:
obj['domain'] = domain
if notes:
obj['notes'] = notes
if not obj:
return True
return self.hardware.editObject(obj, id=hardware_id) | [
"def",
"edit",
"(",
"self",
",",
"hardware_id",
",",
"userdata",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"notes",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"obj",
"=",
"{",
"}",
"if",
"userdata",
":",
"self",
".",
"hardware",
".",
"setUserMetadata",
"(",
"[",
"userdata",
"]",
",",
"id",
"=",
"hardware_id",
")",
"if",
"tags",
"is",
"not",
"None",
":",
"self",
".",
"hardware",
".",
"setTags",
"(",
"tags",
",",
"id",
"=",
"hardware_id",
")",
"if",
"hostname",
":",
"obj",
"[",
"'hostname'",
"]",
"=",
"hostname",
"if",
"domain",
":",
"obj",
"[",
"'domain'",
"]",
"=",
"domain",
"if",
"notes",
":",
"obj",
"[",
"'notes'",
"]",
"=",
"notes",
"if",
"not",
"obj",
":",
"return",
"True",
"return",
"self",
".",
"hardware",
".",
"editObject",
"(",
"obj",
",",
"id",
"=",
"hardware_id",
")"
] | Edit hostname, domain name, notes, user data of the hardware.
Parameters set to None will be ignored and not attempted to be updated.
:param integer hardware_id: the instance ID to edit
:param string userdata: user data on the hardware to edit.
If none exist it will be created
:param string hostname: valid hostname
:param string domain: valid domain name
:param string notes: notes about this particular hardware
:param string tags: tags to set on the hardware as a comma separated
list. Use the empty string to remove all tags.
Example::
# Change the hostname on instance 12345 to 'something'
result = mgr.edit(hardware_id=12345 , hostname="something")
#result will be True or an Exception | [
"Edit",
"hostname",
"domain",
"name",
"notes",
"user",
"data",
"of",
"the",
"hardware",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L547-L588 |
1,806 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.update_firmware | def update_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True,
hard_drive=True):
"""Update hardware firmware.
This will cause the server to be unavailable for ~20 minutes.
:param int hardware_id: The ID of the hardware to have its firmware
updated.
:param bool ipmi: Update the ipmi firmware.
:param bool raid_controller: Update the raid controller firmware.
:param bool bios: Update the bios firmware.
:param bool hard_drive: Update the hard drive firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.update_firmware(hardware_id=1234)
"""
return self.hardware.createFirmwareUpdateTransaction(
bool(ipmi), bool(raid_controller), bool(bios), bool(hard_drive), id=hardware_id) | python | def update_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True,
hard_drive=True):
"""Update hardware firmware.
This will cause the server to be unavailable for ~20 minutes.
:param int hardware_id: The ID of the hardware to have its firmware
updated.
:param bool ipmi: Update the ipmi firmware.
:param bool raid_controller: Update the raid controller firmware.
:param bool bios: Update the bios firmware.
:param bool hard_drive: Update the hard drive firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.update_firmware(hardware_id=1234)
"""
return self.hardware.createFirmwareUpdateTransaction(
bool(ipmi), bool(raid_controller), bool(bios), bool(hard_drive), id=hardware_id) | [
"def",
"update_firmware",
"(",
"self",
",",
"hardware_id",
",",
"ipmi",
"=",
"True",
",",
"raid_controller",
"=",
"True",
",",
"bios",
"=",
"True",
",",
"hard_drive",
"=",
"True",
")",
":",
"return",
"self",
".",
"hardware",
".",
"createFirmwareUpdateTransaction",
"(",
"bool",
"(",
"ipmi",
")",
",",
"bool",
"(",
"raid_controller",
")",
",",
"bool",
"(",
"bios",
")",
",",
"bool",
"(",
"hard_drive",
")",
",",
"id",
"=",
"hardware_id",
")"
] | Update hardware firmware.
This will cause the server to be unavailable for ~20 minutes.
:param int hardware_id: The ID of the hardware to have its firmware
updated.
:param bool ipmi: Update the ipmi firmware.
:param bool raid_controller: Update the raid controller firmware.
:param bool bios: Update the bios firmware.
:param bool hard_drive: Update the hard drive firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.update_firmware(hardware_id=1234) | [
"Update",
"hardware",
"firmware",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L590-L614 |
1,807 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.reflash_firmware | def reflash_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True):
"""Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have its firmware
reflashed.
:param bool ipmi: Reflash the ipmi firmware.
:param bool raid_controller: Reflash the raid controller firmware.
:param bool bios: Reflash the bios firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.reflash_firmware(hardware_id=1234)
"""
return self.hardware.createFirmwareReflashTransaction(
bool(ipmi), bool(raid_controller), bool(bios), id=hardware_id) | python | def reflash_firmware(self,
hardware_id,
ipmi=True,
raid_controller=True,
bios=True):
"""Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have its firmware
reflashed.
:param bool ipmi: Reflash the ipmi firmware.
:param bool raid_controller: Reflash the raid controller firmware.
:param bool bios: Reflash the bios firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.reflash_firmware(hardware_id=1234)
"""
return self.hardware.createFirmwareReflashTransaction(
bool(ipmi), bool(raid_controller), bool(bios), id=hardware_id) | [
"def",
"reflash_firmware",
"(",
"self",
",",
"hardware_id",
",",
"ipmi",
"=",
"True",
",",
"raid_controller",
"=",
"True",
",",
"bios",
"=",
"True",
")",
":",
"return",
"self",
".",
"hardware",
".",
"createFirmwareReflashTransaction",
"(",
"bool",
"(",
"ipmi",
")",
",",
"bool",
"(",
"raid_controller",
")",
",",
"bool",
"(",
"bios",
")",
",",
"id",
"=",
"hardware_id",
")"
] | Reflash hardware firmware.
This will cause the server to be unavailable for ~60 minutes.
The firmware will not be upgraded but rather reflashed to the version installed.
:param int hardware_id: The ID of the hardware to have its firmware
reflashed.
:param bool ipmi: Reflash the ipmi firmware.
:param bool raid_controller: Reflash the raid controller firmware.
:param bool bios: Reflash the bios firmware.
Example::
# Check the servers active transactions to see progress
result = mgr.reflash_firmware(hardware_id=1234) | [
"Reflash",
"hardware",
"firmware",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L616-L639 |
1,808 | softlayer/softlayer-python | SoftLayer/managers/hardware.py | HardwareManager.wait_for_ready | def wait_for_ready(self, instance_id, limit=14400, delay=10, pending=False):
"""Determine if a Server is ready.
A server is ready when no transactions are running on it.
:param int instance_id: The instance ID with the pending transaction
:param int limit: The maximum amount of seconds to wait.
:param int delay: The number of seconds to sleep before checks. Defaults to 10.
"""
now = time.time()
until = now + limit
mask = "mask[id, lastOperatingSystemReload[id], activeTransaction, provisionDate]"
instance = self.get_hardware(instance_id, mask=mask)
while now <= until:
if utils.is_ready(instance, pending):
return True
transaction = utils.lookup(instance, 'activeTransaction', 'transactionStatus', 'friendlyName')
snooze = min(delay, until - now)
LOGGER.info("%s - %d not ready. Auto retry in %ds", transaction, instance_id, snooze)
time.sleep(snooze)
instance = self.get_hardware(instance_id, mask=mask)
now = time.time()
LOGGER.info("Waiting for %d expired.", instance_id)
return False | python | def wait_for_ready(self, instance_id, limit=14400, delay=10, pending=False):
"""Determine if a Server is ready.
A server is ready when no transactions are running on it.
:param int instance_id: The instance ID with the pending transaction
:param int limit: The maximum amount of seconds to wait.
:param int delay: The number of seconds to sleep before checks. Defaults to 10.
"""
now = time.time()
until = now + limit
mask = "mask[id, lastOperatingSystemReload[id], activeTransaction, provisionDate]"
instance = self.get_hardware(instance_id, mask=mask)
while now <= until:
if utils.is_ready(instance, pending):
return True
transaction = utils.lookup(instance, 'activeTransaction', 'transactionStatus', 'friendlyName')
snooze = min(delay, until - now)
LOGGER.info("%s - %d not ready. Auto retry in %ds", transaction, instance_id, snooze)
time.sleep(snooze)
instance = self.get_hardware(instance_id, mask=mask)
now = time.time()
LOGGER.info("Waiting for %d expired.", instance_id)
return False | [
"def",
"wait_for_ready",
"(",
"self",
",",
"instance_id",
",",
"limit",
"=",
"14400",
",",
"delay",
"=",
"10",
",",
"pending",
"=",
"False",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"until",
"=",
"now",
"+",
"limit",
"mask",
"=",
"\"mask[id, lastOperatingSystemReload[id], activeTransaction, provisionDate]\"",
"instance",
"=",
"self",
".",
"get_hardware",
"(",
"instance_id",
",",
"mask",
"=",
"mask",
")",
"while",
"now",
"<=",
"until",
":",
"if",
"utils",
".",
"is_ready",
"(",
"instance",
",",
"pending",
")",
":",
"return",
"True",
"transaction",
"=",
"utils",
".",
"lookup",
"(",
"instance",
",",
"'activeTransaction'",
",",
"'transactionStatus'",
",",
"'friendlyName'",
")",
"snooze",
"=",
"min",
"(",
"delay",
",",
"until",
"-",
"now",
")",
"LOGGER",
".",
"info",
"(",
"\"%s - %d not ready. Auto retry in %ds\"",
",",
"transaction",
",",
"instance_id",
",",
"snooze",
")",
"time",
".",
"sleep",
"(",
"snooze",
")",
"instance",
"=",
"self",
".",
"get_hardware",
"(",
"instance_id",
",",
"mask",
"=",
"mask",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"LOGGER",
".",
"info",
"(",
"\"Waiting for %d expired.\"",
",",
"instance_id",
")",
"return",
"False"
] | Determine if a Server is ready.
A server is ready when no transactions are running on it.
:param int instance_id: The instance ID with the pending transaction
:param int limit: The maximum amount of seconds to wait.
:param int delay: The number of seconds to sleep before checks. Defaults to 10. | [
"Determine",
"if",
"a",
"Server",
"is",
"ready",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L641-L665 |
1,809 | softlayer/softlayer-python | SoftLayer/CLI/hardware/cancel.py | cli | def cli(env, identifier, immediate, comment, reason):
"""Cancel a dedicated server."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or formatting.no_going_back(hw_id)):
raise exceptions.CLIAbort('Aborted')
mgr.cancel_hardware(hw_id, reason, comment, immediate) | python | def cli(env, identifier, immediate, comment, reason):
"""Cancel a dedicated server."""
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or formatting.no_going_back(hw_id)):
raise exceptions.CLIAbort('Aborted')
mgr.cancel_hardware(hw_id, reason, comment, immediate) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"immediate",
",",
"comment",
",",
"reason",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hw_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'hardware'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"hw_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"mgr",
".",
"cancel_hardware",
"(",
"hw_id",
",",
"reason",
",",
"comment",
",",
"immediate",
")"
] | Cancel a dedicated server. | [
"Cancel",
"a",
"dedicated",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/cancel.py#L24-L33 |
1,810 | softlayer/softlayer-python | SoftLayer/CLI/virt/reload.py | cli | def cli(env, identifier, postinstall, key, image):
"""Reload operating system on a virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
keys = []
if key:
for single_key in key:
resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
key_id = helpers.resolve_id(resolver, single_key, 'SshKey')
keys.append(key_id)
if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
raise exceptions.CLIAbort('Aborted')
vsi.reload_instance(vs_id,
post_uri=postinstall,
ssh_keys=keys,
image_id=image) | python | def cli(env, identifier, postinstall, key, image):
"""Reload operating system on a virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
keys = []
if key:
for single_key in key:
resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
key_id = helpers.resolve_id(resolver, single_key, 'SshKey')
keys.append(key_id)
if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
raise exceptions.CLIAbort('Aborted')
vsi.reload_instance(vs_id,
post_uri=postinstall,
ssh_keys=keys,
image_id=image) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"postinstall",
",",
"key",
",",
"image",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"keys",
"=",
"[",
"]",
"if",
"key",
":",
"for",
"single_key",
"in",
"key",
":",
"resolver",
"=",
"SoftLayer",
".",
"SshKeyManager",
"(",
"env",
".",
"client",
")",
".",
"resolve_ids",
"key_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"resolver",
",",
"single_key",
",",
"'SshKey'",
")",
"keys",
".",
"append",
"(",
"key_id",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"no_going_back",
"(",
"vs_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"vsi",
".",
"reload_instance",
"(",
"vs_id",
",",
"post_uri",
"=",
"postinstall",
",",
"ssh_keys",
"=",
"keys",
",",
"image_id",
"=",
"image",
")"
] | Reload operating system on a virtual server. | [
"Reload",
"operating",
"system",
"on",
"a",
"virtual",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/reload.py#L23-L40 |
1,811 | softlayer/softlayer-python | SoftLayer/CLI/virt/capacity/detail.py | cli | def cli(env, identifier, columns):
"""Reserved Capacity Group details. Will show which guests are assigned to a reservation."""
manager = CapacityManager(env.client)
mask = """mask[instances[id,createDate,guestId,billingItem[id, description, recurringFee, category[name]],
guest[modifyDate,id, primaryBackendIpAddress, primaryIpAddress,domain, hostname]]]"""
result = manager.get_object(identifier, mask)
try:
flavor = result['instances'][0]['billingItem']['description']
except KeyError:
flavor = "Pending Approval..."
table = formatting.Table(columns.columns, title="%s - %s" % (result.get('name'), flavor))
# RCI = Reserved Capacity Instance
for rci in result['instances']:
guest = rci.get('guest', None)
if guest is not None:
table.add_row([value or formatting.blank() for value in columns.row(guest)])
else:
table.add_row(['-' for value in columns.columns])
env.fout(table) | python | def cli(env, identifier, columns):
"""Reserved Capacity Group details. Will show which guests are assigned to a reservation."""
manager = CapacityManager(env.client)
mask = """mask[instances[id,createDate,guestId,billingItem[id, description, recurringFee, category[name]],
guest[modifyDate,id, primaryBackendIpAddress, primaryIpAddress,domain, hostname]]]"""
result = manager.get_object(identifier, mask)
try:
flavor = result['instances'][0]['billingItem']['description']
except KeyError:
flavor = "Pending Approval..."
table = formatting.Table(columns.columns, title="%s - %s" % (result.get('name'), flavor))
# RCI = Reserved Capacity Instance
for rci in result['instances']:
guest = rci.get('guest', None)
if guest is not None:
table.add_row([value or formatting.blank() for value in columns.row(guest)])
else:
table.add_row(['-' for value in columns.columns])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"columns",
")",
":",
"manager",
"=",
"CapacityManager",
"(",
"env",
".",
"client",
")",
"mask",
"=",
"\"\"\"mask[instances[id,createDate,guestId,billingItem[id, description, recurringFee, category[name]],\n guest[modifyDate,id, primaryBackendIpAddress, primaryIpAddress,domain, hostname]]]\"\"\"",
"result",
"=",
"manager",
".",
"get_object",
"(",
"identifier",
",",
"mask",
")",
"try",
":",
"flavor",
"=",
"result",
"[",
"'instances'",
"]",
"[",
"0",
"]",
"[",
"'billingItem'",
"]",
"[",
"'description'",
"]",
"except",
"KeyError",
":",
"flavor",
"=",
"\"Pending Approval...\"",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
",",
"title",
"=",
"\"%s - %s\"",
"%",
"(",
"result",
".",
"get",
"(",
"'name'",
")",
",",
"flavor",
")",
")",
"# RCI = Reserved Capacity Instance",
"for",
"rci",
"in",
"result",
"[",
"'instances'",
"]",
":",
"guest",
"=",
"rci",
".",
"get",
"(",
"'guest'",
",",
"None",
")",
"if",
"guest",
"is",
"not",
"None",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"guest",
")",
"]",
")",
"else",
":",
"table",
".",
"add_row",
"(",
"[",
"'-'",
"for",
"value",
"in",
"columns",
".",
"columns",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | Reserved Capacity Group details. Will show which guests are assigned to a reservation. | [
"Reserved",
"Capacity",
"Group",
"details",
".",
"Will",
"show",
"which",
"guests",
"are",
"assigned",
"to",
"a",
"reservation",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/detail.py#L36-L57 |
1,812 | softlayer/softlayer-python | SoftLayer/config.py | get_client_settings_args | def get_client_settings_args(**kwargs):
"""Retrieve client settings from user-supplied arguments.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
timeout = kwargs.get('timeout')
if timeout is not None:
timeout = float(timeout)
return {
'endpoint_url': kwargs.get('endpoint_url'),
'timeout': timeout,
'proxy': kwargs.get('proxy'),
'username': kwargs.get('username'),
'api_key': kwargs.get('api_key'),
} | python | def get_client_settings_args(**kwargs):
"""Retrieve client settings from user-supplied arguments.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
timeout = kwargs.get('timeout')
if timeout is not None:
timeout = float(timeout)
return {
'endpoint_url': kwargs.get('endpoint_url'),
'timeout': timeout,
'proxy': kwargs.get('proxy'),
'username': kwargs.get('username'),
'api_key': kwargs.get('api_key'),
} | [
"def",
"get_client_settings_args",
"(",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"return",
"{",
"'endpoint_url'",
":",
"kwargs",
".",
"get",
"(",
"'endpoint_url'",
")",
",",
"'timeout'",
":",
"timeout",
",",
"'proxy'",
":",
"kwargs",
".",
"get",
"(",
"'proxy'",
")",
",",
"'username'",
":",
"kwargs",
".",
"get",
"(",
"'username'",
")",
",",
"'api_key'",
":",
"kwargs",
".",
"get",
"(",
"'api_key'",
")",
",",
"}"
] | Retrieve client settings from user-supplied arguments.
:param \\*\\*kwargs: Arguments that are passed into the client instance | [
"Retrieve",
"client",
"settings",
"from",
"user",
"-",
"supplied",
"arguments",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/config.py#L14-L29 |
1,813 | softlayer/softlayer-python | SoftLayer/config.py | get_client_settings_env | def get_client_settings_env(**_):
"""Retrieve client settings from environment settings.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
return {
'proxy': os.environ.get('https_proxy'),
'username': os.environ.get('SL_USERNAME'),
'api_key': os.environ.get('SL_API_KEY'),
} | python | def get_client_settings_env(**_):
"""Retrieve client settings from environment settings.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
return {
'proxy': os.environ.get('https_proxy'),
'username': os.environ.get('SL_USERNAME'),
'api_key': os.environ.get('SL_API_KEY'),
} | [
"def",
"get_client_settings_env",
"(",
"*",
"*",
"_",
")",
":",
"return",
"{",
"'proxy'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'https_proxy'",
")",
",",
"'username'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'SL_USERNAME'",
")",
",",
"'api_key'",
":",
"os",
".",
"environ",
".",
"get",
"(",
"'SL_API_KEY'",
")",
",",
"}"
] | Retrieve client settings from environment settings.
:param \\*\\*kwargs: Arguments that are passed into the client instance | [
"Retrieve",
"client",
"settings",
"from",
"environment",
"settings",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/config.py#L32-L42 |
1,814 | softlayer/softlayer-python | SoftLayer/config.py | get_client_settings_config_file | def get_client_settings_config_file(**kwargs): # pylint: disable=inconsistent-return-statements
"""Retrieve client settings from the possible config file locations.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
config_files = ['/etc/softlayer.conf', '~/.softlayer']
if kwargs.get('config_file'):
config_files.append(kwargs.get('config_file'))
config_files = [os.path.expanduser(f) for f in config_files]
config = utils.configparser.RawConfigParser({
'username': '',
'api_key': '',
'endpoint_url': '',
'timeout': '0',
'proxy': '',
})
config.read(config_files)
if config.has_section('softlayer'):
return {
'endpoint_url': config.get('softlayer', 'endpoint_url'),
'timeout': config.getfloat('softlayer', 'timeout'),
'proxy': config.get('softlayer', 'proxy'),
'username': config.get('softlayer', 'username'),
'api_key': config.get('softlayer', 'api_key'),
} | python | def get_client_settings_config_file(**kwargs): # pylint: disable=inconsistent-return-statements
"""Retrieve client settings from the possible config file locations.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
config_files = ['/etc/softlayer.conf', '~/.softlayer']
if kwargs.get('config_file'):
config_files.append(kwargs.get('config_file'))
config_files = [os.path.expanduser(f) for f in config_files]
config = utils.configparser.RawConfigParser({
'username': '',
'api_key': '',
'endpoint_url': '',
'timeout': '0',
'proxy': '',
})
config.read(config_files)
if config.has_section('softlayer'):
return {
'endpoint_url': config.get('softlayer', 'endpoint_url'),
'timeout': config.getfloat('softlayer', 'timeout'),
'proxy': config.get('softlayer', 'proxy'),
'username': config.get('softlayer', 'username'),
'api_key': config.get('softlayer', 'api_key'),
} | [
"def",
"get_client_settings_config_file",
"(",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"config_files",
"=",
"[",
"'/etc/softlayer.conf'",
",",
"'~/.softlayer'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'config_file'",
")",
":",
"config_files",
".",
"append",
"(",
"kwargs",
".",
"get",
"(",
"'config_file'",
")",
")",
"config_files",
"=",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"f",
")",
"for",
"f",
"in",
"config_files",
"]",
"config",
"=",
"utils",
".",
"configparser",
".",
"RawConfigParser",
"(",
"{",
"'username'",
":",
"''",
",",
"'api_key'",
":",
"''",
",",
"'endpoint_url'",
":",
"''",
",",
"'timeout'",
":",
"'0'",
",",
"'proxy'",
":",
"''",
",",
"}",
")",
"config",
".",
"read",
"(",
"config_files",
")",
"if",
"config",
".",
"has_section",
"(",
"'softlayer'",
")",
":",
"return",
"{",
"'endpoint_url'",
":",
"config",
".",
"get",
"(",
"'softlayer'",
",",
"'endpoint_url'",
")",
",",
"'timeout'",
":",
"config",
".",
"getfloat",
"(",
"'softlayer'",
",",
"'timeout'",
")",
",",
"'proxy'",
":",
"config",
".",
"get",
"(",
"'softlayer'",
",",
"'proxy'",
")",
",",
"'username'",
":",
"config",
".",
"get",
"(",
"'softlayer'",
",",
"'username'",
")",
",",
"'api_key'",
":",
"config",
".",
"get",
"(",
"'softlayer'",
",",
"'api_key'",
")",
",",
"}"
] | Retrieve client settings from the possible config file locations.
:param \\*\\*kwargs: Arguments that are passed into the client instance | [
"Retrieve",
"client",
"settings",
"from",
"the",
"possible",
"config",
"file",
"locations",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/config.py#L45-L70 |
1,815 | softlayer/softlayer-python | SoftLayer/config.py | get_client_settings | def get_client_settings(**kwargs):
"""Parse client settings.
Parses settings from various input methods, preferring earlier values
to later ones. The settings currently come from explicit user arguments,
environmental variables and config files.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
all_settings = {}
for setting_method in SETTING_RESOLVERS:
settings = setting_method(**kwargs)
if settings:
settings.update((k, v) for k, v in all_settings.items() if v)
all_settings = settings
return all_settings | python | def get_client_settings(**kwargs):
"""Parse client settings.
Parses settings from various input methods, preferring earlier values
to later ones. The settings currently come from explicit user arguments,
environmental variables and config files.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
all_settings = {}
for setting_method in SETTING_RESOLVERS:
settings = setting_method(**kwargs)
if settings:
settings.update((k, v) for k, v in all_settings.items() if v)
all_settings = settings
return all_settings | [
"def",
"get_client_settings",
"(",
"*",
"*",
"kwargs",
")",
":",
"all_settings",
"=",
"{",
"}",
"for",
"setting_method",
"in",
"SETTING_RESOLVERS",
":",
"settings",
"=",
"setting_method",
"(",
"*",
"*",
"kwargs",
")",
"if",
"settings",
":",
"settings",
".",
"update",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"all_settings",
".",
"items",
"(",
")",
"if",
"v",
")",
"all_settings",
"=",
"settings",
"return",
"all_settings"
] | Parse client settings.
Parses settings from various input methods, preferring earlier values
to later ones. The settings currently come from explicit user arguments,
environmental variables and config files.
:param \\*\\*kwargs: Arguments that are passed into the client instance | [
"Parse",
"client",
"settings",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/config.py#L78-L94 |
1,816 | softlayer/softlayer-python | SoftLayer/CLI/order/category_list.py | cli | def cli(env, package_keyname, required):
"""List the categories of a package.
::
# List the categories of Bare Metal servers
slcli order category-list BARE_METAL_SERVER
# List the required categories for Bare Metal servers
slcli order category-list BARE_METAL_SERVER --required
"""
client = env.client
manager = ordering.OrderingManager(client)
table = formatting.Table(COLUMNS)
categories = manager.list_categories(package_keyname)
if required:
categories = [cat for cat in categories if cat['isRequired']]
for cat in categories:
table.add_row([
cat['itemCategory']['name'],
cat['itemCategory']['categoryCode'],
'Y' if cat['isRequired'] else 'N'
])
env.fout(table) | python | def cli(env, package_keyname, required):
"""List the categories of a package.
::
# List the categories of Bare Metal servers
slcli order category-list BARE_METAL_SERVER
# List the required categories for Bare Metal servers
slcli order category-list BARE_METAL_SERVER --required
"""
client = env.client
manager = ordering.OrderingManager(client)
table = formatting.Table(COLUMNS)
categories = manager.list_categories(package_keyname)
if required:
categories = [cat for cat in categories if cat['isRequired']]
for cat in categories:
table.add_row([
cat['itemCategory']['name'],
cat['itemCategory']['categoryCode'],
'Y' if cat['isRequired'] else 'N'
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"package_keyname",
",",
"required",
")",
":",
"client",
"=",
"env",
".",
"client",
"manager",
"=",
"ordering",
".",
"OrderingManager",
"(",
"client",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"COLUMNS",
")",
"categories",
"=",
"manager",
".",
"list_categories",
"(",
"package_keyname",
")",
"if",
"required",
":",
"categories",
"=",
"[",
"cat",
"for",
"cat",
"in",
"categories",
"if",
"cat",
"[",
"'isRequired'",
"]",
"]",
"for",
"cat",
"in",
"categories",
":",
"table",
".",
"add_row",
"(",
"[",
"cat",
"[",
"'itemCategory'",
"]",
"[",
"'name'",
"]",
",",
"cat",
"[",
"'itemCategory'",
"]",
"[",
"'categoryCode'",
"]",
",",
"'Y'",
"if",
"cat",
"[",
"'isRequired'",
"]",
"else",
"'N'",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List the categories of a package.
::
# List the categories of Bare Metal servers
slcli order category-list BARE_METAL_SERVER
# List the required categories for Bare Metal servers
slcli order category-list BARE_METAL_SERVER --required | [
"List",
"the",
"categories",
"of",
"a",
"package",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/category_list.py#L19-L47 |
1,817 | softlayer/softlayer-python | SoftLayer/managers/ssl.py | SSLManager.list_certs | def list_certs(self, method='all'):
"""List all certificates.
:param string method: The type of certificates to list. Options are
'all', 'expired', and 'valid'.
:returns: A list of dictionaries representing the requested SSL certs.
Example::
# Get all valid SSL certs
certs = mgr.list_certs(method='valid')
print certs
"""
ssl = self.client['Account']
methods = {
'all': 'getSecurityCertificates',
'expired': 'getExpiredSecurityCertificates',
'valid': 'getValidSecurityCertificates'
}
mask = "mask[id, commonName, validityDays, notes]"
func = getattr(ssl, methods[method])
return func(mask=mask) | python | def list_certs(self, method='all'):
"""List all certificates.
:param string method: The type of certificates to list. Options are
'all', 'expired', and 'valid'.
:returns: A list of dictionaries representing the requested SSL certs.
Example::
# Get all valid SSL certs
certs = mgr.list_certs(method='valid')
print certs
"""
ssl = self.client['Account']
methods = {
'all': 'getSecurityCertificates',
'expired': 'getExpiredSecurityCertificates',
'valid': 'getValidSecurityCertificates'
}
mask = "mask[id, commonName, validityDays, notes]"
func = getattr(ssl, methods[method])
return func(mask=mask) | [
"def",
"list_certs",
"(",
"self",
",",
"method",
"=",
"'all'",
")",
":",
"ssl",
"=",
"self",
".",
"client",
"[",
"'Account'",
"]",
"methods",
"=",
"{",
"'all'",
":",
"'getSecurityCertificates'",
",",
"'expired'",
":",
"'getExpiredSecurityCertificates'",
",",
"'valid'",
":",
"'getValidSecurityCertificates'",
"}",
"mask",
"=",
"\"mask[id, commonName, validityDays, notes]\"",
"func",
"=",
"getattr",
"(",
"ssl",
",",
"methods",
"[",
"method",
"]",
")",
"return",
"func",
"(",
"mask",
"=",
"mask",
")"
] | List all certificates.
:param string method: The type of certificates to list. Options are
'all', 'expired', and 'valid'.
:returns: A list of dictionaries representing the requested SSL certs.
Example::
# Get all valid SSL certs
certs = mgr.list_certs(method='valid')
print certs | [
"List",
"all",
"certificates",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ssl.py#L34-L57 |
1,818 | softlayer/softlayer-python | SoftLayer/CLI/dns/zone_list.py | cli | def cli(env):
"""List all zones."""
manager = SoftLayer.DNSManager(env.client)
zones = manager.list_zones()
table = formatting.Table(['id', 'zone', 'serial', 'updated'])
table.align['serial'] = 'c'
table.align['updated'] = 'c'
for zone in zones:
table.add_row([
zone['id'],
zone['name'],
zone['serial'],
zone['updateDate'],
])
env.fout(table) | python | def cli(env):
"""List all zones."""
manager = SoftLayer.DNSManager(env.client)
zones = manager.list_zones()
table = formatting.Table(['id', 'zone', 'serial', 'updated'])
table.align['serial'] = 'c'
table.align['updated'] = 'c'
for zone in zones:
table.add_row([
zone['id'],
zone['name'],
zone['serial'],
zone['updateDate'],
])
env.fout(table) | [
"def",
"cli",
"(",
"env",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"zones",
"=",
"manager",
".",
"list_zones",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'zone'",
",",
"'serial'",
",",
"'updated'",
"]",
")",
"table",
".",
"align",
"[",
"'serial'",
"]",
"=",
"'c'",
"table",
".",
"align",
"[",
"'updated'",
"]",
"=",
"'c'",
"for",
"zone",
"in",
"zones",
":",
"table",
".",
"add_row",
"(",
"[",
"zone",
"[",
"'id'",
"]",
",",
"zone",
"[",
"'name'",
"]",
",",
"zone",
"[",
"'serial'",
"]",
",",
"zone",
"[",
"'updateDate'",
"]",
",",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List all zones. | [
"List",
"all",
"zones",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/zone_list.py#L13-L30 |
1,819 | softlayer/softlayer-python | SoftLayer/managers/file.py | FileStorageManager.list_file_volumes | def list_file_volumes(self, datacenter=None, username=None,
storage_type=None, **kwargs):
"""Returns a list of file volumes.
:param datacenter: Datacenter short name (e.g.: dal09)
:param username: Name of volume.
:param storage_type: Type of volume: Endurance or Performance
:param kwargs:
:return: Returns a list of file volumes.
"""
if 'mask' not in kwargs:
items = [
'id',
'username',
'capacityGb',
'bytesUsed',
'serviceResource.datacenter[name]',
'serviceResourceBackendIpAddress',
'activeTransactionCount',
'fileNetworkMountAddress',
'replicationPartnerCount'
]
kwargs['mask'] = ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
_filter['nasNetworkStorage']['serviceResource']['type']['type'] = \
(utils.query_filter('!~ NAS'))
_filter['nasNetworkStorage']['storageType']['keyName'] = (
utils.query_filter('*FILE_STORAGE*'))
if storage_type:
_filter['nasNetworkStorage']['storageType']['keyName'] = (
utils.query_filter('%s_FILE_STORAGE*' % storage_type.upper()))
if datacenter:
_filter['nasNetworkStorage']['serviceResource']['datacenter'][
'name'] = (utils.query_filter(datacenter))
if username:
_filter['nasNetworkStorage']['username'] = \
(utils.query_filter(username))
kwargs['filter'] = _filter.to_dict()
return self.client.call('Account', 'getNasNetworkStorage', **kwargs) | python | def list_file_volumes(self, datacenter=None, username=None,
storage_type=None, **kwargs):
"""Returns a list of file volumes.
:param datacenter: Datacenter short name (e.g.: dal09)
:param username: Name of volume.
:param storage_type: Type of volume: Endurance or Performance
:param kwargs:
:return: Returns a list of file volumes.
"""
if 'mask' not in kwargs:
items = [
'id',
'username',
'capacityGb',
'bytesUsed',
'serviceResource.datacenter[name]',
'serviceResourceBackendIpAddress',
'activeTransactionCount',
'fileNetworkMountAddress',
'replicationPartnerCount'
]
kwargs['mask'] = ','.join(items)
_filter = utils.NestedDict(kwargs.get('filter') or {})
_filter['nasNetworkStorage']['serviceResource']['type']['type'] = \
(utils.query_filter('!~ NAS'))
_filter['nasNetworkStorage']['storageType']['keyName'] = (
utils.query_filter('*FILE_STORAGE*'))
if storage_type:
_filter['nasNetworkStorage']['storageType']['keyName'] = (
utils.query_filter('%s_FILE_STORAGE*' % storage_type.upper()))
if datacenter:
_filter['nasNetworkStorage']['serviceResource']['datacenter'][
'name'] = (utils.query_filter(datacenter))
if username:
_filter['nasNetworkStorage']['username'] = \
(utils.query_filter(username))
kwargs['filter'] = _filter.to_dict()
return self.client.call('Account', 'getNasNetworkStorage', **kwargs) | [
"def",
"list_file_volumes",
"(",
"self",
",",
"datacenter",
"=",
"None",
",",
"username",
"=",
"None",
",",
"storage_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"items",
"=",
"[",
"'id'",
",",
"'username'",
",",
"'capacityGb'",
",",
"'bytesUsed'",
",",
"'serviceResource.datacenter[name]'",
",",
"'serviceResourceBackendIpAddress'",
",",
"'activeTransactionCount'",
",",
"'fileNetworkMountAddress'",
",",
"'replicationPartnerCount'",
"]",
"kwargs",
"[",
"'mask'",
"]",
"=",
"','",
".",
"join",
"(",
"items",
")",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"kwargs",
".",
"get",
"(",
"'filter'",
")",
"or",
"{",
"}",
")",
"_filter",
"[",
"'nasNetworkStorage'",
"]",
"[",
"'serviceResource'",
"]",
"[",
"'type'",
"]",
"[",
"'type'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"'!~ NAS'",
")",
")",
"_filter",
"[",
"'nasNetworkStorage'",
"]",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"'*FILE_STORAGE*'",
")",
")",
"if",
"storage_type",
":",
"_filter",
"[",
"'nasNetworkStorage'",
"]",
"[",
"'storageType'",
"]",
"[",
"'keyName'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"'%s_FILE_STORAGE*'",
"%",
"storage_type",
".",
"upper",
"(",
")",
")",
")",
"if",
"datacenter",
":",
"_filter",
"[",
"'nasNetworkStorage'",
"]",
"[",
"'serviceResource'",
"]",
"[",
"'datacenter'",
"]",
"[",
"'name'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"datacenter",
")",
")",
"if",
"username",
":",
"_filter",
"[",
"'nasNetworkStorage'",
"]",
"[",
"'username'",
"]",
"=",
"(",
"utils",
".",
"query_filter",
"(",
"username",
")",
")",
"kwargs",
"[",
"'filter'",
"]",
"=",
"_filter",
".",
"to_dict",
"(",
")",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Account'",
",",
"'getNasNetworkStorage'",
",",
"*",
"*",
"kwargs",
")"
] | Returns a list of file volumes.
:param datacenter: Datacenter short name (e.g.: dal09)
:param username: Name of volume.
:param storage_type: Type of volume: Endurance or Performance
:param kwargs:
:return: Returns a list of file volumes. | [
"Returns",
"a",
"list",
"of",
"file",
"volumes",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L22-L66 |
1,820 | softlayer/softlayer-python | SoftLayer/managers/file.py | FileStorageManager.get_file_volume_details | def get_file_volume_details(self, volume_id, **kwargs):
"""Returns details about the specified volume.
:param volume_id: ID of volume.
:param kwargs:
:return: Returns details about the specified volume.
"""
if 'mask' not in kwargs:
items = [
'id',
'username',
'password',
'capacityGb',
'bytesUsed',
'snapshotCapacityGb',
'parentVolume.snapshotSizeBytes',
'storageType.keyName',
'serviceResource.datacenter[name]',
'serviceResourceBackendIpAddress',
'fileNetworkMountAddress',
'storageTierLevel',
'provisionedIops',
'lunId',
'originalVolumeName',
'originalSnapshotName',
'originalVolumeSize',
'activeTransactionCount',
'activeTransactions.transactionStatus[friendlyName]',
'replicationPartnerCount',
'replicationStatus',
'replicationPartners[id,username,'
'serviceResourceBackendIpAddress,'
'serviceResource[datacenter[name]],'
'replicationSchedule[type[keyname]]]',
]
kwargs['mask'] = ','.join(items)
return self.client.call('Network_Storage', 'getObject',
id=volume_id, **kwargs) | python | def get_file_volume_details(self, volume_id, **kwargs):
"""Returns details about the specified volume.
:param volume_id: ID of volume.
:param kwargs:
:return: Returns details about the specified volume.
"""
if 'mask' not in kwargs:
items = [
'id',
'username',
'password',
'capacityGb',
'bytesUsed',
'snapshotCapacityGb',
'parentVolume.snapshotSizeBytes',
'storageType.keyName',
'serviceResource.datacenter[name]',
'serviceResourceBackendIpAddress',
'fileNetworkMountAddress',
'storageTierLevel',
'provisionedIops',
'lunId',
'originalVolumeName',
'originalSnapshotName',
'originalVolumeSize',
'activeTransactionCount',
'activeTransactions.transactionStatus[friendlyName]',
'replicationPartnerCount',
'replicationStatus',
'replicationPartners[id,username,'
'serviceResourceBackendIpAddress,'
'serviceResource[datacenter[name]],'
'replicationSchedule[type[keyname]]]',
]
kwargs['mask'] = ','.join(items)
return self.client.call('Network_Storage', 'getObject',
id=volume_id, **kwargs) | [
"def",
"get_file_volume_details",
"(",
"self",
",",
"volume_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"items",
"=",
"[",
"'id'",
",",
"'username'",
",",
"'password'",
",",
"'capacityGb'",
",",
"'bytesUsed'",
",",
"'snapshotCapacityGb'",
",",
"'parentVolume.snapshotSizeBytes'",
",",
"'storageType.keyName'",
",",
"'serviceResource.datacenter[name]'",
",",
"'serviceResourceBackendIpAddress'",
",",
"'fileNetworkMountAddress'",
",",
"'storageTierLevel'",
",",
"'provisionedIops'",
",",
"'lunId'",
",",
"'originalVolumeName'",
",",
"'originalSnapshotName'",
",",
"'originalVolumeSize'",
",",
"'activeTransactionCount'",
",",
"'activeTransactions.transactionStatus[friendlyName]'",
",",
"'replicationPartnerCount'",
",",
"'replicationStatus'",
",",
"'replicationPartners[id,username,'",
"'serviceResourceBackendIpAddress,'",
"'serviceResource[datacenter[name]],'",
"'replicationSchedule[type[keyname]]]'",
",",
"]",
"kwargs",
"[",
"'mask'",
"]",
"=",
"','",
".",
"join",
"(",
"items",
")",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Network_Storage'",
",",
"'getObject'",
",",
"id",
"=",
"volume_id",
",",
"*",
"*",
"kwargs",
")"
] | Returns details about the specified volume.
:param volume_id: ID of volume.
:param kwargs:
:return: Returns details about the specified volume. | [
"Returns",
"details",
"about",
"the",
"specified",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L68-L106 |
1,821 | softlayer/softlayer-python | SoftLayer/managers/file.py | FileStorageManager.order_replicant_volume | def order_replicant_volume(self, volume_id, snapshot_schedule,
location, tier=None):
"""Places an order for a replicant file volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snapshot
schedule to use for replication
:param location: The location for the ordered replicant volume
:param tier: The tier (IOPS per GB) of the primary volume
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
file_mask = 'billingItem[activeChildren,hourlyFlag],'\
'storageTierLevel,osType,staasVersion,'\
'hasEncryptionAtRest,snapshotCapacityGb,schedules,'\
'intervalSchedule,hourlySchedule,dailySchedule,'\
'weeklySchedule,storageType[keyName],provisionedIops'
file_volume = self.get_file_volume_details(volume_id,
mask=file_mask)
order = storage_utils.prepare_replicant_order_object(
self, snapshot_schedule, location, tier, file_volume, 'file'
)
return self.client.call('Product_Order', 'placeOrder', order) | python | def order_replicant_volume(self, volume_id, snapshot_schedule,
location, tier=None):
"""Places an order for a replicant file volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snapshot
schedule to use for replication
:param location: The location for the ordered replicant volume
:param tier: The tier (IOPS per GB) of the primary volume
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
file_mask = 'billingItem[activeChildren,hourlyFlag],'\
'storageTierLevel,osType,staasVersion,'\
'hasEncryptionAtRest,snapshotCapacityGb,schedules,'\
'intervalSchedule,hourlySchedule,dailySchedule,'\
'weeklySchedule,storageType[keyName],provisionedIops'
file_volume = self.get_file_volume_details(volume_id,
mask=file_mask)
order = storage_utils.prepare_replicant_order_object(
self, snapshot_schedule, location, tier, file_volume, 'file'
)
return self.client.call('Product_Order', 'placeOrder', order) | [
"def",
"order_replicant_volume",
"(",
"self",
",",
"volume_id",
",",
"snapshot_schedule",
",",
"location",
",",
"tier",
"=",
"None",
")",
":",
"file_mask",
"=",
"'billingItem[activeChildren,hourlyFlag],'",
"'storageTierLevel,osType,staasVersion,'",
"'hasEncryptionAtRest,snapshotCapacityGb,schedules,'",
"'intervalSchedule,hourlySchedule,dailySchedule,'",
"'weeklySchedule,storageType[keyName],provisionedIops'",
"file_volume",
"=",
"self",
".",
"get_file_volume_details",
"(",
"volume_id",
",",
"mask",
"=",
"file_mask",
")",
"order",
"=",
"storage_utils",
".",
"prepare_replicant_order_object",
"(",
"self",
",",
"snapshot_schedule",
",",
"location",
",",
"tier",
",",
"file_volume",
",",
"'file'",
")",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Product_Order'",
",",
"'placeOrder'",
",",
"order",
")"
] | Places an order for a replicant file volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snapshot
schedule to use for replication
:param location: The location for the ordered replicant volume
:param tier: The tier (IOPS per GB) of the primary volume
:return: Returns a SoftLayer_Container_Product_Order_Receipt | [
"Places",
"an",
"order",
"for",
"a",
"replicant",
"file",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L205-L229 |
1,822 | softlayer/softlayer-python | SoftLayer/managers/file.py | FileStorageManager.order_duplicate_volume | def order_duplicate_volume(self, origin_volume_id, origin_snapshot_id=None,
duplicate_size=None, duplicate_iops=None,
duplicate_tier_level=None,
duplicate_snapshot_size=None,
hourly_billing_flag=False):
"""Places an order for a duplicate file volume.
:param origin_volume_id: The ID of the origin volume to be duplicated
:param origin_snapshot_id: Origin snapshot ID to use for duplication
:param duplicate_size: Size/capacity for the duplicate volume
:param duplicate_iops: The IOPS per GB for the duplicate volume
:param duplicate_tier_level: Tier level for the duplicate volume
:param duplicate_snapshot_size: Snapshot space size for the duplicate
:param hourly_billing_flag: Billing type, monthly (False)
or hourly (True), default to monthly.
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
file_mask = 'id,billingItem[location,hourlyFlag],snapshotCapacityGb,'\
'storageType[keyName],capacityGb,originalVolumeSize,'\
'provisionedIops,storageTierLevel,'\
'staasVersion,hasEncryptionAtRest'
origin_volume = self.get_file_volume_details(origin_volume_id,
mask=file_mask)
order = storage_utils.prepare_duplicate_order_object(
self, origin_volume, duplicate_iops, duplicate_tier_level,
duplicate_size, duplicate_snapshot_size, 'file',
hourly_billing_flag
)
if origin_snapshot_id is not None:
order['duplicateOriginSnapshotId'] = origin_snapshot_id
return self.client.call('Product_Order', 'placeOrder', order) | python | def order_duplicate_volume(self, origin_volume_id, origin_snapshot_id=None,
duplicate_size=None, duplicate_iops=None,
duplicate_tier_level=None,
duplicate_snapshot_size=None,
hourly_billing_flag=False):
"""Places an order for a duplicate file volume.
:param origin_volume_id: The ID of the origin volume to be duplicated
:param origin_snapshot_id: Origin snapshot ID to use for duplication
:param duplicate_size: Size/capacity for the duplicate volume
:param duplicate_iops: The IOPS per GB for the duplicate volume
:param duplicate_tier_level: Tier level for the duplicate volume
:param duplicate_snapshot_size: Snapshot space size for the duplicate
:param hourly_billing_flag: Billing type, monthly (False)
or hourly (True), default to monthly.
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
file_mask = 'id,billingItem[location,hourlyFlag],snapshotCapacityGb,'\
'storageType[keyName],capacityGb,originalVolumeSize,'\
'provisionedIops,storageTierLevel,'\
'staasVersion,hasEncryptionAtRest'
origin_volume = self.get_file_volume_details(origin_volume_id,
mask=file_mask)
order = storage_utils.prepare_duplicate_order_object(
self, origin_volume, duplicate_iops, duplicate_tier_level,
duplicate_size, duplicate_snapshot_size, 'file',
hourly_billing_flag
)
if origin_snapshot_id is not None:
order['duplicateOriginSnapshotId'] = origin_snapshot_id
return self.client.call('Product_Order', 'placeOrder', order) | [
"def",
"order_duplicate_volume",
"(",
"self",
",",
"origin_volume_id",
",",
"origin_snapshot_id",
"=",
"None",
",",
"duplicate_size",
"=",
"None",
",",
"duplicate_iops",
"=",
"None",
",",
"duplicate_tier_level",
"=",
"None",
",",
"duplicate_snapshot_size",
"=",
"None",
",",
"hourly_billing_flag",
"=",
"False",
")",
":",
"file_mask",
"=",
"'id,billingItem[location,hourlyFlag],snapshotCapacityGb,'",
"'storageType[keyName],capacityGb,originalVolumeSize,'",
"'provisionedIops,storageTierLevel,'",
"'staasVersion,hasEncryptionAtRest'",
"origin_volume",
"=",
"self",
".",
"get_file_volume_details",
"(",
"origin_volume_id",
",",
"mask",
"=",
"file_mask",
")",
"order",
"=",
"storage_utils",
".",
"prepare_duplicate_order_object",
"(",
"self",
",",
"origin_volume",
",",
"duplicate_iops",
",",
"duplicate_tier_level",
",",
"duplicate_size",
",",
"duplicate_snapshot_size",
",",
"'file'",
",",
"hourly_billing_flag",
")",
"if",
"origin_snapshot_id",
"is",
"not",
"None",
":",
"order",
"[",
"'duplicateOriginSnapshotId'",
"]",
"=",
"origin_snapshot_id",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Product_Order'",
",",
"'placeOrder'",
",",
"order",
")"
] | Places an order for a duplicate file volume.
:param origin_volume_id: The ID of the origin volume to be duplicated
:param origin_snapshot_id: Origin snapshot ID to use for duplication
:param duplicate_size: Size/capacity for the duplicate volume
:param duplicate_iops: The IOPS per GB for the duplicate volume
:param duplicate_tier_level: Tier level for the duplicate volume
:param duplicate_snapshot_size: Snapshot space size for the duplicate
:param hourly_billing_flag: Billing type, monthly (False)
or hourly (True), default to monthly.
:return: Returns a SoftLayer_Container_Product_Order_Receipt | [
"Places",
"an",
"order",
"for",
"a",
"duplicate",
"file",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L251-L285 |
1,823 | softlayer/softlayer-python | SoftLayer/managers/file.py | FileStorageManager.order_modified_volume | def order_modified_volume(self, volume_id, new_size=None, new_iops=None, new_tier_level=None):
"""Places an order for modifying an existing file volume.
:param volume_id: The ID of the volume to be modified
:param new_size: The new size/capacity for the volume
:param new_iops: The new IOPS for the volume
:param new_tier_level: The new tier level for the volume
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
mask_items = [
'id',
'billingItem',
'storageType[keyName]',
'capacityGb',
'provisionedIops',
'storageTierLevel',
'staasVersion',
'hasEncryptionAtRest',
]
file_mask = ','.join(mask_items)
volume = self.get_file_volume_details(volume_id, mask=file_mask)
order = storage_utils.prepare_modify_order_object(
self, volume, new_iops, new_tier_level, new_size
)
return self.client.call('Product_Order', 'placeOrder', order) | python | def order_modified_volume(self, volume_id, new_size=None, new_iops=None, new_tier_level=None):
"""Places an order for modifying an existing file volume.
:param volume_id: The ID of the volume to be modified
:param new_size: The new size/capacity for the volume
:param new_iops: The new IOPS for the volume
:param new_tier_level: The new tier level for the volume
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
mask_items = [
'id',
'billingItem',
'storageType[keyName]',
'capacityGb',
'provisionedIops',
'storageTierLevel',
'staasVersion',
'hasEncryptionAtRest',
]
file_mask = ','.join(mask_items)
volume = self.get_file_volume_details(volume_id, mask=file_mask)
order = storage_utils.prepare_modify_order_object(
self, volume, new_iops, new_tier_level, new_size
)
return self.client.call('Product_Order', 'placeOrder', order) | [
"def",
"order_modified_volume",
"(",
"self",
",",
"volume_id",
",",
"new_size",
"=",
"None",
",",
"new_iops",
"=",
"None",
",",
"new_tier_level",
"=",
"None",
")",
":",
"mask_items",
"=",
"[",
"'id'",
",",
"'billingItem'",
",",
"'storageType[keyName]'",
",",
"'capacityGb'",
",",
"'provisionedIops'",
",",
"'storageTierLevel'",
",",
"'staasVersion'",
",",
"'hasEncryptionAtRest'",
",",
"]",
"file_mask",
"=",
"','",
".",
"join",
"(",
"mask_items",
")",
"volume",
"=",
"self",
".",
"get_file_volume_details",
"(",
"volume_id",
",",
"mask",
"=",
"file_mask",
")",
"order",
"=",
"storage_utils",
".",
"prepare_modify_order_object",
"(",
"self",
",",
"volume",
",",
"new_iops",
",",
"new_tier_level",
",",
"new_size",
")",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Product_Order'",
",",
"'placeOrder'",
",",
"order",
")"
] | Places an order for modifying an existing file volume.
:param volume_id: The ID of the volume to be modified
:param new_size: The new size/capacity for the volume
:param new_iops: The new IOPS for the volume
:param new_tier_level: The new tier level for the volume
:return: Returns a SoftLayer_Container_Product_Order_Receipt | [
"Places",
"an",
"order",
"for",
"modifying",
"an",
"existing",
"file",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L287-L314 |
1,824 | softlayer/softlayer-python | SoftLayer/managers/file.py | FileStorageManager.order_snapshot_space | def order_snapshot_space(self, volume_id, capacity, tier, upgrade, **kwargs):
"""Orders snapshot space for the given file volume.
:param integer volume_id: The ID of the volume
:param integer capacity: The capacity to order, in GB
:param float tier: The tier level of the file volume, in IOPS per GB
:param boolean upgrade: Flag to indicate if this order is an upgrade
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
file_mask = 'id,billingItem[location,hourlyFlag],'\
'storageType[keyName],storageTierLevel,provisionedIops,'\
'staasVersion,hasEncryptionAtRest'
file_volume = self.get_file_volume_details(volume_id,
mask=file_mask,
**kwargs)
order = storage_utils.prepare_snapshot_order_object(
self, file_volume, capacity, tier, upgrade)
return self.client.call('Product_Order', 'placeOrder', order) | python | def order_snapshot_space(self, volume_id, capacity, tier, upgrade, **kwargs):
"""Orders snapshot space for the given file volume.
:param integer volume_id: The ID of the volume
:param integer capacity: The capacity to order, in GB
:param float tier: The tier level of the file volume, in IOPS per GB
:param boolean upgrade: Flag to indicate if this order is an upgrade
:return: Returns a SoftLayer_Container_Product_Order_Receipt
"""
file_mask = 'id,billingItem[location,hourlyFlag],'\
'storageType[keyName],storageTierLevel,provisionedIops,'\
'staasVersion,hasEncryptionAtRest'
file_volume = self.get_file_volume_details(volume_id,
mask=file_mask,
**kwargs)
order = storage_utils.prepare_snapshot_order_object(
self, file_volume, capacity, tier, upgrade)
return self.client.call('Product_Order', 'placeOrder', order) | [
"def",
"order_snapshot_space",
"(",
"self",
",",
"volume_id",
",",
"capacity",
",",
"tier",
",",
"upgrade",
",",
"*",
"*",
"kwargs",
")",
":",
"file_mask",
"=",
"'id,billingItem[location,hourlyFlag],'",
"'storageType[keyName],storageTierLevel,provisionedIops,'",
"'staasVersion,hasEncryptionAtRest'",
"file_volume",
"=",
"self",
".",
"get_file_volume_details",
"(",
"volume_id",
",",
"mask",
"=",
"file_mask",
",",
"*",
"*",
"kwargs",
")",
"order",
"=",
"storage_utils",
".",
"prepare_snapshot_order_object",
"(",
"self",
",",
"file_volume",
",",
"capacity",
",",
"tier",
",",
"upgrade",
")",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Product_Order'",
",",
"'placeOrder'",
",",
"order",
")"
] | Orders snapshot space for the given file volume.
:param integer volume_id: The ID of the volume
:param integer capacity: The capacity to order, in GB
:param float tier: The tier level of the file volume, in IOPS per GB
:param boolean upgrade: Flag to indicate if this order is an upgrade
:return: Returns a SoftLayer_Container_Product_Order_Receipt | [
"Orders",
"snapshot",
"space",
"for",
"the",
"given",
"file",
"volume",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L406-L425 |
1,825 | softlayer/softlayer-python | SoftLayer/CLI/dns/zone_print.py | cli | def cli(env, zone):
"""Print zone in BIND format."""
manager = SoftLayer.DNSManager(env.client)
zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')
env.fout(manager.dump_zone(zone_id)) | python | def cli(env, zone):
"""Print zone in BIND format."""
manager = SoftLayer.DNSManager(env.client)
zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')
env.fout(manager.dump_zone(zone_id)) | [
"def",
"cli",
"(",
"env",
",",
"zone",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"DNSManager",
"(",
"env",
".",
"client",
")",
"zone_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"manager",
".",
"resolve_ids",
",",
"zone",
",",
"name",
"=",
"'zone'",
")",
"env",
".",
"fout",
"(",
"manager",
".",
"dump_zone",
"(",
"zone_id",
")",
")"
] | Print zone in BIND format. | [
"Print",
"zone",
"in",
"BIND",
"format",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/zone_print.py#L14-L19 |
1,826 | softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | rescue | def rescue(env, identifier):
"""Reboot into a rescue image."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm("This action will reboot this VSI. Continue?")):
raise exceptions.CLIAbort('Aborted')
vsi.rescue(vs_id) | python | def rescue(env, identifier):
"""Reboot into a rescue image."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm("This action will reboot this VSI. Continue?")):
raise exceptions.CLIAbort('Aborted')
vsi.rescue(vs_id) | [
"def",
"rescue",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"\"This action will reboot this VSI. Continue?\"",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted'",
")",
"vsi",
".",
"rescue",
"(",
"vs_id",
")"
] | Reboot into a rescue image. | [
"Reboot",
"into",
"a",
"rescue",
"image",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L16-L25 |
1,827 | softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | reboot | def reboot(env, identifier, hard):
"""Reboot an active virtual server."""
virtual_guest = env.client['Virtual_Guest']
mgr = SoftLayer.HardwareManager(env.client)
vs_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm('This will reboot the VS with id %s. '
'Continue?' % vs_id)):
raise exceptions.CLIAbort('Aborted.')
if hard is True:
virtual_guest.rebootHard(id=vs_id)
elif hard is False:
virtual_guest.rebootSoft(id=vs_id)
else:
virtual_guest.rebootDefault(id=vs_id) | python | def reboot(env, identifier, hard):
"""Reboot an active virtual server."""
virtual_guest = env.client['Virtual_Guest']
mgr = SoftLayer.HardwareManager(env.client)
vs_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm('This will reboot the VS with id %s. '
'Continue?' % vs_id)):
raise exceptions.CLIAbort('Aborted.')
if hard is True:
virtual_guest.rebootHard(id=vs_id)
elif hard is False:
virtual_guest.rebootSoft(id=vs_id)
else:
virtual_guest.rebootDefault(id=vs_id) | [
"def",
"reboot",
"(",
"env",
",",
"identifier",
",",
"hard",
")",
":",
"virtual_guest",
"=",
"env",
".",
"client",
"[",
"'Virtual_Guest'",
"]",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"mgr",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"'This will reboot the VS with id %s. '",
"'Continue?'",
"%",
"vs_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"if",
"hard",
"is",
"True",
":",
"virtual_guest",
".",
"rebootHard",
"(",
"id",
"=",
"vs_id",
")",
"elif",
"hard",
"is",
"False",
":",
"virtual_guest",
".",
"rebootSoft",
"(",
"id",
"=",
"vs_id",
")",
"else",
":",
"virtual_guest",
".",
"rebootDefault",
"(",
"id",
"=",
"vs_id",
")"
] | Reboot an active virtual server. | [
"Reboot",
"an",
"active",
"virtual",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L34-L50 |
1,828 | softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | power_off | def power_off(env, identifier, hard):
"""Power off an active virtual server."""
virtual_guest = env.client['Virtual_Guest']
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm('This will power off the VS with id %s. '
'Continue?' % vs_id)):
raise exceptions.CLIAbort('Aborted.')
if hard:
virtual_guest.powerOff(id=vs_id)
else:
virtual_guest.powerOffSoft(id=vs_id) | python | def power_off(env, identifier, hard):
"""Power off an active virtual server."""
virtual_guest = env.client['Virtual_Guest']
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm('This will power off the VS with id %s. '
'Continue?' % vs_id)):
raise exceptions.CLIAbort('Aborted.')
if hard:
virtual_guest.powerOff(id=vs_id)
else:
virtual_guest.powerOffSoft(id=vs_id) | [
"def",
"power_off",
"(",
"env",
",",
"identifier",
",",
"hard",
")",
":",
"virtual_guest",
"=",
"env",
".",
"client",
"[",
"'Virtual_Guest'",
"]",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"'This will power off the VS with id %s. '",
"'Continue?'",
"%",
"vs_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"if",
"hard",
":",
"virtual_guest",
".",
"powerOff",
"(",
"id",
"=",
"vs_id",
")",
"else",
":",
"virtual_guest",
".",
"powerOffSoft",
"(",
"id",
"=",
"vs_id",
")"
] | Power off an active virtual server. | [
"Power",
"off",
"an",
"active",
"virtual",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L57-L71 |
1,829 | softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | power_on | def power_on(env, identifier):
"""Power on a virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
env.client['Virtual_Guest'].powerOn(id=vs_id) | python | def power_on(env, identifier):
"""Power on a virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
env.client['Virtual_Guest'].powerOn(id=vs_id) | [
"def",
"power_on",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"env",
".",
"client",
"[",
"'Virtual_Guest'",
"]",
".",
"powerOn",
"(",
"id",
"=",
"vs_id",
")"
] | Power on a virtual server. | [
"Power",
"on",
"a",
"virtual",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L77-L82 |
1,830 | softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | pause | def pause(env, identifier):
"""Pauses an active virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm('This will pause the VS with id %s. Continue?'
% vs_id)):
raise exceptions.CLIAbort('Aborted.')
env.client['Virtual_Guest'].pause(id=vs_id) | python | def pause(env, identifier):
"""Pauses an active virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm('This will pause the VS with id %s. Continue?'
% vs_id)):
raise exceptions.CLIAbort('Aborted.')
env.client['Virtual_Guest'].pause(id=vs_id) | [
"def",
"pause",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"if",
"not",
"(",
"env",
".",
"skip_confirmations",
"or",
"formatting",
".",
"confirm",
"(",
"'This will pause the VS with id %s. Continue?'",
"%",
"vs_id",
")",
")",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Aborted.'",
")",
"env",
".",
"client",
"[",
"'Virtual_Guest'",
"]",
".",
"pause",
"(",
"id",
"=",
"vs_id",
")"
] | Pauses an active virtual server. | [
"Pauses",
"an",
"active",
"virtual",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L88-L99 |
1,831 | softlayer/softlayer-python | SoftLayer/CLI/virt/power.py | resume | def resume(env, identifier):
"""Resumes a paused virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
env.client['Virtual_Guest'].resume(id=vs_id) | python | def resume(env, identifier):
"""Resumes a paused virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
env.client['Virtual_Guest'].resume(id=vs_id) | [
"def",
"resume",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"env",
".",
"client",
"[",
"'Virtual_Guest'",
"]",
".",
"resume",
"(",
"id",
"=",
"vs_id",
")"
] | Resumes a paused virtual server. | [
"Resumes",
"a",
"paused",
"virtual",
"server",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L105-L110 |
1,832 | softlayer/softlayer-python | SoftLayer/CLI/account/summary.py | cli | def cli(env):
"""Prints some various bits of information about an account"""
manager = AccountManager(env.client)
summary = manager.get_summary()
env.fout(get_snapshot_table(summary)) | python | def cli(env):
"""Prints some various bits of information about an account"""
manager = AccountManager(env.client)
summary = manager.get_summary()
env.fout(get_snapshot_table(summary)) | [
"def",
"cli",
"(",
"env",
")",
":",
"manager",
"=",
"AccountManager",
"(",
"env",
".",
"client",
")",
"summary",
"=",
"manager",
".",
"get_summary",
"(",
")",
"env",
".",
"fout",
"(",
"get_snapshot_table",
"(",
"summary",
")",
")"
] | Prints some various bits of information about an account | [
"Prints",
"some",
"various",
"bits",
"of",
"information",
"about",
"an",
"account"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/summary.py#L13-L18 |
1,833 | softlayer/softlayer-python | SoftLayer/CLI/account/summary.py | get_snapshot_table | def get_snapshot_table(account):
"""Generates a table for printing account summary data"""
table = formatting.KeyValueTable(["Name", "Value"], title="Account Snapshot")
table.align['Name'] = 'r'
table.align['Value'] = 'l'
table.add_row(['Company Name', account.get('companyName', '-')])
table.add_row(['Balance', utils.lookup(account, 'pendingInvoice', 'startingBalance')])
table.add_row(['Upcoming Invoice', utils.lookup(account, 'pendingInvoice', 'invoiceTotalAmount')])
table.add_row(['Image Templates', account.get('blockDeviceTemplateGroupCount', '-')])
table.add_row(['Dedicated Hosts', account.get('dedicatedHostCount', '-')])
table.add_row(['Hardware', account.get('hardwareCount', '-')])
table.add_row(['Virtual Guests', account.get('virtualGuestCount', '-')])
table.add_row(['Domains', account.get('domainCount', '-')])
table.add_row(['Network Storage Volumes', account.get('networkStorageCount', '-')])
table.add_row(['Open Tickets', account.get('openTicketCount', '-')])
table.add_row(['Network Vlans', account.get('networkVlanCount', '-')])
table.add_row(['Subnets', account.get('subnetCount', '-')])
table.add_row(['Users', account.get('userCount', '-')])
return table | python | def get_snapshot_table(account):
"""Generates a table for printing account summary data"""
table = formatting.KeyValueTable(["Name", "Value"], title="Account Snapshot")
table.align['Name'] = 'r'
table.align['Value'] = 'l'
table.add_row(['Company Name', account.get('companyName', '-')])
table.add_row(['Balance', utils.lookup(account, 'pendingInvoice', 'startingBalance')])
table.add_row(['Upcoming Invoice', utils.lookup(account, 'pendingInvoice', 'invoiceTotalAmount')])
table.add_row(['Image Templates', account.get('blockDeviceTemplateGroupCount', '-')])
table.add_row(['Dedicated Hosts', account.get('dedicatedHostCount', '-')])
table.add_row(['Hardware', account.get('hardwareCount', '-')])
table.add_row(['Virtual Guests', account.get('virtualGuestCount', '-')])
table.add_row(['Domains', account.get('domainCount', '-')])
table.add_row(['Network Storage Volumes', account.get('networkStorageCount', '-')])
table.add_row(['Open Tickets', account.get('openTicketCount', '-')])
table.add_row(['Network Vlans', account.get('networkVlanCount', '-')])
table.add_row(['Subnets', account.get('subnetCount', '-')])
table.add_row(['Users', account.get('userCount', '-')])
return table | [
"def",
"get_snapshot_table",
"(",
"account",
")",
":",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"\"Name\"",
",",
"\"Value\"",
"]",
",",
"title",
"=",
"\"Account Snapshot\"",
")",
"table",
".",
"align",
"[",
"'Name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'Value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'Company Name'",
",",
"account",
".",
"get",
"(",
"'companyName'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Balance'",
",",
"utils",
".",
"lookup",
"(",
"account",
",",
"'pendingInvoice'",
",",
"'startingBalance'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Upcoming Invoice'",
",",
"utils",
".",
"lookup",
"(",
"account",
",",
"'pendingInvoice'",
",",
"'invoiceTotalAmount'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Image Templates'",
",",
"account",
".",
"get",
"(",
"'blockDeviceTemplateGroupCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Dedicated Hosts'",
",",
"account",
".",
"get",
"(",
"'dedicatedHostCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Hardware'",
",",
"account",
".",
"get",
"(",
"'hardwareCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Virtual Guests'",
",",
"account",
".",
"get",
"(",
"'virtualGuestCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Domains'",
",",
"account",
".",
"get",
"(",
"'domainCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Network Storage Volumes'",
",",
"account",
".",
"get",
"(",
"'networkStorageCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Open Tickets'",
",",
"account",
".",
"get",
"(",
"'openTicketCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Network Vlans'",
",",
"account",
".",
"get",
"(",
"'networkVlanCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Subnets'",
",",
"account",
".",
"get",
"(",
"'subnetCount'",
",",
"'-'",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'Users'",
",",
"account",
".",
"get",
"(",
"'userCount'",
",",
"'-'",
")",
"]",
")",
"return",
"table"
] | Generates a table for printing account summary data | [
"Generates",
"a",
"table",
"for",
"printing",
"account",
"summary",
"data"
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/summary.py#L21-L39 |
1,834 | softlayer/softlayer-python | SoftLayer/CLI/metadata.py | cli | def cli(env, prop):
"""Find details about this machine."""
try:
if prop == 'network':
env.fout(get_network())
return
meta_prop = META_MAPPING.get(prop) or prop
env.fout(SoftLayer.MetadataManager().get(meta_prop))
except SoftLayer.TransportError:
raise exceptions.CLIAbort(
'Cannot connect to the backend service address. Make sure '
'this command is being ran from a device on the backend '
'network.') | python | def cli(env, prop):
"""Find details about this machine."""
try:
if prop == 'network':
env.fout(get_network())
return
meta_prop = META_MAPPING.get(prop) or prop
env.fout(SoftLayer.MetadataManager().get(meta_prop))
except SoftLayer.TransportError:
raise exceptions.CLIAbort(
'Cannot connect to the backend service address. Make sure '
'this command is being ran from a device on the backend '
'network.') | [
"def",
"cli",
"(",
"env",
",",
"prop",
")",
":",
"try",
":",
"if",
"prop",
"==",
"'network'",
":",
"env",
".",
"fout",
"(",
"get_network",
"(",
")",
")",
"return",
"meta_prop",
"=",
"META_MAPPING",
".",
"get",
"(",
"prop",
")",
"or",
"prop",
"env",
".",
"fout",
"(",
"SoftLayer",
".",
"MetadataManager",
"(",
")",
".",
"get",
"(",
"meta_prop",
")",
")",
"except",
"SoftLayer",
".",
"TransportError",
":",
"raise",
"exceptions",
".",
"CLIAbort",
"(",
"'Cannot connect to the backend service address. Make sure '",
"'this command is being ran from a device on the backend '",
"'network.'",
")"
] | Find details about this machine. | [
"Find",
"details",
"about",
"this",
"machine",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/metadata.py#L50-L64 |
1,835 | softlayer/softlayer-python | SoftLayer/CLI/metadata.py | get_network | def get_network():
"""Returns a list of tables with public and private network details."""
meta = SoftLayer.MetadataManager()
network_tables = []
for network_func in [meta.public_network, meta.private_network]:
network = network_func()
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['mac addresses',
formatting.listing(network['mac_addresses'],
separator=',')])
table.add_row(['router', network['router']])
table.add_row(['vlans',
formatting.listing(network['vlans'], separator=',')])
table.add_row(['vlan ids',
formatting.listing(network['vlan_ids'], separator=',')])
network_tables.append(table)
return network_tables | python | def get_network():
"""Returns a list of tables with public and private network details."""
meta = SoftLayer.MetadataManager()
network_tables = []
for network_func in [meta.public_network, meta.private_network]:
network = network_func()
table = formatting.KeyValueTable(['name', 'value'])
table.align['name'] = 'r'
table.align['value'] = 'l'
table.add_row(['mac addresses',
formatting.listing(network['mac_addresses'],
separator=',')])
table.add_row(['router', network['router']])
table.add_row(['vlans',
formatting.listing(network['vlans'], separator=',')])
table.add_row(['vlan ids',
formatting.listing(network['vlan_ids'], separator=',')])
network_tables.append(table)
return network_tables | [
"def",
"get_network",
"(",
")",
":",
"meta",
"=",
"SoftLayer",
".",
"MetadataManager",
"(",
")",
"network_tables",
"=",
"[",
"]",
"for",
"network_func",
"in",
"[",
"meta",
".",
"public_network",
",",
"meta",
".",
"private_network",
"]",
":",
"network",
"=",
"network_func",
"(",
")",
"table",
"=",
"formatting",
".",
"KeyValueTable",
"(",
"[",
"'name'",
",",
"'value'",
"]",
")",
"table",
".",
"align",
"[",
"'name'",
"]",
"=",
"'r'",
"table",
".",
"align",
"[",
"'value'",
"]",
"=",
"'l'",
"table",
".",
"add_row",
"(",
"[",
"'mac addresses'",
",",
"formatting",
".",
"listing",
"(",
"network",
"[",
"'mac_addresses'",
"]",
",",
"separator",
"=",
"','",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'router'",
",",
"network",
"[",
"'router'",
"]",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'vlans'",
",",
"formatting",
".",
"listing",
"(",
"network",
"[",
"'vlans'",
"]",
",",
"separator",
"=",
"','",
")",
"]",
")",
"table",
".",
"add_row",
"(",
"[",
"'vlan ids'",
",",
"formatting",
".",
"listing",
"(",
"network",
"[",
"'vlan_ids'",
"]",
",",
"separator",
"=",
"','",
")",
"]",
")",
"network_tables",
".",
"append",
"(",
"table",
")",
"return",
"network_tables"
] | Returns a list of tables with public and private network details. | [
"Returns",
"a",
"list",
"of",
"tables",
"with",
"public",
"and",
"private",
"network",
"details",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/metadata.py#L67-L87 |
1,836 | softlayer/softlayer-python | SoftLayer/CLI/columns.py | get_formatter | def get_formatter(columns):
"""This function returns a callback to use with click options.
The returned function parses a comma-separated value and returns a new
ColumnFormatter.
:param columns: a list of Column instances
"""
column_map = dict((column.name, column) for column in columns)
def validate(ctx, param, value):
"""Click validation function."""
if value == '':
raise click.BadParameter('At least one column is required.')
formatter = ColumnFormatter()
for column in [col.strip() for col in value.split(',')]:
if column in column_map:
formatter.add_column(column_map[column])
else:
formatter.add_column(Column(column, column.split('.')))
return formatter
return validate | python | def get_formatter(columns):
"""This function returns a callback to use with click options.
The returned function parses a comma-separated value and returns a new
ColumnFormatter.
:param columns: a list of Column instances
"""
column_map = dict((column.name, column) for column in columns)
def validate(ctx, param, value):
"""Click validation function."""
if value == '':
raise click.BadParameter('At least one column is required.')
formatter = ColumnFormatter()
for column in [col.strip() for col in value.split(',')]:
if column in column_map:
formatter.add_column(column_map[column])
else:
formatter.add_column(Column(column, column.split('.')))
return formatter
return validate | [
"def",
"get_formatter",
"(",
"columns",
")",
":",
"column_map",
"=",
"dict",
"(",
"(",
"column",
".",
"name",
",",
"column",
")",
"for",
"column",
"in",
"columns",
")",
"def",
"validate",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"\"\"\"Click validation function.\"\"\"",
"if",
"value",
"==",
"''",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"'At least one column is required.'",
")",
"formatter",
"=",
"ColumnFormatter",
"(",
")",
"for",
"column",
"in",
"[",
"col",
".",
"strip",
"(",
")",
"for",
"col",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
":",
"if",
"column",
"in",
"column_map",
":",
"formatter",
".",
"add_column",
"(",
"column_map",
"[",
"column",
"]",
")",
"else",
":",
"formatter",
".",
"add_column",
"(",
"Column",
"(",
"column",
",",
"column",
".",
"split",
"(",
"'.'",
")",
")",
")",
"return",
"formatter",
"return",
"validate"
] | This function returns a callback to use with click options.
The returned function parses a comma-separated value and returns a new
ColumnFormatter.
:param columns: a list of Column instances | [
"This",
"function",
"returns",
"a",
"callback",
"to",
"use",
"with",
"click",
"options",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/columns.py#L57-L82 |
1,837 | softlayer/softlayer-python | SoftLayer/CLI/columns.py | ColumnFormatter.add_column | def add_column(self, column):
"""Add a new column along with a formatting function."""
self.columns.append(column.name)
self.column_funcs.append(column.path)
if column.mask is not None:
self.mask_parts.add(column.mask) | python | def add_column(self, column):
"""Add a new column along with a formatting function."""
self.columns.append(column.name)
self.column_funcs.append(column.path)
if column.mask is not None:
self.mask_parts.add(column.mask) | [
"def",
"add_column",
"(",
"self",
",",
"column",
")",
":",
"self",
".",
"columns",
".",
"append",
"(",
"column",
".",
"name",
")",
"self",
".",
"column_funcs",
".",
"append",
"(",
"column",
".",
"path",
")",
"if",
"column",
".",
"mask",
"is",
"not",
"None",
":",
"self",
".",
"mask_parts",
".",
"add",
"(",
"column",
".",
"mask",
")"
] | Add a new column along with a formatting function. | [
"Add",
"a",
"new",
"column",
"along",
"with",
"a",
"formatting",
"function",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/columns.py#L36-L42 |
1,838 | softlayer/softlayer-python | SoftLayer/CLI/columns.py | ColumnFormatter.row | def row(self, data):
"""Return a formatted row for the given data."""
for column in self.column_funcs:
if callable(column):
yield column(data)
else:
yield utils.lookup(data, *column) | python | def row(self, data):
"""Return a formatted row for the given data."""
for column in self.column_funcs:
if callable(column):
yield column(data)
else:
yield utils.lookup(data, *column) | [
"def",
"row",
"(",
"self",
",",
"data",
")",
":",
"for",
"column",
"in",
"self",
".",
"column_funcs",
":",
"if",
"callable",
"(",
"column",
")",
":",
"yield",
"column",
"(",
"data",
")",
"else",
":",
"yield",
"utils",
".",
"lookup",
"(",
"data",
",",
"*",
"column",
")"
] | Return a formatted row for the given data. | [
"Return",
"a",
"formatted",
"row",
"for",
"the",
"given",
"data",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/columns.py#L44-L50 |
1,839 | softlayer/softlayer-python | SoftLayer/CLI/cdn/origin_remove.py | cli | def cli(env, account_id, origin_id):
"""Remove an origin pull mapping."""
manager = SoftLayer.CDNManager(env.client)
manager.remove_origin(account_id, origin_id) | python | def cli(env, account_id, origin_id):
"""Remove an origin pull mapping."""
manager = SoftLayer.CDNManager(env.client)
manager.remove_origin(account_id, origin_id) | [
"def",
"cli",
"(",
"env",
",",
"account_id",
",",
"origin_id",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"CDNManager",
"(",
"env",
".",
"client",
")",
"manager",
".",
"remove_origin",
"(",
"account_id",
",",
"origin_id",
")"
] | Remove an origin pull mapping. | [
"Remove",
"an",
"origin",
"pull",
"mapping",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/origin_remove.py#L14-L18 |
1,840 | softlayer/softlayer-python | SoftLayer/CLI/cdn/list.py | cli | def cli(env, sortby):
"""List all CDN accounts."""
manager = SoftLayer.CDNManager(env.client)
accounts = manager.list_accounts()
table = formatting.Table(['id',
'account_name',
'type',
'created',
'notes'])
for account in accounts:
table.add_row([
account['id'],
account['cdnAccountName'],
account['cdnSolutionName'],
account['createDate'],
account.get('cdnAccountNote', formatting.blank())
])
table.sortby = sortby
env.fout(table) | python | def cli(env, sortby):
"""List all CDN accounts."""
manager = SoftLayer.CDNManager(env.client)
accounts = manager.list_accounts()
table = formatting.Table(['id',
'account_name',
'type',
'created',
'notes'])
for account in accounts:
table.add_row([
account['id'],
account['cdnAccountName'],
account['cdnSolutionName'],
account['createDate'],
account.get('cdnAccountNote', formatting.blank())
])
table.sortby = sortby
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"sortby",
")",
":",
"manager",
"=",
"SoftLayer",
".",
"CDNManager",
"(",
"env",
".",
"client",
")",
"accounts",
"=",
"manager",
".",
"list_accounts",
"(",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"'id'",
",",
"'account_name'",
",",
"'type'",
",",
"'created'",
",",
"'notes'",
"]",
")",
"for",
"account",
"in",
"accounts",
":",
"table",
".",
"add_row",
"(",
"[",
"account",
"[",
"'id'",
"]",
",",
"account",
"[",
"'cdnAccountName'",
"]",
",",
"account",
"[",
"'cdnSolutionName'",
"]",
",",
"account",
"[",
"'createDate'",
"]",
",",
"account",
".",
"get",
"(",
"'cdnAccountNote'",
",",
"formatting",
".",
"blank",
"(",
")",
")",
"]",
")",
"table",
".",
"sortby",
"=",
"sortby",
"env",
".",
"fout",
"(",
"table",
")"
] | List all CDN accounts. | [
"List",
"all",
"CDN",
"accounts",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/list.py#L22-L43 |
1,841 | softlayer/softlayer-python | SoftLayer/CLI/file/snapshot/list.py | cli | def cli(env, volume_id, sortby, columns):
"""List file storage snapshots."""
file_manager = SoftLayer.FileStorageManager(env.client)
snapshots = file_manager.get_file_volume_snapshot_list(
volume_id,
mask=columns.mask()
)
table = formatting.Table(columns.columns)
table.sortby = sortby
for snapshot in snapshots:
table.add_row([value or formatting.blank()
for value in columns.row(snapshot)])
env.fout(table) | python | def cli(env, volume_id, sortby, columns):
"""List file storage snapshots."""
file_manager = SoftLayer.FileStorageManager(env.client)
snapshots = file_manager.get_file_volume_snapshot_list(
volume_id,
mask=columns.mask()
)
table = formatting.Table(columns.columns)
table.sortby = sortby
for snapshot in snapshots:
table.add_row([value or formatting.blank()
for value in columns.row(snapshot)])
env.fout(table) | [
"def",
"cli",
"(",
"env",
",",
"volume_id",
",",
"sortby",
",",
"columns",
")",
":",
"file_manager",
"=",
"SoftLayer",
".",
"FileStorageManager",
"(",
"env",
".",
"client",
")",
"snapshots",
"=",
"file_manager",
".",
"get_file_volume_snapshot_list",
"(",
"volume_id",
",",
"mask",
"=",
"columns",
".",
"mask",
"(",
")",
")",
"table",
"=",
"formatting",
".",
"Table",
"(",
"columns",
".",
"columns",
")",
"table",
".",
"sortby",
"=",
"sortby",
"for",
"snapshot",
"in",
"snapshots",
":",
"table",
".",
"add_row",
"(",
"[",
"value",
"or",
"formatting",
".",
"blank",
"(",
")",
"for",
"value",
"in",
"columns",
".",
"row",
"(",
"snapshot",
")",
"]",
")",
"env",
".",
"fout",
"(",
"table",
")"
] | List file storage snapshots. | [
"List",
"file",
"storage",
"snapshots",
"."
] | 9f181be08cc3668353b05a6de0cb324f52cff6fa | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/list.py#L38-L53 |
1,842 | 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 |
1,843 | 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 |
1,844 | 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 |
1,845 | 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 |
1,846 | 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 |
1,847 | 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 |
1,848 | 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 |
1,849 | 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 |
1,850 | 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 |
1,851 | 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 |
1,852 | 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 |
1,853 | 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 |
1,854 | 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 |
1,855 | 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 |
1,856 | 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 |
1,857 | 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 |
1,858 | 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 |
1,859 | 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 |
1,860 | 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 |
1,861 | 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 |
1,862 | 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 |
1,863 | 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 |
1,864 | 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 |
1,865 | 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 |
1,866 | 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 |
1,867 | 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 |
1,868 | 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 |
1,869 | 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 |
1,870 | 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 |
1,871 | 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 |
1,872 | 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 |
1,873 | 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 |
1,874 | 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 |
1,875 | 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 |
1,876 | 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 |
1,877 | 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 |
1,878 | 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 |
1,879 | 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 |
1,880 | 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 |
1,881 | 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 |
1,882 | 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 |
1,883 | 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 |
1,884 | 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 |
1,885 | 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 |
1,886 | 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 |
1,887 | 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 |
1,888 | 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 |
1,889 | 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 |
1,890 | 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 |
1,891 | 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 |
1,892 | 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 |
1,893 | 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 |
1,894 | 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 |
1,895 | 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 |
1,896 | 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 |
1,897 | 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 |
1,898 | 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 |
1,899 | 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 |
Subsets and Splits