repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
lago-project/lago | lago/prefix.py | Prefix._create_ssh_keys | def _create_ssh_keys(self):
"""
Generate a pair of ssh keys for this prefix
Returns:
None
Raises:
RuntimeError: if it fails to create the keys
"""
ret, _, _ = utils.run_command(
[
'ssh-keygen',
'-t',
'rsa',
'-m',
'PEM',
'-N',
'',
'-f',
self.paths.ssh_id_rsa(),
]
)
if ret != 0:
raise RuntimeError(
'Failed to crate ssh keys at %s',
self.paths.ssh_id_rsa(),
) | python | def _create_ssh_keys(self):
"""
Generate a pair of ssh keys for this prefix
Returns:
None
Raises:
RuntimeError: if it fails to create the keys
"""
ret, _, _ = utils.run_command(
[
'ssh-keygen',
'-t',
'rsa',
'-m',
'PEM',
'-N',
'',
'-f',
self.paths.ssh_id_rsa(),
]
)
if ret != 0:
raise RuntimeError(
'Failed to crate ssh keys at %s',
self.paths.ssh_id_rsa(),
) | [
"def",
"_create_ssh_keys",
"(",
"self",
")",
":",
"ret",
",",
"_",
",",
"_",
"=",
"utils",
".",
"run_command",
"(",
"[",
"'ssh-keygen'",
",",
"'-t'",
",",
"'rsa'",
",",
"'-m'",
",",
"'PEM'",
",",
"'-N'",
",",
"''",
",",
"'-f'",
",",
"self",
".",
... | Generate a pair of ssh keys for this prefix
Returns:
None
Raises:
RuntimeError: if it fails to create the keys | [
"Generate",
"a",
"pair",
"of",
"ssh",
"keys",
"for",
"this",
"prefix"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L156-L183 | train | 31,700 |
lago-project/lago | lago/prefix.py | Prefix.cleanup | def cleanup(self):
"""
Stops any running entities in the prefix and uninitializes it, usually
you want to do this if you are going to remove the prefix afterwards
Returns:
None
"""
with LogTask('Stop prefix'):
self.stop()
with LogTask("Tag prefix as uninitialized"):
os.unlink(self.paths.prefix_lagofile()) | python | def cleanup(self):
"""
Stops any running entities in the prefix and uninitializes it, usually
you want to do this if you are going to remove the prefix afterwards
Returns:
None
"""
with LogTask('Stop prefix'):
self.stop()
with LogTask("Tag prefix as uninitialized"):
os.unlink(self.paths.prefix_lagofile()) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"with",
"LogTask",
"(",
"'Stop prefix'",
")",
":",
"self",
".",
"stop",
"(",
")",
"with",
"LogTask",
"(",
"\"Tag prefix as uninitialized\"",
")",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"paths",
".",
"prefix_l... | Stops any running entities in the prefix and uninitializes it, usually
you want to do this if you are going to remove the prefix afterwards
Returns:
None | [
"Stops",
"any",
"running",
"entities",
"in",
"the",
"prefix",
"and",
"uninitializes",
"it",
"usually",
"you",
"want",
"to",
"do",
"this",
"if",
"you",
"are",
"going",
"to",
"remove",
"the",
"prefix",
"afterwards"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L228-L239 | train | 31,701 |
lago-project/lago | lago/prefix.py | Prefix._init_net_specs | def _init_net_specs(conf):
"""
Given a configuration specification, initializes all the net
definitions in it so they can be used comfortably
Args:
conf (dict): Configuration specification
Returns:
dict: the adapted new conf
"""
for net_name, net_spec in conf.get('nets', {}).items():
net_spec['name'] = net_name
net_spec['mapping'] = {}
net_spec.setdefault('type', 'nat')
return conf | python | def _init_net_specs(conf):
"""
Given a configuration specification, initializes all the net
definitions in it so they can be used comfortably
Args:
conf (dict): Configuration specification
Returns:
dict: the adapted new conf
"""
for net_name, net_spec in conf.get('nets', {}).items():
net_spec['name'] = net_name
net_spec['mapping'] = {}
net_spec.setdefault('type', 'nat')
return conf | [
"def",
"_init_net_specs",
"(",
"conf",
")",
":",
"for",
"net_name",
",",
"net_spec",
"in",
"conf",
".",
"get",
"(",
"'nets'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"net_spec",
"[",
"'name'",
"]",
"=",
"net_name",
"net_spec",
"[",
"'mapping... | Given a configuration specification, initializes all the net
definitions in it so they can be used comfortably
Args:
conf (dict): Configuration specification
Returns:
dict: the adapted new conf | [
"Given",
"a",
"configuration",
"specification",
"initializes",
"all",
"the",
"net",
"definitions",
"in",
"it",
"so",
"they",
"can",
"be",
"used",
"comfortably"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L242-L258 | train | 31,702 |
lago-project/lago | lago/prefix.py | Prefix._allocate_subnets | def _allocate_subnets(self, conf):
"""
Allocate all the subnets needed by the given configuration spec
Args:
conf (dict): Configuration spec where to get the nets definitions
from
Returns:
tuple(list, dict): allocated subnets and modified conf
"""
allocated_subnets = []
try:
for net_spec in conf.get('nets', {}).itervalues():
if net_spec['type'] != 'nat':
continue
gateway = net_spec.get('gw')
if gateway:
allocated_subnet = self._subnet_store.acquire(
self.paths.uuid(), gateway
)
else:
allocated_subnet = self._subnet_store.acquire(
self.paths.uuid()
)
net_spec['gw'] = str(allocated_subnet.iter_hosts().next())
allocated_subnets.append(allocated_subnet)
except:
self._subnet_store.release(allocated_subnets)
raise
return allocated_subnets, conf | python | def _allocate_subnets(self, conf):
"""
Allocate all the subnets needed by the given configuration spec
Args:
conf (dict): Configuration spec where to get the nets definitions
from
Returns:
tuple(list, dict): allocated subnets and modified conf
"""
allocated_subnets = []
try:
for net_spec in conf.get('nets', {}).itervalues():
if net_spec['type'] != 'nat':
continue
gateway = net_spec.get('gw')
if gateway:
allocated_subnet = self._subnet_store.acquire(
self.paths.uuid(), gateway
)
else:
allocated_subnet = self._subnet_store.acquire(
self.paths.uuid()
)
net_spec['gw'] = str(allocated_subnet.iter_hosts().next())
allocated_subnets.append(allocated_subnet)
except:
self._subnet_store.release(allocated_subnets)
raise
return allocated_subnets, conf | [
"def",
"_allocate_subnets",
"(",
"self",
",",
"conf",
")",
":",
"allocated_subnets",
"=",
"[",
"]",
"try",
":",
"for",
"net_spec",
"in",
"conf",
".",
"get",
"(",
"'nets'",
",",
"{",
"}",
")",
".",
"itervalues",
"(",
")",
":",
"if",
"net_spec",
"[",
... | Allocate all the subnets needed by the given configuration spec
Args:
conf (dict): Configuration spec where to get the nets definitions
from
Returns:
tuple(list, dict): allocated subnets and modified conf | [
"Allocate",
"all",
"the",
"subnets",
"needed",
"by",
"the",
"given",
"configuration",
"spec"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L260-L292 | train | 31,703 |
lago-project/lago | lago/prefix.py | Prefix._select_mgmt_networks | def _select_mgmt_networks(self, conf):
"""
Select management networks. If no management network is found, it will
mark the first network found by sorted the network lists. Also adding
default DNS domain, if none is set.
Args:
conf(spec): spec
"""
nets = conf['nets']
mgmts = sorted(
[
name for name, net in nets.iteritems()
if net.get('management') is True
]
)
if len(mgmts) == 0:
mgmt_name = sorted((nets.keys()))[0]
LOGGER.debug(
'No management network configured, selecting network %s',
mgmt_name
)
nets[mgmt_name]['management'] = True
mgmts.append(mgmt_name)
for mgmt_name in mgmts:
if nets[mgmt_name].get('dns_domain_name', None) is None:
nets[mgmt_name]['dns_domain_name'] = 'lago.local'
return mgmts | python | def _select_mgmt_networks(self, conf):
"""
Select management networks. If no management network is found, it will
mark the first network found by sorted the network lists. Also adding
default DNS domain, if none is set.
Args:
conf(spec): spec
"""
nets = conf['nets']
mgmts = sorted(
[
name for name, net in nets.iteritems()
if net.get('management') is True
]
)
if len(mgmts) == 0:
mgmt_name = sorted((nets.keys()))[0]
LOGGER.debug(
'No management network configured, selecting network %s',
mgmt_name
)
nets[mgmt_name]['management'] = True
mgmts.append(mgmt_name)
for mgmt_name in mgmts:
if nets[mgmt_name].get('dns_domain_name', None) is None:
nets[mgmt_name]['dns_domain_name'] = 'lago.local'
return mgmts | [
"def",
"_select_mgmt_networks",
"(",
"self",
",",
"conf",
")",
":",
"nets",
"=",
"conf",
"[",
"'nets'",
"]",
"mgmts",
"=",
"sorted",
"(",
"[",
"name",
"for",
"name",
",",
"net",
"in",
"nets",
".",
"iteritems",
"(",
")",
"if",
"net",
".",
"get",
"("... | Select management networks. If no management network is found, it will
mark the first network found by sorted the network lists. Also adding
default DNS domain, if none is set.
Args:
conf(spec): spec | [
"Select",
"management",
"networks",
".",
"If",
"no",
"management",
"network",
"is",
"found",
"it",
"will",
"mark",
"the",
"first",
"network",
"found",
"by",
"sorted",
"the",
"network",
"lists",
".",
"Also",
"adding",
"default",
"DNS",
"domain",
"if",
"none",... | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L341-L373 | train | 31,704 |
lago-project/lago | lago/prefix.py | Prefix._register_preallocated_ips | def _register_preallocated_ips(self, conf):
"""
Parse all the domains in the given conf and preallocate all their ips
into the networks mappings, raising exception on duplicated ips or ips
out of the allowed ranges
See Also:
:mod:`lago.subnet_lease`
Args:
conf (dict): Configuration spec to parse
Returns:
None
Raises:
RuntimeError: if there are any duplicated ips or any ip out of the
allowed range
"""
for dom_name, dom_spec in conf.get('domains', {}).items():
for idx, nic in enumerate(dom_spec.get('nics', [])):
if 'ip' not in nic:
continue
net = conf['nets'][nic['net']]
if self._subnet_store.is_leasable_subnet(net['gw']):
nic['ip'] = _create_ip(
net['gw'], int(nic['ip'].split('.')[-1])
)
dom_name = dom_spec['name']
if not _ip_in_subnet(net['gw'], nic['ip']):
raise RuntimeError(
"%s:nic%d's IP [%s] is outside the subnet [%s]" % (
dom_name,
dom_spec['nics'].index(nic),
nic['ip'],
net['gw'],
),
)
if nic['ip'] in net['mapping'].values():
conflict_list = [
name for name, ip in net['mapping'].items()
if ip == net['ip']
]
raise RuntimeError(
'IP %s was to several domains: %s %s' % (
nic['ip'],
dom_name,
' '.join(conflict_list),
),
)
self._add_nic_to_mapping(net, dom_spec, nic) | python | def _register_preallocated_ips(self, conf):
"""
Parse all the domains in the given conf and preallocate all their ips
into the networks mappings, raising exception on duplicated ips or ips
out of the allowed ranges
See Also:
:mod:`lago.subnet_lease`
Args:
conf (dict): Configuration spec to parse
Returns:
None
Raises:
RuntimeError: if there are any duplicated ips or any ip out of the
allowed range
"""
for dom_name, dom_spec in conf.get('domains', {}).items():
for idx, nic in enumerate(dom_spec.get('nics', [])):
if 'ip' not in nic:
continue
net = conf['nets'][nic['net']]
if self._subnet_store.is_leasable_subnet(net['gw']):
nic['ip'] = _create_ip(
net['gw'], int(nic['ip'].split('.')[-1])
)
dom_name = dom_spec['name']
if not _ip_in_subnet(net['gw'], nic['ip']):
raise RuntimeError(
"%s:nic%d's IP [%s] is outside the subnet [%s]" % (
dom_name,
dom_spec['nics'].index(nic),
nic['ip'],
net['gw'],
),
)
if nic['ip'] in net['mapping'].values():
conflict_list = [
name for name, ip in net['mapping'].items()
if ip == net['ip']
]
raise RuntimeError(
'IP %s was to several domains: %s %s' % (
nic['ip'],
dom_name,
' '.join(conflict_list),
),
)
self._add_nic_to_mapping(net, dom_spec, nic) | [
"def",
"_register_preallocated_ips",
"(",
"self",
",",
"conf",
")",
":",
"for",
"dom_name",
",",
"dom_spec",
"in",
"conf",
".",
"get",
"(",
"'domains'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"for",
"idx",
",",
"nic",
"in",
"enumerate",
"("... | Parse all the domains in the given conf and preallocate all their ips
into the networks mappings, raising exception on duplicated ips or ips
out of the allowed ranges
See Also:
:mod:`lago.subnet_lease`
Args:
conf (dict): Configuration spec to parse
Returns:
None
Raises:
RuntimeError: if there are any duplicated ips or any ip out of the
allowed range | [
"Parse",
"all",
"the",
"domains",
"in",
"the",
"given",
"conf",
"and",
"preallocate",
"all",
"their",
"ips",
"into",
"the",
"networks",
"mappings",
"raising",
"exception",
"on",
"duplicated",
"ips",
"or",
"ips",
"out",
"of",
"the",
"allowed",
"ranges"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L406-L460 | train | 31,705 |
lago-project/lago | lago/prefix.py | Prefix._allocate_ips_to_nics | def _allocate_ips_to_nics(self, conf):
"""
For all the nics of all the domains in the conf that have dynamic ip,
allocate one and addit to the network mapping
Args:
conf (dict): Configuration spec to extract the domains from
Returns:
None
"""
for dom_name, dom_spec in conf.get('domains', {}).items():
for idx, nic in enumerate(dom_spec.get('nics', [])):
if 'ip' in nic:
continue
net = self._get_net(conf, dom_name, nic)
if net['type'] != 'nat':
continue
allocated = net['mapping'].values()
vacant = _create_ip(
net['gw'],
set(range(2, 255)).difference(
set([int(ip.split('.')[-1]) for ip in allocated])
).pop()
)
nic['ip'] = vacant
self._add_nic_to_mapping(net, dom_spec, nic) | python | def _allocate_ips_to_nics(self, conf):
"""
For all the nics of all the domains in the conf that have dynamic ip,
allocate one and addit to the network mapping
Args:
conf (dict): Configuration spec to extract the domains from
Returns:
None
"""
for dom_name, dom_spec in conf.get('domains', {}).items():
for idx, nic in enumerate(dom_spec.get('nics', [])):
if 'ip' in nic:
continue
net = self._get_net(conf, dom_name, nic)
if net['type'] != 'nat':
continue
allocated = net['mapping'].values()
vacant = _create_ip(
net['gw'],
set(range(2, 255)).difference(
set([int(ip.split('.')[-1]) for ip in allocated])
).pop()
)
nic['ip'] = vacant
self._add_nic_to_mapping(net, dom_spec, nic) | [
"def",
"_allocate_ips_to_nics",
"(",
"self",
",",
"conf",
")",
":",
"for",
"dom_name",
",",
"dom_spec",
"in",
"conf",
".",
"get",
"(",
"'domains'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"for",
"idx",
",",
"nic",
"in",
"enumerate",
"(",
"... | For all the nics of all the domains in the conf that have dynamic ip,
allocate one and addit to the network mapping
Args:
conf (dict): Configuration spec to extract the domains from
Returns:
None | [
"For",
"all",
"the",
"nics",
"of",
"all",
"the",
"domains",
"in",
"the",
"conf",
"that",
"have",
"dynamic",
"ip",
"allocate",
"one",
"and",
"addit",
"to",
"the",
"network",
"mapping"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L481-L508 | train | 31,706 |
lago-project/lago | lago/prefix.py | Prefix._set_mtu_to_nics | def _set_mtu_to_nics(self, conf):
"""
For all the nics of all the domains in the conf that have MTU set,
save the MTU on the NIC definition.
Args:
conf (dict): Configuration spec to extract the domains from
Returns:
None
"""
for dom_name, dom_spec in conf.get('domains', {}).items():
for idx, nic in enumerate(dom_spec.get('nics', [])):
net = self._get_net(conf, dom_name, nic)
mtu = net.get('mtu', 1500)
if mtu != 1500:
nic['mtu'] = mtu | python | def _set_mtu_to_nics(self, conf):
"""
For all the nics of all the domains in the conf that have MTU set,
save the MTU on the NIC definition.
Args:
conf (dict): Configuration spec to extract the domains from
Returns:
None
"""
for dom_name, dom_spec in conf.get('domains', {}).items():
for idx, nic in enumerate(dom_spec.get('nics', [])):
net = self._get_net(conf, dom_name, nic)
mtu = net.get('mtu', 1500)
if mtu != 1500:
nic['mtu'] = mtu | [
"def",
"_set_mtu_to_nics",
"(",
"self",
",",
"conf",
")",
":",
"for",
"dom_name",
",",
"dom_spec",
"in",
"conf",
".",
"get",
"(",
"'domains'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"for",
"idx",
",",
"nic",
"in",
"enumerate",
"(",
"dom_s... | For all the nics of all the domains in the conf that have MTU set,
save the MTU on the NIC definition.
Args:
conf (dict): Configuration spec to extract the domains from
Returns:
None | [
"For",
"all",
"the",
"nics",
"of",
"all",
"the",
"domains",
"in",
"the",
"conf",
"that",
"have",
"MTU",
"set",
"save",
"the",
"MTU",
"on",
"the",
"NIC",
"definition",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L510-L526 | train | 31,707 |
lago-project/lago | lago/prefix.py | Prefix._config_net_topology | def _config_net_topology(self, conf):
"""
Initialize and populate all the network related elements, like
reserving ips and populating network specs of the given confiiguration
spec
Args:
conf (dict): Configuration spec to initalize
Returns:
None
"""
conf = self._init_net_specs(conf)
mgmts = self._select_mgmt_networks(conf)
self._validate_netconfig(conf)
allocated_subnets, conf = self._allocate_subnets(conf)
try:
self._add_mgmt_to_domains(conf, mgmts)
self._register_preallocated_ips(conf)
self._allocate_ips_to_nics(conf)
self._set_mtu_to_nics(conf)
self._add_dns_records(conf, mgmts)
except:
self._subnet_store.release(allocated_subnets)
raise
return conf | python | def _config_net_topology(self, conf):
"""
Initialize and populate all the network related elements, like
reserving ips and populating network specs of the given confiiguration
spec
Args:
conf (dict): Configuration spec to initalize
Returns:
None
"""
conf = self._init_net_specs(conf)
mgmts = self._select_mgmt_networks(conf)
self._validate_netconfig(conf)
allocated_subnets, conf = self._allocate_subnets(conf)
try:
self._add_mgmt_to_domains(conf, mgmts)
self._register_preallocated_ips(conf)
self._allocate_ips_to_nics(conf)
self._set_mtu_to_nics(conf)
self._add_dns_records(conf, mgmts)
except:
self._subnet_store.release(allocated_subnets)
raise
return conf | [
"def",
"_config_net_topology",
"(",
"self",
",",
"conf",
")",
":",
"conf",
"=",
"self",
".",
"_init_net_specs",
"(",
"conf",
")",
"mgmts",
"=",
"self",
".",
"_select_mgmt_networks",
"(",
"conf",
")",
"self",
".",
"_validate_netconfig",
"(",
"conf",
")",
"a... | Initialize and populate all the network related elements, like
reserving ips and populating network specs of the given confiiguration
spec
Args:
conf (dict): Configuration spec to initalize
Returns:
None | [
"Initialize",
"and",
"populate",
"all",
"the",
"network",
"related",
"elements",
"like",
"reserving",
"ips",
"and",
"populating",
"network",
"specs",
"of",
"the",
"given",
"confiiguration",
"spec"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L528-L553 | train | 31,708 |
lago-project/lago | lago/prefix.py | Prefix._validate_netconfig | def _validate_netconfig(self, conf):
"""
Validate network configuration
Args:
conf(dict): spec
Returns:
None
Raises:
:exc:`~lago.utils.LagoInitException`: If a VM has more than
one management network configured, or a network which is not
management has DNS attributes, or a VM is configured with a
none-existence NIC, or a VM has no management network.
"""
nets = conf.get('nets', {})
if len(nets) == 0:
# TO-DO: add default networking if no network is configured
raise LagoInitException('No networks configured.')
no_mgmt_dns = [
name for name, net in nets.iteritems()
if net.get('management', None) is None and
(net.get('main_dns') or net.get('dns_domain_name'))
]
if len(no_mgmt_dns) > 0 and len(nets.keys()) > 1:
raise LagoInitException(
(
'Networks: {0}, misconfigured, they '
'are not marked as management, but have '
'DNS attributes. DNS is supported '
'only in management networks.'
).format(','.join(no_mgmt_dns))
)
for dom_name, dom_spec in conf['domains'].items():
mgmts = []
for nic in dom_spec['nics']:
net = self._get_net(conf, dom_name, nic)
if net.get('management', False) is True:
mgmts.append(nic['net'])
if len(mgmts) == 0:
raise LagoInitException(
(
'VM {0} has no management network, '
'please connect it to '
'one.'
).format(dom_name)
)
if len(mgmts) > 1:
raise LagoInitException(
(
'VM {0} has more than one management '
'network: {1}. It should have exactly '
'one.'
).format(dom_name, ','.join(mgmts))
) | python | def _validate_netconfig(self, conf):
"""
Validate network configuration
Args:
conf(dict): spec
Returns:
None
Raises:
:exc:`~lago.utils.LagoInitException`: If a VM has more than
one management network configured, or a network which is not
management has DNS attributes, or a VM is configured with a
none-existence NIC, or a VM has no management network.
"""
nets = conf.get('nets', {})
if len(nets) == 0:
# TO-DO: add default networking if no network is configured
raise LagoInitException('No networks configured.')
no_mgmt_dns = [
name for name, net in nets.iteritems()
if net.get('management', None) is None and
(net.get('main_dns') or net.get('dns_domain_name'))
]
if len(no_mgmt_dns) > 0 and len(nets.keys()) > 1:
raise LagoInitException(
(
'Networks: {0}, misconfigured, they '
'are not marked as management, but have '
'DNS attributes. DNS is supported '
'only in management networks.'
).format(','.join(no_mgmt_dns))
)
for dom_name, dom_spec in conf['domains'].items():
mgmts = []
for nic in dom_spec['nics']:
net = self._get_net(conf, dom_name, nic)
if net.get('management', False) is True:
mgmts.append(nic['net'])
if len(mgmts) == 0:
raise LagoInitException(
(
'VM {0} has no management network, '
'please connect it to '
'one.'
).format(dom_name)
)
if len(mgmts) > 1:
raise LagoInitException(
(
'VM {0} has more than one management '
'network: {1}. It should have exactly '
'one.'
).format(dom_name, ','.join(mgmts))
) | [
"def",
"_validate_netconfig",
"(",
"self",
",",
"conf",
")",
":",
"nets",
"=",
"conf",
".",
"get",
"(",
"'nets'",
",",
"{",
"}",
")",
"if",
"len",
"(",
"nets",
")",
"==",
"0",
":",
"# TO-DO: add default networking if no network is configured",
"raise",
"Lago... | Validate network configuration
Args:
conf(dict): spec
Returns:
None
Raises:
:exc:`~lago.utils.LagoInitException`: If a VM has more than
one management network configured, or a network which is not
management has DNS attributes, or a VM is configured with a
none-existence NIC, or a VM has no management network. | [
"Validate",
"network",
"configuration"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L573-L633 | train | 31,709 |
lago-project/lago | lago/prefix.py | Prefix._create_disk | def _create_disk(
self,
name,
spec,
template_repo=None,
template_store=None,
):
"""
Creates a disc with the given name from the given repo or store
Args:
name (str): Name of the domain to create the disk for
spec (dict): Specification of the disk to create
template_repo (TemplateRepository or None): template repo instance
to use
template_store (TemplateStore or None): template store instance to
use
Returns:
Tuple(str, dict): Path to the disk and disk metadata
Raises:
RuntimeError: If the type of the disk is not supported or failed to
create the disk
"""
LOGGER.debug("Spec: %s" % spec)
with LogTask("Create disk %s" % spec['name']):
disk_metadata = {}
if spec['type'] == 'template':
disk_path, disk_metadata = self._handle_template(
host_name=name,
template_spec=spec,
template_repo=template_repo,
template_store=template_store,
)
elif spec['type'] == 'empty':
disk_path, disk_metadata = self._handle_empty_disk(
host_name=name,
disk_spec=spec,
)
elif spec['type'] == 'file':
disk_path, disk_metadata = self._handle_file_disk(
disk_spec=spec,
)
else:
raise RuntimeError('Unknown drive spec %s' % str(spec))
return disk_path, disk_metadata | python | def _create_disk(
self,
name,
spec,
template_repo=None,
template_store=None,
):
"""
Creates a disc with the given name from the given repo or store
Args:
name (str): Name of the domain to create the disk for
spec (dict): Specification of the disk to create
template_repo (TemplateRepository or None): template repo instance
to use
template_store (TemplateStore or None): template store instance to
use
Returns:
Tuple(str, dict): Path to the disk and disk metadata
Raises:
RuntimeError: If the type of the disk is not supported or failed to
create the disk
"""
LOGGER.debug("Spec: %s" % spec)
with LogTask("Create disk %s" % spec['name']):
disk_metadata = {}
if spec['type'] == 'template':
disk_path, disk_metadata = self._handle_template(
host_name=name,
template_spec=spec,
template_repo=template_repo,
template_store=template_store,
)
elif spec['type'] == 'empty':
disk_path, disk_metadata = self._handle_empty_disk(
host_name=name,
disk_spec=spec,
)
elif spec['type'] == 'file':
disk_path, disk_metadata = self._handle_file_disk(
disk_spec=spec,
)
else:
raise RuntimeError('Unknown drive spec %s' % str(spec))
return disk_path, disk_metadata | [
"def",
"_create_disk",
"(",
"self",
",",
"name",
",",
"spec",
",",
"template_repo",
"=",
"None",
",",
"template_store",
"=",
"None",
",",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Spec: %s\"",
"%",
"spec",
")",
"with",
"LogTask",
"(",
"\"Create disk %s\"",... | Creates a disc with the given name from the given repo or store
Args:
name (str): Name of the domain to create the disk for
spec (dict): Specification of the disk to create
template_repo (TemplateRepository or None): template repo instance
to use
template_store (TemplateStore or None): template store instance to
use
Returns:
Tuple(str, dict): Path to the disk and disk metadata
Raises:
RuntimeError: If the type of the disk is not supported or failed to
create the disk | [
"Creates",
"a",
"disc",
"with",
"the",
"given",
"name",
"from",
"the",
"given",
"repo",
"or",
"store"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L635-L683 | train | 31,710 |
lago-project/lago | lago/prefix.py | Prefix._ova_to_spec | def _ova_to_spec(self, filename):
"""
Retrieve the given ova and makes a template of it.
Creates a disk from network provided ova.
Calculates the needed memory from the ovf.
The disk will be cached in the template repo
Args:
filename(str): the url to retrive the data from
TODO:
* Add hash checking against the server
for faster download and latest version
* Add config script running on host - other place
* Add cloud init support - by using cdroms in other place
* Handle cpu in some way - some other place need to pick it up
* Handle the memory units properly - we just assume MegaBytes
Returns:
list of dict: list with the disk specification
int: VM memory, None if none defined
int: Number of virtual cpus, None if none defined
Raises:
RuntimeError: If the ova format is not supported
TypeError: If the memory units in the ova are noot supported
(currently only 'MegaBytes')
"""
# extract if needed
ova_extracted_dir = os.path.splitext(filename)[0]
if not os.path.exists(ova_extracted_dir):
os.makedirs(ova_extracted_dir)
subprocess.check_output(
["tar", "-xvf", filename, "-C", ova_extracted_dir],
stderr=subprocess.STDOUT
)
# lets find the ovf file
# we expect only one to be
ovf = glob.glob(ova_extracted_dir + "/master/vms/*/*.ovf")
if len(ovf) != 1:
raise RuntimeError("We support only one vm in ova")
image_file = None
memory = None
vcpus = None
# we found our ovf
# lets extract the resources
with open(ovf[0]) as fd:
# lets extract the items
obj = xmltodict.parse(fd.read())
hardware_items = [
section
for section in obj["ovf:Envelope"]["Content"]["Section"]
if section["@xsi:type"] == "ovf:VirtualHardwareSection_Type"
]
if len(hardware_items) != 1:
raise RuntimeError("We support only one machine desc in ova")
hardware_items = hardware_items[0]
for item in hardware_items["Item"]:
# lets test resource types
CPU_RESOURCE = 3
MEMORY_RESOURCE = 4
DISK_RESOURCE = 17
resource_type = int(item["rasd:ResourceType"])
if resource_type == CPU_RESOURCE:
vcpus = int(item["rasd:cpu_per_socket"]) * \
int(item["rasd:num_of_sockets"])
elif resource_type == MEMORY_RESOURCE:
memory = int(item["rasd:VirtualQuantity"])
if item["rasd:AllocationUnits"] != "MegaBytes":
raise TypeError(
"Fix me : we need to suport other units too"
)
elif resource_type == DISK_RESOURCE:
image_file = item["rasd:HostResource"]
if image_file is not None:
disk_meta = {"root-partition": "/dev/sda1"}
disk_spec = [
{
"type": "template",
"template_type": "qcow2",
"format": "qcow2",
"dev": "vda",
"name": os.path.basename(image_file),
"path": ova_extracted_dir + "/images/" + image_file,
"metadata": disk_meta
}
]
return disk_spec, memory, vcpus | python | def _ova_to_spec(self, filename):
"""
Retrieve the given ova and makes a template of it.
Creates a disk from network provided ova.
Calculates the needed memory from the ovf.
The disk will be cached in the template repo
Args:
filename(str): the url to retrive the data from
TODO:
* Add hash checking against the server
for faster download and latest version
* Add config script running on host - other place
* Add cloud init support - by using cdroms in other place
* Handle cpu in some way - some other place need to pick it up
* Handle the memory units properly - we just assume MegaBytes
Returns:
list of dict: list with the disk specification
int: VM memory, None if none defined
int: Number of virtual cpus, None if none defined
Raises:
RuntimeError: If the ova format is not supported
TypeError: If the memory units in the ova are noot supported
(currently only 'MegaBytes')
"""
# extract if needed
ova_extracted_dir = os.path.splitext(filename)[0]
if not os.path.exists(ova_extracted_dir):
os.makedirs(ova_extracted_dir)
subprocess.check_output(
["tar", "-xvf", filename, "-C", ova_extracted_dir],
stderr=subprocess.STDOUT
)
# lets find the ovf file
# we expect only one to be
ovf = glob.glob(ova_extracted_dir + "/master/vms/*/*.ovf")
if len(ovf) != 1:
raise RuntimeError("We support only one vm in ova")
image_file = None
memory = None
vcpus = None
# we found our ovf
# lets extract the resources
with open(ovf[0]) as fd:
# lets extract the items
obj = xmltodict.parse(fd.read())
hardware_items = [
section
for section in obj["ovf:Envelope"]["Content"]["Section"]
if section["@xsi:type"] == "ovf:VirtualHardwareSection_Type"
]
if len(hardware_items) != 1:
raise RuntimeError("We support only one machine desc in ova")
hardware_items = hardware_items[0]
for item in hardware_items["Item"]:
# lets test resource types
CPU_RESOURCE = 3
MEMORY_RESOURCE = 4
DISK_RESOURCE = 17
resource_type = int(item["rasd:ResourceType"])
if resource_type == CPU_RESOURCE:
vcpus = int(item["rasd:cpu_per_socket"]) * \
int(item["rasd:num_of_sockets"])
elif resource_type == MEMORY_RESOURCE:
memory = int(item["rasd:VirtualQuantity"])
if item["rasd:AllocationUnits"] != "MegaBytes":
raise TypeError(
"Fix me : we need to suport other units too"
)
elif resource_type == DISK_RESOURCE:
image_file = item["rasd:HostResource"]
if image_file is not None:
disk_meta = {"root-partition": "/dev/sda1"}
disk_spec = [
{
"type": "template",
"template_type": "qcow2",
"format": "qcow2",
"dev": "vda",
"name": os.path.basename(image_file),
"path": ova_extracted_dir + "/images/" + image_file,
"metadata": disk_meta
}
]
return disk_spec, memory, vcpus | [
"def",
"_ova_to_spec",
"(",
"self",
",",
"filename",
")",
":",
"# extract if needed",
"ova_extracted_dir",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"ova_extracted_dir"... | Retrieve the given ova and makes a template of it.
Creates a disk from network provided ova.
Calculates the needed memory from the ovf.
The disk will be cached in the template repo
Args:
filename(str): the url to retrive the data from
TODO:
* Add hash checking against the server
for faster download and latest version
* Add config script running on host - other place
* Add cloud init support - by using cdroms in other place
* Handle cpu in some way - some other place need to pick it up
* Handle the memory units properly - we just assume MegaBytes
Returns:
list of dict: list with the disk specification
int: VM memory, None if none defined
int: Number of virtual cpus, None if none defined
Raises:
RuntimeError: If the ova format is not supported
TypeError: If the memory units in the ova are noot supported
(currently only 'MegaBytes') | [
"Retrieve",
"the",
"given",
"ova",
"and",
"makes",
"a",
"template",
"of",
"it",
".",
"Creates",
"a",
"disk",
"from",
"network",
"provided",
"ova",
".",
"Calculates",
"the",
"needed",
"memory",
"from",
"the",
"ovf",
".",
"The",
"disk",
"will",
"be",
"cach... | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L949-L1046 | train | 31,711 |
lago-project/lago | lago/prefix.py | Prefix._use_prototype | def _use_prototype(self, spec, prototypes):
"""
Populates the given spec with the values of it's declared prototype
Args:
spec (dict): spec to update
prototypes (dict): Configuration spec containing the prototypes
Returns:
dict: updated spec
"""
prototype = spec['based-on']
del spec['based-on']
for attr in prototype:
if attr not in spec:
spec[attr] = copy.deepcopy(prototype[attr])
return spec | python | def _use_prototype(self, spec, prototypes):
"""
Populates the given spec with the values of it's declared prototype
Args:
spec (dict): spec to update
prototypes (dict): Configuration spec containing the prototypes
Returns:
dict: updated spec
"""
prototype = spec['based-on']
del spec['based-on']
for attr in prototype:
if attr not in spec:
spec[attr] = copy.deepcopy(prototype[attr])
return spec | [
"def",
"_use_prototype",
"(",
"self",
",",
"spec",
",",
"prototypes",
")",
":",
"prototype",
"=",
"spec",
"[",
"'based-on'",
"]",
"del",
"spec",
"[",
"'based-on'",
"]",
"for",
"attr",
"in",
"prototype",
":",
"if",
"attr",
"not",
"in",
"spec",
":",
"spe... | Populates the given spec with the values of it's declared prototype
Args:
spec (dict): spec to update
prototypes (dict): Configuration spec containing the prototypes
Returns:
dict: updated spec | [
"Populates",
"the",
"given",
"spec",
"with",
"the",
"values",
"of",
"it",
"s",
"declared",
"prototype"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1048-L1065 | train | 31,712 |
lago-project/lago | lago/prefix.py | Prefix.fetch_url | def fetch_url(self, url):
"""
Retrieves the given url to the prefix
Args:
url(str): Url to retrieve
Returns:
str: path to the downloaded file
"""
url_path = urlparse.urlsplit(url).path
dst_path = os.path.basename(url_path)
dst_path = self.paths.prefixed(dst_path)
with LogTask('Downloading %s' % url):
urllib.urlretrieve(url=os.path.expandvars(url), filename=dst_path)
return dst_path | python | def fetch_url(self, url):
"""
Retrieves the given url to the prefix
Args:
url(str): Url to retrieve
Returns:
str: path to the downloaded file
"""
url_path = urlparse.urlsplit(url).path
dst_path = os.path.basename(url_path)
dst_path = self.paths.prefixed(dst_path)
with LogTask('Downloading %s' % url):
urllib.urlretrieve(url=os.path.expandvars(url), filename=dst_path)
return dst_path | [
"def",
"fetch_url",
"(",
"self",
",",
"url",
")",
":",
"url_path",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
".",
"path",
"dst_path",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"url_path",
")",
"dst_path",
"=",
"self",
".",
"paths",
".",
... | Retrieves the given url to the prefix
Args:
url(str): Url to retrieve
Returns:
str: path to the downloaded file | [
"Retrieves",
"the",
"given",
"url",
"to",
"the",
"prefix"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1067-L1083 | train | 31,713 |
lago-project/lago | lago/prefix.py | Prefix.export_vms | def export_vms(
self,
vms_names=None,
standalone=False,
export_dir='.',
compress=False,
init_file_name='LagoInitFile',
out_format=YAMLOutFormatPlugin(),
collect_only=False,
with_threads=True,
):
"""
Export vm images disks and init file.
The exported images and init file can be used to recreate
the environment.
Args:
vms_names(list of str): Names of the vms to export, if None
export all the vms in the env (default=None)
standalone(bool): If false, export a layered image
(default=False)
export_dir(str): Dir to place the exported images and init file
compress(bool): If True compress the images with xz
(default=False)
init_file_name(str): The name of the exported init file
(default='LagoInitfile')
out_format(:class:`lago.plugins.output.OutFormatPlugin`):
The type of the exported init file (the default is yaml)
collect_only(bool): If True, return only a mapping from vm name
to the disks that will be exported. (default=False)
with_threads(bool): If True, run the export in parallel
(default=True)
Returns
Unless collect_only == True, a mapping between vms' disks.
"""
return self.virt_env.export_vms(
vms_names, standalone, export_dir, compress, init_file_name,
out_format, collect_only, with_threads
) | python | def export_vms(
self,
vms_names=None,
standalone=False,
export_dir='.',
compress=False,
init_file_name='LagoInitFile',
out_format=YAMLOutFormatPlugin(),
collect_only=False,
with_threads=True,
):
"""
Export vm images disks and init file.
The exported images and init file can be used to recreate
the environment.
Args:
vms_names(list of str): Names of the vms to export, if None
export all the vms in the env (default=None)
standalone(bool): If false, export a layered image
(default=False)
export_dir(str): Dir to place the exported images and init file
compress(bool): If True compress the images with xz
(default=False)
init_file_name(str): The name of the exported init file
(default='LagoInitfile')
out_format(:class:`lago.plugins.output.OutFormatPlugin`):
The type of the exported init file (the default is yaml)
collect_only(bool): If True, return only a mapping from vm name
to the disks that will be exported. (default=False)
with_threads(bool): If True, run the export in parallel
(default=True)
Returns
Unless collect_only == True, a mapping between vms' disks.
"""
return self.virt_env.export_vms(
vms_names, standalone, export_dir, compress, init_file_name,
out_format, collect_only, with_threads
) | [
"def",
"export_vms",
"(",
"self",
",",
"vms_names",
"=",
"None",
",",
"standalone",
"=",
"False",
",",
"export_dir",
"=",
"'.'",
",",
"compress",
"=",
"False",
",",
"init_file_name",
"=",
"'LagoInitFile'",
",",
"out_format",
"=",
"YAMLOutFormatPlugin",
"(",
... | Export vm images disks and init file.
The exported images and init file can be used to recreate
the environment.
Args:
vms_names(list of str): Names of the vms to export, if None
export all the vms in the env (default=None)
standalone(bool): If false, export a layered image
(default=False)
export_dir(str): Dir to place the exported images and init file
compress(bool): If True compress the images with xz
(default=False)
init_file_name(str): The name of the exported init file
(default='LagoInitfile')
out_format(:class:`lago.plugins.output.OutFormatPlugin`):
The type of the exported init file (the default is yaml)
collect_only(bool): If True, return only a mapping from vm name
to the disks that will be exported. (default=False)
with_threads(bool): If True, run the export in parallel
(default=True)
Returns
Unless collect_only == True, a mapping between vms' disks. | [
"Export",
"vm",
"images",
"disks",
"and",
"init",
"file",
".",
"The",
"exported",
"images",
"and",
"init",
"file",
"can",
"be",
"used",
"to",
"recreate",
"the",
"environment",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1270-L1310 | train | 31,714 |
lago-project/lago | lago/prefix.py | Prefix.shutdown | def shutdown(self, vm_names=None, reboot=False):
"""
Shutdown this prefix
Args:
vm_names(list of str): List of the vms to shutdown
reboot(bool): If true, reboot the requested vms
Returns:
None
"""
self.virt_env.shutdown(vm_names, reboot) | python | def shutdown(self, vm_names=None, reboot=False):
"""
Shutdown this prefix
Args:
vm_names(list of str): List of the vms to shutdown
reboot(bool): If true, reboot the requested vms
Returns:
None
"""
self.virt_env.shutdown(vm_names, reboot) | [
"def",
"shutdown",
"(",
"self",
",",
"vm_names",
"=",
"None",
",",
"reboot",
"=",
"False",
")",
":",
"self",
".",
"virt_env",
".",
"shutdown",
"(",
"vm_names",
",",
"reboot",
")"
] | Shutdown this prefix
Args:
vm_names(list of str): List of the vms to shutdown
reboot(bool): If true, reboot the requested vms
Returns:
None | [
"Shutdown",
"this",
"prefix"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1339-L1350 | train | 31,715 |
lago-project/lago | lago/prefix.py | Prefix.virt_env | def virt_env(self):
"""
Getter for this instance's virt env, creates it if needed
Returns:
lago.virt.VirtEnv: virt env instance used by this prefix
"""
if self._virt_env is None:
self._virt_env = self._create_virt_env()
return self._virt_env | python | def virt_env(self):
"""
Getter for this instance's virt env, creates it if needed
Returns:
lago.virt.VirtEnv: virt env instance used by this prefix
"""
if self._virt_env is None:
self._virt_env = self._create_virt_env()
return self._virt_env | [
"def",
"virt_env",
"(",
"self",
")",
":",
"if",
"self",
".",
"_virt_env",
"is",
"None",
":",
"self",
".",
"_virt_env",
"=",
"self",
".",
"_create_virt_env",
"(",
")",
"return",
"self",
".",
"_virt_env"
] | Getter for this instance's virt env, creates it if needed
Returns:
lago.virt.VirtEnv: virt env instance used by this prefix | [
"Getter",
"for",
"this",
"instance",
"s",
"virt",
"env",
"creates",
"it",
"if",
"needed"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1395-L1404 | train | 31,716 |
lago-project/lago | lago/prefix.py | Prefix.destroy | def destroy(self):
"""
Destroy this prefix, running any cleanups and removing any files
inside it.
"""
subnets = (
str(net.gw()) for net in self.virt_env.get_nets().itervalues()
)
self._subnet_store.release(subnets)
self.cleanup()
shutil.rmtree(self.paths.prefix_path()) | python | def destroy(self):
"""
Destroy this prefix, running any cleanups and removing any files
inside it.
"""
subnets = (
str(net.gw()) for net in self.virt_env.get_nets().itervalues()
)
self._subnet_store.release(subnets)
self.cleanup()
shutil.rmtree(self.paths.prefix_path()) | [
"def",
"destroy",
"(",
"self",
")",
":",
"subnets",
"=",
"(",
"str",
"(",
"net",
".",
"gw",
"(",
")",
")",
"for",
"net",
"in",
"self",
".",
"virt_env",
".",
"get_nets",
"(",
")",
".",
"itervalues",
"(",
")",
")",
"self",
".",
"_subnet_store",
"."... | Destroy this prefix, running any cleanups and removing any files
inside it. | [
"Destroy",
"this",
"prefix",
"running",
"any",
"cleanups",
"and",
"removing",
"any",
"files",
"inside",
"it",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1414-L1426 | train | 31,717 |
lago-project/lago | lago/prefix.py | Prefix.is_prefix | def is_prefix(cls, path):
"""
Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix
"""
lagofile = paths.Paths(path).prefix_lagofile()
return os.path.isfile(lagofile) | python | def is_prefix(cls, path):
"""
Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix
"""
lagofile = paths.Paths(path).prefix_lagofile()
return os.path.isfile(lagofile) | [
"def",
"is_prefix",
"(",
"cls",
",",
"path",
")",
":",
"lagofile",
"=",
"paths",
".",
"Paths",
"(",
"path",
")",
".",
"prefix_lagofile",
"(",
")",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"lagofile",
")"
] | Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix | [
"Check",
"if",
"a",
"path",
"is",
"a",
"valid",
"prefix"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1501-L1512 | train | 31,718 |
lago-project/lago | lago/prefix.py | Prefix._get_scripts | def _get_scripts(self, host_metadata):
"""
Temporary method to retrieve the host scripts
TODO:
remove once the "ovirt-scripts" option gets deprecated
Args:
host_metadata(dict): host metadata to retrieve the scripts for
Returns:
list: deploy scripts for the host, empty if none found
"""
deploy_scripts = host_metadata.get('deploy-scripts', [])
if deploy_scripts:
return deploy_scripts
ovirt_scripts = host_metadata.get('ovirt-scripts', [])
if ovirt_scripts:
warnings.warn(
'Deprecated entry "ovirt-scripts" will not be supported in '
'the future, replace with "deploy-scripts"'
)
return ovirt_scripts | python | def _get_scripts(self, host_metadata):
"""
Temporary method to retrieve the host scripts
TODO:
remove once the "ovirt-scripts" option gets deprecated
Args:
host_metadata(dict): host metadata to retrieve the scripts for
Returns:
list: deploy scripts for the host, empty if none found
"""
deploy_scripts = host_metadata.get('deploy-scripts', [])
if deploy_scripts:
return deploy_scripts
ovirt_scripts = host_metadata.get('ovirt-scripts', [])
if ovirt_scripts:
warnings.warn(
'Deprecated entry "ovirt-scripts" will not be supported in '
'the future, replace with "deploy-scripts"'
)
return ovirt_scripts | [
"def",
"_get_scripts",
"(",
"self",
",",
"host_metadata",
")",
":",
"deploy_scripts",
"=",
"host_metadata",
".",
"get",
"(",
"'deploy-scripts'",
",",
"[",
"]",
")",
"if",
"deploy_scripts",
":",
"return",
"deploy_scripts",
"ovirt_scripts",
"=",
"host_metadata",
"... | Temporary method to retrieve the host scripts
TODO:
remove once the "ovirt-scripts" option gets deprecated
Args:
host_metadata(dict): host metadata to retrieve the scripts for
Returns:
list: deploy scripts for the host, empty if none found | [
"Temporary",
"method",
"to",
"retrieve",
"the",
"host",
"scripts"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1533-L1557 | train | 31,719 |
lago-project/lago | lago/prefix.py | Prefix._set_scripts | def _set_scripts(self, host_metadata, scripts):
"""
Temporary method to set the host scripts
TODO:
remove once the "ovirt-scripts" option gets deprecated
Args:
host_metadata(dict): host metadata to set scripts in
Returns:
dict: the updated metadata
"""
scripts_key = 'deploy-scripts'
if 'ovirt-scritps' in host_metadata:
scripts_key = 'ovirt-scripts'
host_metadata[scripts_key] = scripts
return host_metadata | python | def _set_scripts(self, host_metadata, scripts):
"""
Temporary method to set the host scripts
TODO:
remove once the "ovirt-scripts" option gets deprecated
Args:
host_metadata(dict): host metadata to set scripts in
Returns:
dict: the updated metadata
"""
scripts_key = 'deploy-scripts'
if 'ovirt-scritps' in host_metadata:
scripts_key = 'ovirt-scripts'
host_metadata[scripts_key] = scripts
return host_metadata | [
"def",
"_set_scripts",
"(",
"self",
",",
"host_metadata",
",",
"scripts",
")",
":",
"scripts_key",
"=",
"'deploy-scripts'",
"if",
"'ovirt-scritps'",
"in",
"host_metadata",
":",
"scripts_key",
"=",
"'ovirt-scripts'",
"host_metadata",
"[",
"scripts_key",
"]",
"=",
"... | Temporary method to set the host scripts
TODO:
remove once the "ovirt-scripts" option gets deprecated
Args:
host_metadata(dict): host metadata to set scripts in
Returns:
dict: the updated metadata | [
"Temporary",
"method",
"to",
"set",
"the",
"host",
"scripts"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1559-L1577 | train | 31,720 |
lago-project/lago | lago/prefix.py | Prefix._copy_deploy_scripts_for_hosts | def _copy_deploy_scripts_for_hosts(self, domains):
"""
Copy the deploy scripts for all the domains into the prefix scripts dir
Args:
domains(dict): spec with the domains info as when loaded from the
initfile
Returns:
None
"""
with LogTask('Copying any deploy scripts'):
for host_name, host_spec in domains.iteritems():
host_metadata = host_spec.get('metadata', {})
deploy_scripts = self._get_scripts(host_metadata)
new_scripts = self._copy_delpoy_scripts(deploy_scripts)
self._set_scripts(
host_metadata=host_metadata,
scripts=new_scripts,
)
return domains | python | def _copy_deploy_scripts_for_hosts(self, domains):
"""
Copy the deploy scripts for all the domains into the prefix scripts dir
Args:
domains(dict): spec with the domains info as when loaded from the
initfile
Returns:
None
"""
with LogTask('Copying any deploy scripts'):
for host_name, host_spec in domains.iteritems():
host_metadata = host_spec.get('metadata', {})
deploy_scripts = self._get_scripts(host_metadata)
new_scripts = self._copy_delpoy_scripts(deploy_scripts)
self._set_scripts(
host_metadata=host_metadata,
scripts=new_scripts,
)
return domains | [
"def",
"_copy_deploy_scripts_for_hosts",
"(",
"self",
",",
"domains",
")",
":",
"with",
"LogTask",
"(",
"'Copying any deploy scripts'",
")",
":",
"for",
"host_name",
",",
"host_spec",
"in",
"domains",
".",
"iteritems",
"(",
")",
":",
"host_metadata",
"=",
"host_... | Copy the deploy scripts for all the domains into the prefix scripts dir
Args:
domains(dict): spec with the domains info as when loaded from the
initfile
Returns:
None | [
"Copy",
"the",
"deploy",
"scripts",
"for",
"all",
"the",
"domains",
"into",
"the",
"prefix",
"scripts",
"dir"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1579-L1600 | train | 31,721 |
lago-project/lago | lago/prefix.py | Prefix._copy_delpoy_scripts | def _copy_delpoy_scripts(self, scripts):
"""
Copy the given deploy scripts to the scripts dir in the prefix
Args:
scripts(list of str): list of paths of the scripts to copy to the
prefix
Returns:
list of str: list with the paths to the copied scripts, with a
prefixed with $LAGO_PREFIX_PATH so the full path is not
hardcoded
"""
if not os.path.exists(self.paths.scripts()):
os.makedirs(self.paths.scripts())
new_scripts = []
for script in scripts:
script = os.path.expandvars(script)
if not os.path.exists(script):
raise RuntimeError('Script %s does not exist' % script)
sanitized_name = script.replace('/', '_')
new_script_cur_path = os.path.expandvars(
self.paths.scripts(sanitized_name)
)
shutil.copy(script, new_script_cur_path)
new_script_init_path = os.path.join(
'$LAGO_PREFIX_PATH',
os.path.basename(self.paths.scripts()),
sanitized_name,
)
new_scripts.append(new_script_init_path)
return new_scripts | python | def _copy_delpoy_scripts(self, scripts):
"""
Copy the given deploy scripts to the scripts dir in the prefix
Args:
scripts(list of str): list of paths of the scripts to copy to the
prefix
Returns:
list of str: list with the paths to the copied scripts, with a
prefixed with $LAGO_PREFIX_PATH so the full path is not
hardcoded
"""
if not os.path.exists(self.paths.scripts()):
os.makedirs(self.paths.scripts())
new_scripts = []
for script in scripts:
script = os.path.expandvars(script)
if not os.path.exists(script):
raise RuntimeError('Script %s does not exist' % script)
sanitized_name = script.replace('/', '_')
new_script_cur_path = os.path.expandvars(
self.paths.scripts(sanitized_name)
)
shutil.copy(script, new_script_cur_path)
new_script_init_path = os.path.join(
'$LAGO_PREFIX_PATH',
os.path.basename(self.paths.scripts()),
sanitized_name,
)
new_scripts.append(new_script_init_path)
return new_scripts | [
"def",
"_copy_delpoy_scripts",
"(",
"self",
",",
"scripts",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
".",
"scripts",
"(",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"paths",
".",
"scripts",
"(... | Copy the given deploy scripts to the scripts dir in the prefix
Args:
scripts(list of str): list of paths of the scripts to copy to the
prefix
Returns:
list of str: list with the paths to the copied scripts, with a
prefixed with $LAGO_PREFIX_PATH so the full path is not
hardcoded | [
"Copy",
"the",
"given",
"deploy",
"scripts",
"to",
"the",
"scripts",
"dir",
"in",
"the",
"prefix"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1602-L1637 | train | 31,722 |
lago-project/lago | lago/config.py | ConfigLoad.update_args | def update_args(self, args):
"""Update config dictionary with parsed args, as resolved by argparse.
Only root positional arguments that already exist will overridden.
Args:
args (namespace): args parsed by argparse
"""
for arg in vars(args):
if self.get(arg) and getattr(args, arg) is not None:
self._config[self.root_section][arg] = getattr(args, arg) | python | def update_args(self, args):
"""Update config dictionary with parsed args, as resolved by argparse.
Only root positional arguments that already exist will overridden.
Args:
args (namespace): args parsed by argparse
"""
for arg in vars(args):
if self.get(arg) and getattr(args, arg) is not None:
self._config[self.root_section][arg] = getattr(args, arg) | [
"def",
"update_args",
"(",
"self",
",",
"args",
")",
":",
"for",
"arg",
"in",
"vars",
"(",
"args",
")",
":",
"if",
"self",
".",
"get",
"(",
"arg",
")",
"and",
"getattr",
"(",
"args",
",",
"arg",
")",
"is",
"not",
"None",
":",
"self",
".",
"_con... | Update config dictionary with parsed args, as resolved by argparse.
Only root positional arguments that already exist will overridden.
Args:
args (namespace): args parsed by argparse | [
"Update",
"config",
"dictionary",
"with",
"parsed",
"args",
"as",
"resolved",
"by",
"argparse",
".",
"Only",
"root",
"positional",
"arguments",
"that",
"already",
"exist",
"will",
"overridden",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/config.py#L148-L159 | train | 31,723 |
lago-project/lago | lago/config.py | ConfigLoad.update_parser | def update_parser(self, parser):
"""Update config dictionary with declared arguments in an argparse.parser
New variables will be created, and existing ones overridden.
Args:
parser (argparse.ArgumentParser): parser to read variables from
"""
self._parser = parser
ini_str = argparse_to_ini(parser)
configp = configparser.ConfigParser(allow_no_value=True)
configp.read_dict(self._config)
configp.read_string(ini_str)
self._config.update(
{s: dict(configp.items(s))
for s in configp.sections()}
) | python | def update_parser(self, parser):
"""Update config dictionary with declared arguments in an argparse.parser
New variables will be created, and existing ones overridden.
Args:
parser (argparse.ArgumentParser): parser to read variables from
"""
self._parser = parser
ini_str = argparse_to_ini(parser)
configp = configparser.ConfigParser(allow_no_value=True)
configp.read_dict(self._config)
configp.read_string(ini_str)
self._config.update(
{s: dict(configp.items(s))
for s in configp.sections()}
) | [
"def",
"update_parser",
"(",
"self",
",",
"parser",
")",
":",
"self",
".",
"_parser",
"=",
"parser",
"ini_str",
"=",
"argparse_to_ini",
"(",
"parser",
")",
"configp",
"=",
"configparser",
".",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"configp... | Update config dictionary with declared arguments in an argparse.parser
New variables will be created, and existing ones overridden.
Args:
parser (argparse.ArgumentParser): parser to read variables from | [
"Update",
"config",
"dictionary",
"with",
"declared",
"arguments",
"in",
"an",
"argparse",
".",
"parser",
"New",
"variables",
"will",
"be",
"created",
"and",
"existing",
"ones",
"overridden",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/config.py#L161-L178 | train | 31,724 |
eXamadeus/godaddypy | godaddypy/client.py | Client._request_submit | def _request_submit(self, func, **kwargs):
"""A helper function that will wrap any requests we make.
:param func: a function reference to the requests method to invoke
:param kwargs: any extra arguments that requests.request takes
:type func: (url: Any, data: Any, json: Any, kwargs: Dict)
"""
resp = func(headers=self._get_headers(), **kwargs)
self._log_response_from_method(func.__name__, resp)
self._validate_response_success(resp)
return resp | python | def _request_submit(self, func, **kwargs):
"""A helper function that will wrap any requests we make.
:param func: a function reference to the requests method to invoke
:param kwargs: any extra arguments that requests.request takes
:type func: (url: Any, data: Any, json: Any, kwargs: Dict)
"""
resp = func(headers=self._get_headers(), **kwargs)
self._log_response_from_method(func.__name__, resp)
self._validate_response_success(resp)
return resp | [
"def",
"_request_submit",
"(",
"self",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"func",
"(",
"headers",
"=",
"self",
".",
"_get_headers",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_log_response_from_method",
"(",
"func",... | A helper function that will wrap any requests we make.
:param func: a function reference to the requests method to invoke
:param kwargs: any extra arguments that requests.request takes
:type func: (url: Any, data: Any, json: Any, kwargs: Dict) | [
"A",
"helper",
"function",
"that",
"will",
"wrap",
"any",
"requests",
"we",
"make",
"."
] | 67820604ffe233a67ef9f6b3a59ab85b02653e57 | https://github.com/eXamadeus/godaddypy/blob/67820604ffe233a67ef9f6b3a59ab85b02653e57/godaddypy/client.py#L80-L91 | train | 31,725 |
eXamadeus/godaddypy | godaddypy/client.py | Client.add_records | def add_records(self, domain, records):
"""Adds the specified DNS records to a domain.
:param domain: the domain to add the records to
:param records: the records to add
"""
url = self.API_TEMPLATE + self.RECORDS.format(domain=domain)
self._patch(url, json=records)
self.logger.debug('Added records @ {}'.format(records))
# If we didn't get any exceptions, return True to let the user know
return True | python | def add_records(self, domain, records):
"""Adds the specified DNS records to a domain.
:param domain: the domain to add the records to
:param records: the records to add
"""
url = self.API_TEMPLATE + self.RECORDS.format(domain=domain)
self._patch(url, json=records)
self.logger.debug('Added records @ {}'.format(records))
# If we didn't get any exceptions, return True to let the user know
return True | [
"def",
"add_records",
"(",
"self",
",",
"domain",
",",
"records",
")",
":",
"url",
"=",
"self",
".",
"API_TEMPLATE",
"+",
"self",
".",
"RECORDS",
".",
"format",
"(",
"domain",
"=",
"domain",
")",
"self",
".",
"_patch",
"(",
"url",
",",
"json",
"=",
... | Adds the specified DNS records to a domain.
:param domain: the domain to add the records to
:param records: the records to add | [
"Adds",
"the",
"specified",
"DNS",
"records",
"to",
"a",
"domain",
"."
] | 67820604ffe233a67ef9f6b3a59ab85b02653e57 | https://github.com/eXamadeus/godaddypy/blob/67820604ffe233a67ef9f6b3a59ab85b02653e57/godaddypy/client.py#L113-L124 | train | 31,726 |
eXamadeus/godaddypy | godaddypy/client.py | Client.get_domain_info | def get_domain_info(self, domain):
"""Get the GoDaddy supplied information about a specific domain.
:param domain: The domain to obtain info about.
:type domain: str
:return A JSON string representing the domain information
"""
url = self.API_TEMPLATE + self.DOMAIN_INFO.format(domain=domain)
return self._get_json_from_response(url) | python | def get_domain_info(self, domain):
"""Get the GoDaddy supplied information about a specific domain.
:param domain: The domain to obtain info about.
:type domain: str
:return A JSON string representing the domain information
"""
url = self.API_TEMPLATE + self.DOMAIN_INFO.format(domain=domain)
return self._get_json_from_response(url) | [
"def",
"get_domain_info",
"(",
"self",
",",
"domain",
")",
":",
"url",
"=",
"self",
".",
"API_TEMPLATE",
"+",
"self",
".",
"DOMAIN_INFO",
".",
"format",
"(",
"domain",
"=",
"domain",
")",
"return",
"self",
".",
"_get_json_from_response",
"(",
"url",
")"
] | Get the GoDaddy supplied information about a specific domain.
:param domain: The domain to obtain info about.
:type domain: str
:return A JSON string representing the domain information | [
"Get",
"the",
"GoDaddy",
"supplied",
"information",
"about",
"a",
"specific",
"domain",
"."
] | 67820604ffe233a67ef9f6b3a59ab85b02653e57 | https://github.com/eXamadeus/godaddypy/blob/67820604ffe233a67ef9f6b3a59ab85b02653e57/godaddypy/client.py#L126-L135 | train | 31,727 |
eXamadeus/godaddypy | godaddypy/client.py | Client.get_domains | def get_domains(self):
"""Returns a list of domains for the authenticated user.
"""
url = self.API_TEMPLATE + self.DOMAINS
data = self._get_json_from_response(url)
domains = list()
for item in data:
domain = item['domain']
domains.append(domain)
self.logger.debug('Discovered domains: {}'.format(domain))
return domains | python | def get_domains(self):
"""Returns a list of domains for the authenticated user.
"""
url = self.API_TEMPLATE + self.DOMAINS
data = self._get_json_from_response(url)
domains = list()
for item in data:
domain = item['domain']
domains.append(domain)
self.logger.debug('Discovered domains: {}'.format(domain))
return domains | [
"def",
"get_domains",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"API_TEMPLATE",
"+",
"self",
".",
"DOMAINS",
"data",
"=",
"self",
".",
"_get_json_from_response",
"(",
"url",
")",
"domains",
"=",
"list",
"(",
")",
"for",
"item",
"in",
"data",
":",... | Returns a list of domains for the authenticated user. | [
"Returns",
"a",
"list",
"of",
"domains",
"for",
"the",
"authenticated",
"user",
"."
] | 67820604ffe233a67ef9f6b3a59ab85b02653e57 | https://github.com/eXamadeus/godaddypy/blob/67820604ffe233a67ef9f6b3a59ab85b02653e57/godaddypy/client.py#L137-L149 | train | 31,728 |
eXamadeus/godaddypy | godaddypy/client.py | Client.replace_records | def replace_records(self, domain, records, record_type=None, name=None):
"""This will replace all records at the domain. Record type and record name can be provided to filter
which records to replace.
:param domain: the domain to replace records at
:param records: the records you will be saving
:param record_type: the type of records you want to replace (eg. only replace 'A' records)
:param name: the name of records you want to replace (eg. only replace records with name 'test')
:return: True if no exceptions occurred
"""
url = self._build_record_url(domain, name=name, record_type=record_type)
self._put(url, json=records)
# If we didn't get any exceptions, return True to let the user know
return True | python | def replace_records(self, domain, records, record_type=None, name=None):
"""This will replace all records at the domain. Record type and record name can be provided to filter
which records to replace.
:param domain: the domain to replace records at
:param records: the records you will be saving
:param record_type: the type of records you want to replace (eg. only replace 'A' records)
:param name: the name of records you want to replace (eg. only replace records with name 'test')
:return: True if no exceptions occurred
"""
url = self._build_record_url(domain, name=name, record_type=record_type)
self._put(url, json=records)
# If we didn't get any exceptions, return True to let the user know
return True | [
"def",
"replace_records",
"(",
"self",
",",
"domain",
",",
"records",
",",
"record_type",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_build_record_url",
"(",
"domain",
",",
"name",
"=",
"name",
",",
"record_type",
"=",
"... | This will replace all records at the domain. Record type and record name can be provided to filter
which records to replace.
:param domain: the domain to replace records at
:param records: the records you will be saving
:param record_type: the type of records you want to replace (eg. only replace 'A' records)
:param name: the name of records you want to replace (eg. only replace records with name 'test')
:return: True if no exceptions occurred | [
"This",
"will",
"replace",
"all",
"records",
"at",
"the",
"domain",
".",
"Record",
"type",
"and",
"record",
"name",
"can",
"be",
"provided",
"to",
"filter",
"which",
"records",
"to",
"replace",
"."
] | 67820604ffe233a67ef9f6b3a59ab85b02653e57 | https://github.com/eXamadeus/godaddypy/blob/67820604ffe233a67ef9f6b3a59ab85b02653e57/godaddypy/client.py#L187-L203 | train | 31,729 |
eXamadeus/godaddypy | godaddypy/client.py | Client.update_record | def update_record(self, domain, record, record_type=None, name=None):
"""Call to GoDaddy API to update a single DNS record
:param name: only required if the record is None (deletion)
:param record_type: only required if the record is None (deletion)
:param domain: the domain where the DNS belongs to (eg. 'example.com')
:param record: dict with record info (ex. {'name': 'dynamic', 'ttl': 3600, 'data': '1.1.1.1', 'type': 'A'})
:return: True if no exceptions occurred
"""
if record_type is None:
record_type = record['type']
if name is None:
name = record['name']
url = self.API_TEMPLATE + self.RECORDS_TYPE_NAME.format(domain=domain, type=record_type, name=name)
self._put(url, json=[record])
self.logger.info(
'Updated record. Domain {} name {} type {}'.format(domain, str(record['name']), str(record['type'])))
# If we didn't get any exceptions, return True to let the user know
return True | python | def update_record(self, domain, record, record_type=None, name=None):
"""Call to GoDaddy API to update a single DNS record
:param name: only required if the record is None (deletion)
:param record_type: only required if the record is None (deletion)
:param domain: the domain where the DNS belongs to (eg. 'example.com')
:param record: dict with record info (ex. {'name': 'dynamic', 'ttl': 3600, 'data': '1.1.1.1', 'type': 'A'})
:return: True if no exceptions occurred
"""
if record_type is None:
record_type = record['type']
if name is None:
name = record['name']
url = self.API_TEMPLATE + self.RECORDS_TYPE_NAME.format(domain=domain, type=record_type, name=name)
self._put(url, json=[record])
self.logger.info(
'Updated record. Domain {} name {} type {}'.format(domain, str(record['name']), str(record['type'])))
# If we didn't get any exceptions, return True to let the user know
return True | [
"def",
"update_record",
"(",
"self",
",",
"domain",
",",
"record",
",",
"record_type",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"record_type",
"is",
"None",
":",
"record_type",
"=",
"record",
"[",
"'type'",
"]",
"if",
"name",
"is",
"None"... | Call to GoDaddy API to update a single DNS record
:param name: only required if the record is None (deletion)
:param record_type: only required if the record is None (deletion)
:param domain: the domain where the DNS belongs to (eg. 'example.com')
:param record: dict with record info (ex. {'name': 'dynamic', 'ttl': 3600, 'data': '1.1.1.1', 'type': 'A'})
:return: True if no exceptions occurred | [
"Call",
"to",
"GoDaddy",
"API",
"to",
"update",
"a",
"single",
"DNS",
"record"
] | 67820604ffe233a67ef9f6b3a59ab85b02653e57 | https://github.com/eXamadeus/godaddypy/blob/67820604ffe233a67ef9f6b3a59ab85b02653e57/godaddypy/client.py#L284-L305 | train | 31,730 |
tokibito/django-ftpserver | django_ftpserver/utils.py | parse_ports | def parse_ports(ports_text):
"""Parse ports text
e.g. ports_text = "12345,13000-15000,20000-30000"
"""
ports_set = set()
for bit in ports_text.split(','):
if '-' in bit:
low, high = bit.split('-', 1)
ports_set = ports_set.union(range(int(low), int(high) + 1))
else:
ports_set.add(int(bit))
return sorted(list(ports_set)) | python | def parse_ports(ports_text):
"""Parse ports text
e.g. ports_text = "12345,13000-15000,20000-30000"
"""
ports_set = set()
for bit in ports_text.split(','):
if '-' in bit:
low, high = bit.split('-', 1)
ports_set = ports_set.union(range(int(low), int(high) + 1))
else:
ports_set.add(int(bit))
return sorted(list(ports_set)) | [
"def",
"parse_ports",
"(",
"ports_text",
")",
":",
"ports_set",
"=",
"set",
"(",
")",
"for",
"bit",
"in",
"ports_text",
".",
"split",
"(",
"','",
")",
":",
"if",
"'-'",
"in",
"bit",
":",
"low",
",",
"high",
"=",
"bit",
".",
"split",
"(",
"'-'",
"... | Parse ports text
e.g. ports_text = "12345,13000-15000,20000-30000" | [
"Parse",
"ports",
"text"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/utils.py#L10-L22 | train | 31,731 |
tokibito/django-ftpserver | django_ftpserver/utils.py | make_server | def make_server(
server_class, handler_class, authorizer_class, filesystem_class,
host_port, file_access_user=None, **handler_options):
"""make server instance
:host_port: (host, port)
:file_access_user: 'spam'
handler_options:
* timeout
* passive_ports
* masquerade_address
* certfile
* keyfile
"""
from . import compat
if isinstance(handler_class, compat.string_type):
handler_class = import_class(handler_class)
if isinstance(authorizer_class, compat.string_type):
authorizer_class = import_class(authorizer_class)
if isinstance(filesystem_class, compat.string_type):
filesystem_class = import_class(filesystem_class)
authorizer = authorizer_class(file_access_user)
handler = handler_class
for key, value in handler_options.items():
setattr(handler, key, value)
handler.authorizer = authorizer
if filesystem_class is not None:
handler.abstracted_fs = filesystem_class
return server_class(host_port, handler) | python | def make_server(
server_class, handler_class, authorizer_class, filesystem_class,
host_port, file_access_user=None, **handler_options):
"""make server instance
:host_port: (host, port)
:file_access_user: 'spam'
handler_options:
* timeout
* passive_ports
* masquerade_address
* certfile
* keyfile
"""
from . import compat
if isinstance(handler_class, compat.string_type):
handler_class = import_class(handler_class)
if isinstance(authorizer_class, compat.string_type):
authorizer_class = import_class(authorizer_class)
if isinstance(filesystem_class, compat.string_type):
filesystem_class = import_class(filesystem_class)
authorizer = authorizer_class(file_access_user)
handler = handler_class
for key, value in handler_options.items():
setattr(handler, key, value)
handler.authorizer = authorizer
if filesystem_class is not None:
handler.abstracted_fs = filesystem_class
return server_class(host_port, handler) | [
"def",
"make_server",
"(",
"server_class",
",",
"handler_class",
",",
"authorizer_class",
",",
"filesystem_class",
",",
"host_port",
",",
"file_access_user",
"=",
"None",
",",
"*",
"*",
"handler_options",
")",
":",
"from",
".",
"import",
"compat",
"if",
"isinsta... | make server instance
:host_port: (host, port)
:file_access_user: 'spam'
handler_options:
* timeout
* passive_ports
* masquerade_address
* certfile
* keyfile | [
"make",
"server",
"instance"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/utils.py#L34-L67 | train | 31,732 |
tokibito/django-ftpserver | django_ftpserver/filesystems.py | StoragePatch.apply | def apply(cls, fs):
"""replace bound methods of fs.
"""
logger.debug(
'Patching %s with %s.', fs.__class__.__name__, cls.__name__)
fs._patch = cls
for method_name in cls.patch_methods:
# if fs hasn't method, raise AttributeError.
origin = getattr(fs, method_name)
method = getattr(cls, method_name)
bound_method = method.__get__(fs, fs.__class__)
setattr(fs, method_name, bound_method)
setattr(fs, '_origin_' + method_name, origin) | python | def apply(cls, fs):
"""replace bound methods of fs.
"""
logger.debug(
'Patching %s with %s.', fs.__class__.__name__, cls.__name__)
fs._patch = cls
for method_name in cls.patch_methods:
# if fs hasn't method, raise AttributeError.
origin = getattr(fs, method_name)
method = getattr(cls, method_name)
bound_method = method.__get__(fs, fs.__class__)
setattr(fs, method_name, bound_method)
setattr(fs, '_origin_' + method_name, origin) | [
"def",
"apply",
"(",
"cls",
",",
"fs",
")",
":",
"logger",
".",
"debug",
"(",
"'Patching %s with %s.'",
",",
"fs",
".",
"__class__",
".",
"__name__",
",",
"cls",
".",
"__name__",
")",
"fs",
".",
"_patch",
"=",
"cls",
"for",
"method_name",
"in",
"cls",
... | replace bound methods of fs. | [
"replace",
"bound",
"methods",
"of",
"fs",
"."
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/filesystems.py#L29-L41 | train | 31,733 |
tokibito/django-ftpserver | django_ftpserver/filesystems.py | S3Boto3StoragePatch._exists | def _exists(self, path):
"""S3 directory is not S3Ojbect.
"""
if path.endswith('/'):
return True
return self.storage.exists(path) | python | def _exists(self, path):
"""S3 directory is not S3Ojbect.
"""
if path.endswith('/'):
return True
return self.storage.exists(path) | [
"def",
"_exists",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"return",
"True",
"return",
"self",
".",
"storage",
".",
"exists",
"(",
"path",
")"
] | S3 directory is not S3Ojbect. | [
"S3",
"directory",
"is",
"not",
"S3Ojbect",
"."
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/filesystems.py#L68-L73 | train | 31,734 |
tokibito/django-ftpserver | django_ftpserver/filesystems.py | StorageFS.apply_patch | def apply_patch(self):
"""apply adjustment patch for storage
"""
patch = self.patches.get(self.storage.__class__.__name__)
if patch:
patch.apply(self) | python | def apply_patch(self):
"""apply adjustment patch for storage
"""
patch = self.patches.get(self.storage.__class__.__name__)
if patch:
patch.apply(self) | [
"def",
"apply_patch",
"(",
"self",
")",
":",
"patch",
"=",
"self",
".",
"patches",
".",
"get",
"(",
"self",
".",
"storage",
".",
"__class__",
".",
"__name__",
")",
"if",
"patch",
":",
"patch",
".",
"apply",
"(",
"self",
")"
] | apply adjustment patch for storage | [
"apply",
"adjustment",
"patch",
"for",
"storage"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/filesystems.py#L122-L127 | train | 31,735 |
tokibito/django-ftpserver | django_ftpserver/authorizers.py | FTPAccountAuthorizer.has_user | def has_user(self, username):
"""return True if exists user.
"""
return self.model.objects.filter(
**self._filter_user_by(username)
).exists() | python | def has_user(self, username):
"""return True if exists user.
"""
return self.model.objects.filter(
**self._filter_user_by(username)
).exists() | [
"def",
"has_user",
"(",
"self",
",",
"username",
")",
":",
"return",
"self",
".",
"model",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"self",
".",
"_filter_user_by",
"(",
"username",
")",
")",
".",
"exists",
"(",
")"
] | return True if exists user. | [
"return",
"True",
"if",
"exists",
"user",
"."
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/authorizers.py#L39-L44 | train | 31,736 |
tokibito/django-ftpserver | django_ftpserver/authorizers.py | FTPAccountAuthorizer.get_account | def get_account(self, username):
"""return user by username.
"""
try:
account = self.model.objects.get(
**self._filter_user_by(username)
)
except self.model.DoesNotExist:
return None
return account | python | def get_account(self, username):
"""return user by username.
"""
try:
account = self.model.objects.get(
**self._filter_user_by(username)
)
except self.model.DoesNotExist:
return None
return account | [
"def",
"get_account",
"(",
"self",
",",
"username",
")",
":",
"try",
":",
"account",
"=",
"self",
".",
"model",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"self",
".",
"_filter_user_by",
"(",
"username",
")",
")",
"except",
"self",
".",
"model",
".",... | return user by username. | [
"return",
"user",
"by",
"username",
"."
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/authorizers.py#L46-L55 | train | 31,737 |
tokibito/django-ftpserver | django_ftpserver/authorizers.py | FTPAccountAuthorizer.validate_authentication | def validate_authentication(self, username, password, handler):
"""authenticate user with password
"""
user = authenticate(
**{self.username_field: username, 'password': password}
)
account = self.get_account(username)
if not (user and account):
raise AuthenticationFailed("Authentication failed.") | python | def validate_authentication(self, username, password, handler):
"""authenticate user with password
"""
user = authenticate(
**{self.username_field: username, 'password': password}
)
account = self.get_account(username)
if not (user and account):
raise AuthenticationFailed("Authentication failed.") | [
"def",
"validate_authentication",
"(",
"self",
",",
"username",
",",
"password",
",",
"handler",
")",
":",
"user",
"=",
"authenticate",
"(",
"*",
"*",
"{",
"self",
".",
"username_field",
":",
"username",
",",
"'password'",
":",
"password",
"}",
")",
"accou... | authenticate user with password | [
"authenticate",
"user",
"with",
"password"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/authorizers.py#L57-L65 | train | 31,738 |
tokibito/django-ftpserver | django_ftpserver/authorizers.py | FTPAccountAuthorizer.get_msg_login | def get_msg_login(self, username):
"""message for welcome.
"""
account = self.get_account(username)
if account:
account.update_last_login()
account.save()
return 'welcome.' | python | def get_msg_login(self, username):
"""message for welcome.
"""
account = self.get_account(username)
if account:
account.update_last_login()
account.save()
return 'welcome.' | [
"def",
"get_msg_login",
"(",
"self",
",",
"username",
")",
":",
"account",
"=",
"self",
".",
"get_account",
"(",
"username",
")",
"if",
"account",
":",
"account",
".",
"update_last_login",
"(",
")",
"account",
".",
"save",
"(",
")",
"return",
"'welcome.'"
... | message for welcome. | [
"message",
"for",
"welcome",
"."
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/authorizers.py#L73-L80 | train | 31,739 |
tokibito/django-ftpserver | django_ftpserver/authorizers.py | FTPAccountAuthorizer.has_perm | def has_perm(self, username, perm, path=None):
"""check user permission
"""
account = self.get_account(username)
return account and account.has_perm(perm, path) | python | def has_perm(self, username, perm, path=None):
"""check user permission
"""
account = self.get_account(username)
return account and account.has_perm(perm, path) | [
"def",
"has_perm",
"(",
"self",
",",
"username",
",",
"perm",
",",
"path",
"=",
"None",
")",
":",
"account",
"=",
"self",
".",
"get_account",
"(",
"username",
")",
"return",
"account",
"and",
"account",
".",
"has_perm",
"(",
"perm",
",",
"path",
")"
] | check user permission | [
"check",
"user",
"permission"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/authorizers.py#L85-L89 | train | 31,740 |
tokibito/django-ftpserver | django_ftpserver/authorizers.py | FTPAccountAuthorizer.get_perms | def get_perms(self, username):
"""return user permissions
"""
account = self.get_account(username)
return account and account.get_perms() | python | def get_perms(self, username):
"""return user permissions
"""
account = self.get_account(username)
return account and account.get_perms() | [
"def",
"get_perms",
"(",
"self",
",",
"username",
")",
":",
"account",
"=",
"self",
".",
"get_account",
"(",
"username",
")",
"return",
"account",
"and",
"account",
".",
"get_perms",
"(",
")"
] | return user permissions | [
"return",
"user",
"permissions"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/authorizers.py#L91-L95 | train | 31,741 |
tokibito/django-ftpserver | django_ftpserver/authorizers.py | FTPAccountAuthorizer.impersonate_user | def impersonate_user(self, username, password):
"""delegate to personate_user method
"""
if self.personate_user:
self.personate_user.impersonate_user(username, password) | python | def impersonate_user(self, username, password):
"""delegate to personate_user method
"""
if self.personate_user:
self.personate_user.impersonate_user(username, password) | [
"def",
"impersonate_user",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"if",
"self",
".",
"personate_user",
":",
"self",
".",
"personate_user",
".",
"impersonate_user",
"(",
"username",
",",
"password",
")"
] | delegate to personate_user method | [
"delegate",
"to",
"personate_user",
"method"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/authorizers.py#L97-L101 | train | 31,742 |
benknight/hue-python-rgb-converter | rgbxy/__init__.py | ColorHelper.hex_to_rgb | def hex_to_rgb(self, h):
"""Converts a valid hex color string to an RGB array."""
rgb = (self.hex_to_red(h), self.hex_to_green(h), self.hex_to_blue(h))
return rgb | python | def hex_to_rgb(self, h):
"""Converts a valid hex color string to an RGB array."""
rgb = (self.hex_to_red(h), self.hex_to_green(h), self.hex_to_blue(h))
return rgb | [
"def",
"hex_to_rgb",
"(",
"self",
",",
"h",
")",
":",
"rgb",
"=",
"(",
"self",
".",
"hex_to_red",
"(",
"h",
")",
",",
"self",
".",
"hex_to_green",
"(",
"h",
")",
",",
"self",
".",
"hex_to_blue",
"(",
"h",
")",
")",
"return",
"rgb"
] | Converts a valid hex color string to an RGB array. | [
"Converts",
"a",
"valid",
"hex",
"color",
"string",
"to",
"an",
"RGB",
"array",
"."
] | 76dd70eac7a56a1260fd94a52cca3991cd57dff0 | https://github.com/benknight/hue-python-rgb-converter/blob/76dd70eac7a56a1260fd94a52cca3991cd57dff0/rgbxy/__init__.py#L73-L76 | train | 31,743 |
benknight/hue-python-rgb-converter | rgbxy/__init__.py | ColorHelper.cross_product | def cross_product(self, p1, p2):
"""Returns the cross product of two XYPoints."""
return (p1.x * p2.y - p1.y * p2.x) | python | def cross_product(self, p1, p2):
"""Returns the cross product of two XYPoints."""
return (p1.x * p2.y - p1.y * p2.x) | [
"def",
"cross_product",
"(",
"self",
",",
"p1",
",",
"p2",
")",
":",
"return",
"(",
"p1",
".",
"x",
"*",
"p2",
".",
"y",
"-",
"p1",
".",
"y",
"*",
"p2",
".",
"x",
")"
] | Returns the cross product of two XYPoints. | [
"Returns",
"the",
"cross",
"product",
"of",
"two",
"XYPoints",
"."
] | 76dd70eac7a56a1260fd94a52cca3991cd57dff0 | https://github.com/benknight/hue-python-rgb-converter/blob/76dd70eac7a56a1260fd94a52cca3991cd57dff0/rgbxy/__init__.py#L86-L88 | train | 31,744 |
benknight/hue-python-rgb-converter | rgbxy/__init__.py | ColorHelper.get_distance_between_two_points | def get_distance_between_two_points(self, one, two):
"""Returns the distance between two XYPoints."""
dx = one.x - two.x
dy = one.y - two.y
return math.sqrt(dx * dx + dy * dy) | python | def get_distance_between_two_points(self, one, two):
"""Returns the distance between two XYPoints."""
dx = one.x - two.x
dy = one.y - two.y
return math.sqrt(dx * dx + dy * dy) | [
"def",
"get_distance_between_two_points",
"(",
"self",
",",
"one",
",",
"two",
")",
":",
"dx",
"=",
"one",
".",
"x",
"-",
"two",
".",
"x",
"dy",
"=",
"one",
".",
"y",
"-",
"two",
".",
"y",
"return",
"math",
".",
"sqrt",
"(",
"dx",
"*",
"dx",
"+... | Returns the distance between two XYPoints. | [
"Returns",
"the",
"distance",
"between",
"two",
"XYPoints",
"."
] | 76dd70eac7a56a1260fd94a52cca3991cd57dff0 | https://github.com/benknight/hue-python-rgb-converter/blob/76dd70eac7a56a1260fd94a52cca3991cd57dff0/rgbxy/__init__.py#L144-L148 | train | 31,745 |
benknight/hue-python-rgb-converter | rgbxy/__init__.py | ColorHelper.get_xy_point_from_rgb | def get_xy_point_from_rgb(self, red_i, green_i, blue_i):
"""Returns an XYPoint object containing the closest available CIE 1931 x, y coordinates
based on the RGB input values."""
red = red_i / 255.0
green = green_i / 255.0
blue = blue_i / 255.0
r = ((red + 0.055) / (1.0 + 0.055))**2.4 if (red > 0.04045) else (red / 12.92)
g = ((green + 0.055) / (1.0 + 0.055))**2.4 if (green > 0.04045) else (green / 12.92)
b = ((blue + 0.055) / (1.0 + 0.055))**2.4 if (blue > 0.04045) else (blue / 12.92)
X = r * 0.664511 + g * 0.154324 + b * 0.162028
Y = r * 0.283881 + g * 0.668433 + b * 0.047685
Z = r * 0.000088 + g * 0.072310 + b * 0.986039
cx = X / (X + Y + Z)
cy = Y / (X + Y + Z)
# Check if the given XY value is within the colourreach of our lamps.
xy_point = XYPoint(cx, cy)
in_reach = self.check_point_in_lamps_reach(xy_point)
if not in_reach:
xy_point = self.get_closest_point_to_point(xy_point)
return xy_point | python | def get_xy_point_from_rgb(self, red_i, green_i, blue_i):
"""Returns an XYPoint object containing the closest available CIE 1931 x, y coordinates
based on the RGB input values."""
red = red_i / 255.0
green = green_i / 255.0
blue = blue_i / 255.0
r = ((red + 0.055) / (1.0 + 0.055))**2.4 if (red > 0.04045) else (red / 12.92)
g = ((green + 0.055) / (1.0 + 0.055))**2.4 if (green > 0.04045) else (green / 12.92)
b = ((blue + 0.055) / (1.0 + 0.055))**2.4 if (blue > 0.04045) else (blue / 12.92)
X = r * 0.664511 + g * 0.154324 + b * 0.162028
Y = r * 0.283881 + g * 0.668433 + b * 0.047685
Z = r * 0.000088 + g * 0.072310 + b * 0.986039
cx = X / (X + Y + Z)
cy = Y / (X + Y + Z)
# Check if the given XY value is within the colourreach of our lamps.
xy_point = XYPoint(cx, cy)
in_reach = self.check_point_in_lamps_reach(xy_point)
if not in_reach:
xy_point = self.get_closest_point_to_point(xy_point)
return xy_point | [
"def",
"get_xy_point_from_rgb",
"(",
"self",
",",
"red_i",
",",
"green_i",
",",
"blue_i",
")",
":",
"red",
"=",
"red_i",
"/",
"255.0",
"green",
"=",
"green_i",
"/",
"255.0",
"blue",
"=",
"blue_i",
"/",
"255.0",
"r",
"=",
"(",
"(",
"red",
"+",
"0.055"... | Returns an XYPoint object containing the closest available CIE 1931 x, y coordinates
based on the RGB input values. | [
"Returns",
"an",
"XYPoint",
"object",
"containing",
"the",
"closest",
"available",
"CIE",
"1931",
"x",
"y",
"coordinates",
"based",
"on",
"the",
"RGB",
"input",
"values",
"."
] | 76dd70eac7a56a1260fd94a52cca3991cd57dff0 | https://github.com/benknight/hue-python-rgb-converter/blob/76dd70eac7a56a1260fd94a52cca3991cd57dff0/rgbxy/__init__.py#L150-L176 | train | 31,746 |
benknight/hue-python-rgb-converter | rgbxy/__init__.py | Converter.hex_to_xy | def hex_to_xy(self, h):
"""Converts hexadecimal colors represented as a String to approximate CIE
1931 x and y coordinates.
"""
rgb = self.color.hex_to_rgb(h)
return self.rgb_to_xy(rgb[0], rgb[1], rgb[2]) | python | def hex_to_xy(self, h):
"""Converts hexadecimal colors represented as a String to approximate CIE
1931 x and y coordinates.
"""
rgb = self.color.hex_to_rgb(h)
return self.rgb_to_xy(rgb[0], rgb[1], rgb[2]) | [
"def",
"hex_to_xy",
"(",
"self",
",",
"h",
")",
":",
"rgb",
"=",
"self",
".",
"color",
".",
"hex_to_rgb",
"(",
"h",
")",
"return",
"self",
".",
"rgb_to_xy",
"(",
"rgb",
"[",
"0",
"]",
",",
"rgb",
"[",
"1",
"]",
",",
"rgb",
"[",
"2",
"]",
")"
... | Converts hexadecimal colors represented as a String to approximate CIE
1931 x and y coordinates. | [
"Converts",
"hexadecimal",
"colors",
"represented",
"as",
"a",
"String",
"to",
"approximate",
"CIE",
"1931",
"x",
"and",
"y",
"coordinates",
"."
] | 76dd70eac7a56a1260fd94a52cca3991cd57dff0 | https://github.com/benknight/hue-python-rgb-converter/blob/76dd70eac7a56a1260fd94a52cca3991cd57dff0/rgbxy/__init__.py#L228-L233 | train | 31,747 |
benknight/hue-python-rgb-converter | rgbxy/__init__.py | Converter.rgb_to_xy | def rgb_to_xy(self, red, green, blue):
"""Converts red, green and blue integer values to approximate CIE 1931
x and y coordinates.
"""
point = self.color.get_xy_point_from_rgb(red, green, blue)
return (point.x, point.y) | python | def rgb_to_xy(self, red, green, blue):
"""Converts red, green and blue integer values to approximate CIE 1931
x and y coordinates.
"""
point = self.color.get_xy_point_from_rgb(red, green, blue)
return (point.x, point.y) | [
"def",
"rgb_to_xy",
"(",
"self",
",",
"red",
",",
"green",
",",
"blue",
")",
":",
"point",
"=",
"self",
".",
"color",
".",
"get_xy_point_from_rgb",
"(",
"red",
",",
"green",
",",
"blue",
")",
"return",
"(",
"point",
".",
"x",
",",
"point",
".",
"y"... | Converts red, green and blue integer values to approximate CIE 1931
x and y coordinates. | [
"Converts",
"red",
"green",
"and",
"blue",
"integer",
"values",
"to",
"approximate",
"CIE",
"1931",
"x",
"and",
"y",
"coordinates",
"."
] | 76dd70eac7a56a1260fd94a52cca3991cd57dff0 | https://github.com/benknight/hue-python-rgb-converter/blob/76dd70eac7a56a1260fd94a52cca3991cd57dff0/rgbxy/__init__.py#L235-L240 | train | 31,748 |
benknight/hue-python-rgb-converter | rgbxy/__init__.py | Converter.get_random_xy_color | def get_random_xy_color(self):
"""Returns the approximate CIE 1931 x,y coordinates represented by the
supplied hexColor parameter, or of a random color if the parameter
is not passed."""
r = self.color.random_rgb_value()
g = self.color.random_rgb_value()
b = self.color.random_rgb_value()
return self.rgb_to_xy(r, g, b) | python | def get_random_xy_color(self):
"""Returns the approximate CIE 1931 x,y coordinates represented by the
supplied hexColor parameter, or of a random color if the parameter
is not passed."""
r = self.color.random_rgb_value()
g = self.color.random_rgb_value()
b = self.color.random_rgb_value()
return self.rgb_to_xy(r, g, b) | [
"def",
"get_random_xy_color",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"color",
".",
"random_rgb_value",
"(",
")",
"g",
"=",
"self",
".",
"color",
".",
"random_rgb_value",
"(",
")",
"b",
"=",
"self",
".",
"color",
".",
"random_rgb_value",
"(",
")"... | Returns the approximate CIE 1931 x,y coordinates represented by the
supplied hexColor parameter, or of a random color if the parameter
is not passed. | [
"Returns",
"the",
"approximate",
"CIE",
"1931",
"x",
"y",
"coordinates",
"represented",
"by",
"the",
"supplied",
"hexColor",
"parameter",
"or",
"of",
"a",
"random",
"color",
"if",
"the",
"parameter",
"is",
"not",
"passed",
"."
] | 76dd70eac7a56a1260fd94a52cca3991cd57dff0 | https://github.com/benknight/hue-python-rgb-converter/blob/76dd70eac7a56a1260fd94a52cca3991cd57dff0/rgbxy/__init__.py#L254-L261 | train | 31,749 |
tokibito/django-ftpserver | django_ftpserver/compat.py | become_daemon | def become_daemon(*args, **kwargs):
"""become_daemon function wrapper
In Django 1.9, 'become_daemon' is removed.
It means compatibility.
"""
if django.VERSION >= (1, 9):
from .daemonize import become_daemon
else:
from django.utils.daemonize import become_daemon
return become_daemon(*args, **kwargs) | python | def become_daemon(*args, **kwargs):
"""become_daemon function wrapper
In Django 1.9, 'become_daemon' is removed.
It means compatibility.
"""
if django.VERSION >= (1, 9):
from .daemonize import become_daemon
else:
from django.utils.daemonize import become_daemon
return become_daemon(*args, **kwargs) | [
"def",
"become_daemon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"django",
".",
"VERSION",
">=",
"(",
"1",
",",
"9",
")",
":",
"from",
".",
"daemonize",
"import",
"become_daemon",
"else",
":",
"from",
"django",
".",
"utils",
".",
... | become_daemon function wrapper
In Django 1.9, 'become_daemon' is removed.
It means compatibility. | [
"become_daemon",
"function",
"wrapper"
] | 18cf9f6645df9c2d9c5188bf21e74c188d55de47 | https://github.com/tokibito/django-ftpserver/blob/18cf9f6645df9c2d9c5188bf21e74c188d55de47/django_ftpserver/compat.py#L15-L25 | train | 31,750 |
spacetelescope/pysynphot | commissioning/convert/conv_base.py | SpecCase.setUpClass | def setUpClass(cls):
"""Always overridden by the child cases, but let's put some
real values in here to test with"""
self.obsmode=None
self.spectrum=None
self.bp=None
self.sp=None
self.obs=None
self.setup2() | python | def setUpClass(cls):
"""Always overridden by the child cases, but let's put some
real values in here to test with"""
self.obsmode=None
self.spectrum=None
self.bp=None
self.sp=None
self.obs=None
self.setup2() | [
"def",
"setUpClass",
"(",
"cls",
")",
":",
"self",
".",
"obsmode",
"=",
"None",
"self",
".",
"spectrum",
"=",
"None",
"self",
".",
"bp",
"=",
"None",
"self",
".",
"sp",
"=",
"None",
"self",
".",
"obs",
"=",
"None",
"self",
".",
"setup2",
"(",
")"... | Always overridden by the child cases, but let's put some
real values in here to test with | [
"Always",
"overridden",
"by",
"the",
"child",
"cases",
"but",
"let",
"s",
"put",
"some",
"real",
"values",
"in",
"here",
"to",
"test",
"with"
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/convert/conv_base.py#L22-L30 | train | 31,751 |
spacetelescope/pysynphot | pysynphot/graphtab.py | GraphTable.validate | def validate(self):
""" Simulataneously checks for loops and unreachable nodes
"""
msg = list()
previously_seen = set()
currently_seen = set([1])
problemset = set()
while currently_seen:
node = currently_seen.pop()
if node in previously_seen:
problemset.add(node)
else:
previously_seen.add(node)
self.add_descendants(node, currently_seen)
unreachable = self.all_nodes - previously_seen
if unreachable:
msg.append("%d unreachable nodes: "%len(unreachable))
for node in unreachable:
msg.append(str(node))
if problemset:
msg.append("Loop involving %d nodes"%len(problemset))
for node in problemset:
msg.append(str(node))
if msg:
return msg
else:
return True | python | def validate(self):
""" Simulataneously checks for loops and unreachable nodes
"""
msg = list()
previously_seen = set()
currently_seen = set([1])
problemset = set()
while currently_seen:
node = currently_seen.pop()
if node in previously_seen:
problemset.add(node)
else:
previously_seen.add(node)
self.add_descendants(node, currently_seen)
unreachable = self.all_nodes - previously_seen
if unreachable:
msg.append("%d unreachable nodes: "%len(unreachable))
for node in unreachable:
msg.append(str(node))
if problemset:
msg.append("Loop involving %d nodes"%len(problemset))
for node in problemset:
msg.append(str(node))
if msg:
return msg
else:
return True | [
"def",
"validate",
"(",
"self",
")",
":",
"msg",
"=",
"list",
"(",
")",
"previously_seen",
"=",
"set",
"(",
")",
"currently_seen",
"=",
"set",
"(",
"[",
"1",
"]",
")",
"problemset",
"=",
"set",
"(",
")",
"while",
"currently_seen",
":",
"node",
"=",
... | Simulataneously checks for loops and unreachable nodes | [
"Simulataneously",
"checks",
"for",
"loops",
"and",
"unreachable",
"nodes"
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/graphtab.py#L242-L271 | train | 31,752 |
spacetelescope/pysynphot | pysynphot/refs.py | set_default_waveset | def set_default_waveset(minwave=500, maxwave=26000, num=10000,
delta=None, log=True):
"""Set the default wavelength set, ``pysynphot.refs._default_waveset``.
Parameters
----------
minwave, maxwave : float, optional
The start (inclusive) and end (exclusive) points of the wavelength set.
Values should be given in linear space regardless of ``log``.
num : int, optional
The number of elements in the wavelength set.
Only used if ``delta=None``.
delta : float, optional
Delta between values in the wavelength set.
If ``log=True``, this defines wavelegth spacing in log space.
log : bool, optional
Determines whether the wavelength set is evenly spaced in log or linear
space.
"""
global _default_waveset
global _default_waveset_str
# Must be int for numpy>=1.12
num = int(num)
s = 'Min: %s, Max: %s, Num: %s, Delta: %s, Log: %s'
if log and not delta:
s = s % tuple([str(x) for x in (minwave, maxwave, num, None, log)])
logmin = np.log10(minwave)
logmax = np.log10(maxwave)
_default_waveset = np.logspace(logmin, logmax, num, endpoint=False)
elif log and delta:
s = s % tuple([str(x) for x in (minwave, maxwave, None, delta, log)])
logmin = np.log10(minwave)
logmax = np.log10(maxwave)
_default_waveset = 10 ** np.arange(logmin, logmax, delta)
elif not log and not delta:
s = s % tuple([str(x) for x in (minwave, maxwave, num, None, log)])
_default_waveset = np.linspace(minwave, maxwave, num, endpoint=False)
elif not log and delta:
s = s % tuple([str(x) for x in (minwave, maxwave, None, delta, log)])
_default_waveset = np.arange(minwave, maxwave, delta)
_default_waveset_str = s | python | def set_default_waveset(minwave=500, maxwave=26000, num=10000,
delta=None, log=True):
"""Set the default wavelength set, ``pysynphot.refs._default_waveset``.
Parameters
----------
minwave, maxwave : float, optional
The start (inclusive) and end (exclusive) points of the wavelength set.
Values should be given in linear space regardless of ``log``.
num : int, optional
The number of elements in the wavelength set.
Only used if ``delta=None``.
delta : float, optional
Delta between values in the wavelength set.
If ``log=True``, this defines wavelegth spacing in log space.
log : bool, optional
Determines whether the wavelength set is evenly spaced in log or linear
space.
"""
global _default_waveset
global _default_waveset_str
# Must be int for numpy>=1.12
num = int(num)
s = 'Min: %s, Max: %s, Num: %s, Delta: %s, Log: %s'
if log and not delta:
s = s % tuple([str(x) for x in (minwave, maxwave, num, None, log)])
logmin = np.log10(minwave)
logmax = np.log10(maxwave)
_default_waveset = np.logspace(logmin, logmax, num, endpoint=False)
elif log and delta:
s = s % tuple([str(x) for x in (minwave, maxwave, None, delta, log)])
logmin = np.log10(minwave)
logmax = np.log10(maxwave)
_default_waveset = 10 ** np.arange(logmin, logmax, delta)
elif not log and not delta:
s = s % tuple([str(x) for x in (minwave, maxwave, num, None, log)])
_default_waveset = np.linspace(minwave, maxwave, num, endpoint=False)
elif not log and delta:
s = s % tuple([str(x) for x in (minwave, maxwave, None, delta, log)])
_default_waveset = np.arange(minwave, maxwave, delta)
_default_waveset_str = s | [
"def",
"set_default_waveset",
"(",
"minwave",
"=",
"500",
",",
"maxwave",
"=",
"26000",
",",
"num",
"=",
"10000",
",",
"delta",
"=",
"None",
",",
"log",
"=",
"True",
")",
":",
"global",
"_default_waveset",
"global",
"_default_waveset_str",
"# Must be int for n... | Set the default wavelength set, ``pysynphot.refs._default_waveset``.
Parameters
----------
minwave, maxwave : float, optional
The start (inclusive) and end (exclusive) points of the wavelength set.
Values should be given in linear space regardless of ``log``.
num : int, optional
The number of elements in the wavelength set.
Only used if ``delta=None``.
delta : float, optional
Delta between values in the wavelength set.
If ``log=True``, this defines wavelegth spacing in log space.
log : bool, optional
Determines whether the wavelength set is evenly spaced in log or linear
space. | [
"Set",
"the",
"default",
"wavelength",
"set",
"pysynphot",
".",
"refs",
".",
"_default_waveset",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/refs.py#L46-L103 | train | 31,753 |
spacetelescope/pysynphot | pysynphot/refs.py | _set_default_refdata | def _set_default_refdata():
"""Default refdata set on import."""
global GRAPHTABLE, COMPTABLE, THERMTABLE, PRIMARY_AREA
# Component tables are defined here.
try:
GRAPHTABLE = _refTable(os.path.join('mtab','*_tmg.fits'))
COMPTABLE = _refTable(os.path.join('mtab','*_tmc.fits'))
except IOError as e:
GRAPHTABLE = None
COMPTABLE = None
warnings.warn('No graph or component tables found; '
'functionality will be SEVERELY crippled. ' + str(e))
try:
THERMTABLE = _refTable(os.path.join('mtab','*_tmt.fits'))
except IOError as e:
THERMTABLE = None
warnings.warn('No thermal tables found, '
'no thermal calculations can be performed. ' + str(e))
PRIMARY_AREA = 45238.93416 # cm^2 - default to HST mirror
set_default_waveset() | python | def _set_default_refdata():
"""Default refdata set on import."""
global GRAPHTABLE, COMPTABLE, THERMTABLE, PRIMARY_AREA
# Component tables are defined here.
try:
GRAPHTABLE = _refTable(os.path.join('mtab','*_tmg.fits'))
COMPTABLE = _refTable(os.path.join('mtab','*_tmc.fits'))
except IOError as e:
GRAPHTABLE = None
COMPTABLE = None
warnings.warn('No graph or component tables found; '
'functionality will be SEVERELY crippled. ' + str(e))
try:
THERMTABLE = _refTable(os.path.join('mtab','*_tmt.fits'))
except IOError as e:
THERMTABLE = None
warnings.warn('No thermal tables found, '
'no thermal calculations can be performed. ' + str(e))
PRIMARY_AREA = 45238.93416 # cm^2 - default to HST mirror
set_default_waveset() | [
"def",
"_set_default_refdata",
"(",
")",
":",
"global",
"GRAPHTABLE",
",",
"COMPTABLE",
",",
"THERMTABLE",
",",
"PRIMARY_AREA",
"# Component tables are defined here.",
"try",
":",
"GRAPHTABLE",
"=",
"_refTable",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'mtab'",
... | Default refdata set on import. | [
"Default",
"refdata",
"set",
"on",
"import",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/refs.py#L106-L129 | train | 31,754 |
spacetelescope/pysynphot | pysynphot/refs.py | setref | def setref(graphtable=None, comptable=None, thermtable=None,
area=None, waveset=None):
"""Set default graph and component tables, primary area, and
wavelength set.
This is similar to setting ``refdata`` in IRAF STSDAS SYNPHOT.
If all parameters set to `None`, they are reverted to software default.
If any of the parameters are not `None`, they are set to desired
values while the rest (if any) remain at current setting.
Parameters
----------
graphtable, comptable, thermtable : str or `None`
Graph, component, and thermal table names, respectively,
for `~pysynphot.observationmode` throughput look-up.
Do not use "*" wildcard.
area : float or `None`
Telescope collecting area, i.e., the primary
mirror, in :math:`\\textnormal{cm}^{2}`.
waveset : tuple or `None`
Parameters for :func:`set_default_waveset` as follow:
* ``(minwave, maxwave, num)`` - This assumes log scale.
* ``(minwave, maxwave, num, 'log')``
* ``(minwave, maxwave, num, 'linear')``
Raises
------
ValueError
Invalid ``waveset`` parameters.
"""
global GRAPHTABLE, COMPTABLE, THERMTABLE, PRIMARY_AREA, GRAPHDICT, COMPDICT, THERMDICT
GRAPHDICT = {}
COMPDICT = {}
THERMDICT = {}
#Check for all None, which means reset
kwds=set([graphtable,comptable,thermtable,area,waveset])
if kwds == set([None]):
#then we should reset everything.
_set_default_refdata()
return
#Otherwise, check them all separately
if graphtable is not None:
GRAPHTABLE = irafconvert(graphtable)
if comptable is not None:
COMPTABLE = irafconvert(comptable)
if thermtable is not None:
THERMTABLE = irafconvert(thermtable)
#Area is a bit different:
if area is not None:
PRIMARY_AREA = area
if waveset is not None:
if len(waveset) not in (3, 4):
raise ValueError('waveset tuple must contain 3 or 4 values')
minwave = waveset[0]
maxwave = waveset[1]
num = waveset[2]
if len(waveset) == 3:
log = True
elif len(waveset) == 4:
if waveset[3].lower() == 'log':
log = True
elif waveset[3].lower() == 'linear':
log = False
else:
raise ValueError('fourth waveset option must be "log" or "linear"')
set_default_waveset(minwave,maxwave,num,log=log)
#That's it.
return | python | def setref(graphtable=None, comptable=None, thermtable=None,
area=None, waveset=None):
"""Set default graph and component tables, primary area, and
wavelength set.
This is similar to setting ``refdata`` in IRAF STSDAS SYNPHOT.
If all parameters set to `None`, they are reverted to software default.
If any of the parameters are not `None`, they are set to desired
values while the rest (if any) remain at current setting.
Parameters
----------
graphtable, comptable, thermtable : str or `None`
Graph, component, and thermal table names, respectively,
for `~pysynphot.observationmode` throughput look-up.
Do not use "*" wildcard.
area : float or `None`
Telescope collecting area, i.e., the primary
mirror, in :math:`\\textnormal{cm}^{2}`.
waveset : tuple or `None`
Parameters for :func:`set_default_waveset` as follow:
* ``(minwave, maxwave, num)`` - This assumes log scale.
* ``(minwave, maxwave, num, 'log')``
* ``(minwave, maxwave, num, 'linear')``
Raises
------
ValueError
Invalid ``waveset`` parameters.
"""
global GRAPHTABLE, COMPTABLE, THERMTABLE, PRIMARY_AREA, GRAPHDICT, COMPDICT, THERMDICT
GRAPHDICT = {}
COMPDICT = {}
THERMDICT = {}
#Check for all None, which means reset
kwds=set([graphtable,comptable,thermtable,area,waveset])
if kwds == set([None]):
#then we should reset everything.
_set_default_refdata()
return
#Otherwise, check them all separately
if graphtable is not None:
GRAPHTABLE = irafconvert(graphtable)
if comptable is not None:
COMPTABLE = irafconvert(comptable)
if thermtable is not None:
THERMTABLE = irafconvert(thermtable)
#Area is a bit different:
if area is not None:
PRIMARY_AREA = area
if waveset is not None:
if len(waveset) not in (3, 4):
raise ValueError('waveset tuple must contain 3 or 4 values')
minwave = waveset[0]
maxwave = waveset[1]
num = waveset[2]
if len(waveset) == 3:
log = True
elif len(waveset) == 4:
if waveset[3].lower() == 'log':
log = True
elif waveset[3].lower() == 'linear':
log = False
else:
raise ValueError('fourth waveset option must be "log" or "linear"')
set_default_waveset(minwave,maxwave,num,log=log)
#That's it.
return | [
"def",
"setref",
"(",
"graphtable",
"=",
"None",
",",
"comptable",
"=",
"None",
",",
"thermtable",
"=",
"None",
",",
"area",
"=",
"None",
",",
"waveset",
"=",
"None",
")",
":",
"global",
"GRAPHTABLE",
",",
"COMPTABLE",
",",
"THERMTABLE",
",",
"PRIMARY_AR... | Set default graph and component tables, primary area, and
wavelength set.
This is similar to setting ``refdata`` in IRAF STSDAS SYNPHOT.
If all parameters set to `None`, they are reverted to software default.
If any of the parameters are not `None`, they are set to desired
values while the rest (if any) remain at current setting.
Parameters
----------
graphtable, comptable, thermtable : str or `None`
Graph, component, and thermal table names, respectively,
for `~pysynphot.observationmode` throughput look-up.
Do not use "*" wildcard.
area : float or `None`
Telescope collecting area, i.e., the primary
mirror, in :math:`\\textnormal{cm}^{2}`.
waveset : tuple or `None`
Parameters for :func:`set_default_waveset` as follow:
* ``(minwave, maxwave, num)`` - This assumes log scale.
* ``(minwave, maxwave, num, 'log')``
* ``(minwave, maxwave, num, 'linear')``
Raises
------
ValueError
Invalid ``waveset`` parameters. | [
"Set",
"default",
"graph",
"and",
"component",
"tables",
"primary",
"area",
"and",
"wavelength",
"set",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/refs.py#L135-L216 | train | 31,755 |
spacetelescope/pysynphot | pysynphot/refs.py | getref | def getref():
"""Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values.
"""
ans=dict(graphtable=GRAPHTABLE,
comptable=COMPTABLE,
thermtable=THERMTABLE,
area=PRIMARY_AREA,
waveset=_default_waveset_str)
return ans | python | def getref():
"""Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values.
"""
ans=dict(graphtable=GRAPHTABLE,
comptable=COMPTABLE,
thermtable=THERMTABLE,
area=PRIMARY_AREA,
waveset=_default_waveset_str)
return ans | [
"def",
"getref",
"(",
")",
":",
"ans",
"=",
"dict",
"(",
"graphtable",
"=",
"GRAPHTABLE",
",",
"comptable",
"=",
"COMPTABLE",
",",
"thermtable",
"=",
"THERMTABLE",
",",
"area",
"=",
"PRIMARY_AREA",
",",
"waveset",
"=",
"_default_waveset_str",
")",
"return",
... | Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values. | [
"Current",
"default",
"values",
"for",
"graph",
"and",
"component",
"tables",
"primary",
"area",
"and",
"wavelength",
"set",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/refs.py#L219-L238 | train | 31,756 |
spacetelescope/pysynphot | commissioning/kwfile_dict.py | read_kwfile | def read_kwfile(fname):
"""Syntax used as of r452 in commissioning tests"""
d={}
f=open(fname)
for line in f:
try:
kvpair=re.findall("(.*):: (.*)=(.*)$",line)[0]
d['name']=os.path.basename(kvpair[0])
key,val=kvpair[1:]
d[key.lower()]=val
except (ValueError,IndexError):
break
f.close()
return d | python | def read_kwfile(fname):
"""Syntax used as of r452 in commissioning tests"""
d={}
f=open(fname)
for line in f:
try:
kvpair=re.findall("(.*):: (.*)=(.*)$",line)[0]
d['name']=os.path.basename(kvpair[0])
key,val=kvpair[1:]
d[key.lower()]=val
except (ValueError,IndexError):
break
f.close()
return d | [
"def",
"read_kwfile",
"(",
"fname",
")",
":",
"d",
"=",
"{",
"}",
"f",
"=",
"open",
"(",
"fname",
")",
"for",
"line",
"in",
"f",
":",
"try",
":",
"kvpair",
"=",
"re",
".",
"findall",
"(",
"\"(.*):: (.*)=(.*)$\"",
",",
"line",
")",
"[",
"0",
"]",
... | Syntax used as of r452 in commissioning tests | [
"Syntax",
"used",
"as",
"of",
"r452",
"in",
"commissioning",
"tests"
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/kwfile_dict.py#L5-L19 | train | 31,757 |
spacetelescope/pysynphot | pysynphot/obsbandpass.py | ObsBandpass | def ObsBandpass(obstring, graphtable=None, comptable=None, component_dict={}):
"""Generate a bandpass object from observation mode.
If the bandpass consists of multiple throughput files
(e.g., "acs,hrc,f555w"), then `ObsModeBandpass` is returned.
Otherwise, if it consists of a single throughput file
(e.g., "johnson,v"), then `~pysynphot.spectrum.TabularSpectralElement`
is returned.
See :ref:`pysynphot-obsmode-bandpass` and :ref:`pysynphot-appendixb`
for more details.
Parameters
----------
obstring : str
Observation mode.
graphtable, comptable, component_dict
See `~pysynphot.observationmode.ObservationMode`.
Returns
-------
bp : `~pysynphot.spectrum.TabularSpectralElement` or `ObsModeBandpass`
Examples
--------
>>> bp1 = S.ObsBandpass('acs,hrc,f555w')
>>> bp2 = S.ObsBandpass('johnson,v')
"""
##Temporarily create an Obsmode to determine whether an
##ObsModeBandpass or a TabularSpectralElement will be returned.
ob=ObservationMode(obstring,graphtable=graphtable,
comptable=comptable,component_dict=component_dict)
if len(ob) > 1:
return ObsModeBandpass(ob)
else:
return TabularSpectralElement(ob.components[0].throughput_name) | python | def ObsBandpass(obstring, graphtable=None, comptable=None, component_dict={}):
"""Generate a bandpass object from observation mode.
If the bandpass consists of multiple throughput files
(e.g., "acs,hrc,f555w"), then `ObsModeBandpass` is returned.
Otherwise, if it consists of a single throughput file
(e.g., "johnson,v"), then `~pysynphot.spectrum.TabularSpectralElement`
is returned.
See :ref:`pysynphot-obsmode-bandpass` and :ref:`pysynphot-appendixb`
for more details.
Parameters
----------
obstring : str
Observation mode.
graphtable, comptable, component_dict
See `~pysynphot.observationmode.ObservationMode`.
Returns
-------
bp : `~pysynphot.spectrum.TabularSpectralElement` or `ObsModeBandpass`
Examples
--------
>>> bp1 = S.ObsBandpass('acs,hrc,f555w')
>>> bp2 = S.ObsBandpass('johnson,v')
"""
##Temporarily create an Obsmode to determine whether an
##ObsModeBandpass or a TabularSpectralElement will be returned.
ob=ObservationMode(obstring,graphtable=graphtable,
comptable=comptable,component_dict=component_dict)
if len(ob) > 1:
return ObsModeBandpass(ob)
else:
return TabularSpectralElement(ob.components[0].throughput_name) | [
"def",
"ObsBandpass",
"(",
"obstring",
",",
"graphtable",
"=",
"None",
",",
"comptable",
"=",
"None",
",",
"component_dict",
"=",
"{",
"}",
")",
":",
"##Temporarily create an Obsmode to determine whether an",
"##ObsModeBandpass or a TabularSpectralElement will be returned.",
... | Generate a bandpass object from observation mode.
If the bandpass consists of multiple throughput files
(e.g., "acs,hrc,f555w"), then `ObsModeBandpass` is returned.
Otherwise, if it consists of a single throughput file
(e.g., "johnson,v"), then `~pysynphot.spectrum.TabularSpectralElement`
is returned.
See :ref:`pysynphot-obsmode-bandpass` and :ref:`pysynphot-appendixb`
for more details.
Parameters
----------
obstring : str
Observation mode.
graphtable, comptable, component_dict
See `~pysynphot.observationmode.ObservationMode`.
Returns
-------
bp : `~pysynphot.spectrum.TabularSpectralElement` or `ObsModeBandpass`
Examples
--------
>>> bp1 = S.ObsBandpass('acs,hrc,f555w')
>>> bp2 = S.ObsBandpass('johnson,v') | [
"Generate",
"a",
"bandpass",
"object",
"from",
"observation",
"mode",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/obsbandpass.py#L11-L48 | train | 31,758 |
spacetelescope/pysynphot | pysynphot/obsbandpass.py | ObsModeBandpass.thermback | def thermback(self):
"""Calculate thermal background count rate for ``self.obsmode``.
Calculation uses
:func:`~pysynphot.observationmode.ObservationMode.ThermalSpectrum`
to extract thermal component source spectrum in
``photlam`` per square arcsec. Then this spectrum is
integrated and multiplied by detector pixel scale
and telescope collecting area to produce a count rate
in count/s/pix. This unit is non-standard but used widely
by STScI Exposure Time Calculator.
.. note::
Similar to IRAF STSDAS SYNPHOT ``thermback`` task.
Returns
-------
ans : float
Thermal background count rate.
Raises
------
NotImplementedError
Bandpass has no thermal information in graph table.
"""
#The obsmode.ThermalSpectrum method will raise an exception if there is
#no thermal information, and that will just propagate up.
sp=self.obsmode.ThermalSpectrum()
#Thermback is always provided in this non-standard set of units.
#This code was copied from etc.py.
ans = sp.integrate() * (self.obsmode.pixscale**2 *
self.obsmode.primary_area)
return ans | python | def thermback(self):
"""Calculate thermal background count rate for ``self.obsmode``.
Calculation uses
:func:`~pysynphot.observationmode.ObservationMode.ThermalSpectrum`
to extract thermal component source spectrum in
``photlam`` per square arcsec. Then this spectrum is
integrated and multiplied by detector pixel scale
and telescope collecting area to produce a count rate
in count/s/pix. This unit is non-standard but used widely
by STScI Exposure Time Calculator.
.. note::
Similar to IRAF STSDAS SYNPHOT ``thermback`` task.
Returns
-------
ans : float
Thermal background count rate.
Raises
------
NotImplementedError
Bandpass has no thermal information in graph table.
"""
#The obsmode.ThermalSpectrum method will raise an exception if there is
#no thermal information, and that will just propagate up.
sp=self.obsmode.ThermalSpectrum()
#Thermback is always provided in this non-standard set of units.
#This code was copied from etc.py.
ans = sp.integrate() * (self.obsmode.pixscale**2 *
self.obsmode.primary_area)
return ans | [
"def",
"thermback",
"(",
"self",
")",
":",
"#The obsmode.ThermalSpectrum method will raise an exception if there is",
"#no thermal information, and that will just propagate up.",
"sp",
"=",
"self",
".",
"obsmode",
".",
"ThermalSpectrum",
"(",
")",
"#Thermback is always provided in ... | Calculate thermal background count rate for ``self.obsmode``.
Calculation uses
:func:`~pysynphot.observationmode.ObservationMode.ThermalSpectrum`
to extract thermal component source spectrum in
``photlam`` per square arcsec. Then this spectrum is
integrated and multiplied by detector pixel scale
and telescope collecting area to produce a count rate
in count/s/pix. This unit is non-standard but used widely
by STScI Exposure Time Calculator.
.. note::
Similar to IRAF STSDAS SYNPHOT ``thermback`` task.
Returns
-------
ans : float
Thermal background count rate.
Raises
------
NotImplementedError
Bandpass has no thermal information in graph table. | [
"Calculate",
"thermal",
"background",
"count",
"rate",
"for",
"self",
".",
"obsmode",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/obsbandpass.py#L151-L186 | train | 31,759 |
spacetelescope/pysynphot | pysynphot/spectrum.py | MergeWaveSets | def MergeWaveSets(waveset1, waveset2):
"""Return the union of the two wavelength sets.
The union is computed using `numpy.union1d`, unless one or
both of them is `None`.
The merged result may sometimes contain numbers which are nearly
equal but differ at levels as small as 1E-14. Having values this
close together can cause problems due to effectively duplicate
wavelength values. Therefore, wavelength values having differences
smaller than or equal to ``pysynphot.spectrum.MERGETHRESH``
(defaults to 1E-12) are considered as the same.
Parameters
----------
waveset1, waveset2 : array_like or `None`
Wavelength sets to combine.
Returns
-------
MergedWaveSet : array_like or `None`
Merged wavelength set. It is `None` if both inputs are such.
"""
if waveset1 is None and waveset2 is not None:
MergedWaveSet = waveset2
elif waveset2 is None and waveset1 is not None:
MergedWaveSet = waveset1
elif waveset1 is None and waveset2 is None:
MergedWaveSet = None
else:
MergedWaveSet = N.union1d(waveset1, waveset2)
# The merged wave sets may sometimes contain numbers which are nearly
# equal but differ at levels as small as 1e-14. Having values this
# close together can cause problems down the line so here we test
# whether any such small differences are present, with a small
# difference defined as less than MERGETHRESH.
#
# If small differences are present we make a copy of the union'ed array
# with the lower of the close together pairs removed.
delta = MergedWaveSet[1:] - MergedWaveSet[:-1]
if not (delta > MERGETHRESH).all():
newlen = len(delta[delta > MERGETHRESH]) + 1
newmerged = N.zeros(newlen, dtype=MergedWaveSet.dtype)
newmerged[:-1] = MergedWaveSet[:-1][delta > MERGETHRESH]
newmerged[-1] = MergedWaveSet[-1]
MergedWaveSet = newmerged
return MergedWaveSet | python | def MergeWaveSets(waveset1, waveset2):
"""Return the union of the two wavelength sets.
The union is computed using `numpy.union1d`, unless one or
both of them is `None`.
The merged result may sometimes contain numbers which are nearly
equal but differ at levels as small as 1E-14. Having values this
close together can cause problems due to effectively duplicate
wavelength values. Therefore, wavelength values having differences
smaller than or equal to ``pysynphot.spectrum.MERGETHRESH``
(defaults to 1E-12) are considered as the same.
Parameters
----------
waveset1, waveset2 : array_like or `None`
Wavelength sets to combine.
Returns
-------
MergedWaveSet : array_like or `None`
Merged wavelength set. It is `None` if both inputs are such.
"""
if waveset1 is None and waveset2 is not None:
MergedWaveSet = waveset2
elif waveset2 is None and waveset1 is not None:
MergedWaveSet = waveset1
elif waveset1 is None and waveset2 is None:
MergedWaveSet = None
else:
MergedWaveSet = N.union1d(waveset1, waveset2)
# The merged wave sets may sometimes contain numbers which are nearly
# equal but differ at levels as small as 1e-14. Having values this
# close together can cause problems down the line so here we test
# whether any such small differences are present, with a small
# difference defined as less than MERGETHRESH.
#
# If small differences are present we make a copy of the union'ed array
# with the lower of the close together pairs removed.
delta = MergedWaveSet[1:] - MergedWaveSet[:-1]
if not (delta > MERGETHRESH).all():
newlen = len(delta[delta > MERGETHRESH]) + 1
newmerged = N.zeros(newlen, dtype=MergedWaveSet.dtype)
newmerged[:-1] = MergedWaveSet[:-1][delta > MERGETHRESH]
newmerged[-1] = MergedWaveSet[-1]
MergedWaveSet = newmerged
return MergedWaveSet | [
"def",
"MergeWaveSets",
"(",
"waveset1",
",",
"waveset2",
")",
":",
"if",
"waveset1",
"is",
"None",
"and",
"waveset2",
"is",
"not",
"None",
":",
"MergedWaveSet",
"=",
"waveset2",
"elif",
"waveset2",
"is",
"None",
"and",
"waveset1",
"is",
"not",
"None",
":"... | Return the union of the two wavelength sets.
The union is computed using `numpy.union1d`, unless one or
both of them is `None`.
The merged result may sometimes contain numbers which are nearly
equal but differ at levels as small as 1E-14. Having values this
close together can cause problems due to effectively duplicate
wavelength values. Therefore, wavelength values having differences
smaller than or equal to ``pysynphot.spectrum.MERGETHRESH``
(defaults to 1E-12) are considered as the same.
Parameters
----------
waveset1, waveset2 : array_like or `None`
Wavelength sets to combine.
Returns
-------
MergedWaveSet : array_like or `None`
Merged wavelength set. It is `None` if both inputs are such. | [
"Return",
"the",
"union",
"of",
"the",
"two",
"wavelength",
"sets",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L51-L102 | train | 31,760 |
spacetelescope/pysynphot | pysynphot/spectrum.py | trimSpectrum | def trimSpectrum(sp, minw, maxw):
"""Create a new spectrum with trimmed upper and lower ranges.
Parameters
----------
sp : `SourceSpectrum`
Spectrum to trim.
minw, maxw : number
Lower and upper limits (inclusive) for the wavelength set
in the trimmed spectrum.
Returns
-------
result : `TabularSourceSpectrum`
Trimmed spectrum.
"""
wave = sp.GetWaveSet()
flux = sp(wave)
new_wave = N.compress(wave >= minw, wave)
new_flux = N.compress(wave >= minw, flux)
new_wave = N.compress(new_wave <= maxw, new_wave)
new_flux = N.compress(new_wave <= maxw, new_flux)
result = TabularSourceSpectrum()
result._wavetable = new_wave
result._fluxtable = new_flux
result.waveunits = units.Units(sp.waveunits.name)
result.fluxunits = units.Units(sp.fluxunits.name)
return result | python | def trimSpectrum(sp, minw, maxw):
"""Create a new spectrum with trimmed upper and lower ranges.
Parameters
----------
sp : `SourceSpectrum`
Spectrum to trim.
minw, maxw : number
Lower and upper limits (inclusive) for the wavelength set
in the trimmed spectrum.
Returns
-------
result : `TabularSourceSpectrum`
Trimmed spectrum.
"""
wave = sp.GetWaveSet()
flux = sp(wave)
new_wave = N.compress(wave >= minw, wave)
new_flux = N.compress(wave >= minw, flux)
new_wave = N.compress(new_wave <= maxw, new_wave)
new_flux = N.compress(new_wave <= maxw, new_flux)
result = TabularSourceSpectrum()
result._wavetable = new_wave
result._fluxtable = new_flux
result.waveunits = units.Units(sp.waveunits.name)
result.fluxunits = units.Units(sp.fluxunits.name)
return result | [
"def",
"trimSpectrum",
"(",
"sp",
",",
"minw",
",",
"maxw",
")",
":",
"wave",
"=",
"sp",
".",
"GetWaveSet",
"(",
")",
"flux",
"=",
"sp",
"(",
"wave",
")",
"new_wave",
"=",
"N",
".",
"compress",
"(",
"wave",
">=",
"minw",
",",
"wave",
")",
"new_fl... | Create a new spectrum with trimmed upper and lower ranges.
Parameters
----------
sp : `SourceSpectrum`
Spectrum to trim.
minw, maxw : number
Lower and upper limits (inclusive) for the wavelength set
in the trimmed spectrum.
Returns
-------
result : `TabularSourceSpectrum`
Trimmed spectrum. | [
"Create",
"a",
"new",
"spectrum",
"with",
"trimmed",
"upper",
"and",
"lower",
"ranges",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L105-L140 | train | 31,761 |
spacetelescope/pysynphot | pysynphot/spectrum.py | Integrator.trapezoidIntegration | def trapezoidIntegration(self, x, y):
"""Perform trapezoid integration.
Parameters
----------
x : array_like
Wavelength set.
y : array_like
Integrand. For example, throughput or throughput
multiplied by wavelength.
Returns
-------
sum : float
Integrated sum.
"""
npoints = x.size
if npoints > 0:
indices = N.arange(npoints)[:-1]
deltas = x[indices+1] - x[indices]
integrand = 0.5*(y[indices+1] + y[indices])*deltas
sum = integrand.sum()
if x[-1] < x[0]:
sum *= -1.0
return sum
else:
return 0.0 | python | def trapezoidIntegration(self, x, y):
"""Perform trapezoid integration.
Parameters
----------
x : array_like
Wavelength set.
y : array_like
Integrand. For example, throughput or throughput
multiplied by wavelength.
Returns
-------
sum : float
Integrated sum.
"""
npoints = x.size
if npoints > 0:
indices = N.arange(npoints)[:-1]
deltas = x[indices+1] - x[indices]
integrand = 0.5*(y[indices+1] + y[indices])*deltas
sum = integrand.sum()
if x[-1] < x[0]:
sum *= -1.0
return sum
else:
return 0.0 | [
"def",
"trapezoidIntegration",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"npoints",
"=",
"x",
".",
"size",
"if",
"npoints",
">",
"0",
":",
"indices",
"=",
"N",
".",
"arange",
"(",
"npoints",
")",
"[",
":",
"-",
"1",
"]",
"deltas",
"=",
"x",
"[... | Perform trapezoid integration.
Parameters
----------
x : array_like
Wavelength set.
y : array_like
Integrand. For example, throughput or throughput
multiplied by wavelength.
Returns
-------
sum : float
Integrated sum. | [
"Perform",
"trapezoid",
"integration",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L148-L176 | train | 31,762 |
spacetelescope/pysynphot | pysynphot/spectrum.py | Integrator.validate_wavetable | def validate_wavetable(self):
"""Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptions.UnsortedWavelength
Wavelength array is not monotonic ascending or descending.
pysynphot.exceptions.ZeroWavelength
Wavelength array has zero or negative value(s).
"""
# First check for invalid values
wave = self._wavetable
if N.any(wave <= 0):
wrong = N.where(wave <= 0)[0]
raise exceptions.ZeroWavelength(
'Negative or Zero wavelength occurs in wavelength array',
rows=wrong)
# Now check for monotonicity & enforce ascending
sorted = N.sort(wave)
if not N.alltrue(sorted == wave):
if N.alltrue(sorted[::-1] == wave):
# monotonic descending is allowed
pass
else:
wrong = N.where(sorted != wave)[0]
raise exceptions.UnsortedWavelength(
'Wavelength array is not monotonic', rows=wrong)
# Check for duplicate values
dw = sorted[1:] - sorted[:-1]
if N.any(dw == 0):
wrong = N.where(dw == 0)[0]
raise exceptions.DuplicateWavelength(
"Wavelength array contains duplicate entries", rows=wrong) | python | def validate_wavetable(self):
"""Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptions.UnsortedWavelength
Wavelength array is not monotonic ascending or descending.
pysynphot.exceptions.ZeroWavelength
Wavelength array has zero or negative value(s).
"""
# First check for invalid values
wave = self._wavetable
if N.any(wave <= 0):
wrong = N.where(wave <= 0)[0]
raise exceptions.ZeroWavelength(
'Negative or Zero wavelength occurs in wavelength array',
rows=wrong)
# Now check for monotonicity & enforce ascending
sorted = N.sort(wave)
if not N.alltrue(sorted == wave):
if N.alltrue(sorted[::-1] == wave):
# monotonic descending is allowed
pass
else:
wrong = N.where(sorted != wave)[0]
raise exceptions.UnsortedWavelength(
'Wavelength array is not monotonic', rows=wrong)
# Check for duplicate values
dw = sorted[1:] - sorted[:-1]
if N.any(dw == 0):
wrong = N.where(dw == 0)[0]
raise exceptions.DuplicateWavelength(
"Wavelength array contains duplicate entries", rows=wrong) | [
"def",
"validate_wavetable",
"(",
"self",
")",
":",
"# First check for invalid values",
"wave",
"=",
"self",
".",
"_wavetable",
"if",
"N",
".",
"any",
"(",
"wave",
"<=",
"0",
")",
":",
"wrong",
"=",
"N",
".",
"where",
"(",
"wave",
"<=",
"0",
")",
"[",
... | Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptions.UnsortedWavelength
Wavelength array is not monotonic ascending or descending.
pysynphot.exceptions.ZeroWavelength
Wavelength array has zero or negative value(s). | [
"Enforce",
"monotonic",
"ascending",
"wavelength",
"array",
"with",
"no",
"zero",
"or",
"negative",
"values",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L207-L247 | train | 31,763 |
spacetelescope/pysynphot | pysynphot/spectrum.py | Integrator.validate_fluxtable | def validate_fluxtable(self):
"""Check for non-negative fluxes.
If found, the negative flux values are set to zero, and
a warning is printed to screen. This check is not done
if flux unit is a magnitude because negative magnitude
values are legal.
"""
# neg. magnitudes are legal
if ((not self.fluxunits.isMag) and (self._fluxtable.min() < 0)):
idx = N.where(self._fluxtable < 0)
self._fluxtable[idx] = 0.0
print("Warning, %d of %d bins contained negative fluxes; they "
"have been set to zero." % (
len(idx[0]), len(self._fluxtable))) | python | def validate_fluxtable(self):
"""Check for non-negative fluxes.
If found, the negative flux values are set to zero, and
a warning is printed to screen. This check is not done
if flux unit is a magnitude because negative magnitude
values are legal.
"""
# neg. magnitudes are legal
if ((not self.fluxunits.isMag) and (self._fluxtable.min() < 0)):
idx = N.where(self._fluxtable < 0)
self._fluxtable[idx] = 0.0
print("Warning, %d of %d bins contained negative fluxes; they "
"have been set to zero." % (
len(idx[0]), len(self._fluxtable))) | [
"def",
"validate_fluxtable",
"(",
"self",
")",
":",
"# neg. magnitudes are legal",
"if",
"(",
"(",
"not",
"self",
".",
"fluxunits",
".",
"isMag",
")",
"and",
"(",
"self",
".",
"_fluxtable",
".",
"min",
"(",
")",
"<",
"0",
")",
")",
":",
"idx",
"=",
"... | Check for non-negative fluxes.
If found, the negative flux values are set to zero, and
a warning is printed to screen. This check is not done
if flux unit is a magnitude because negative magnitude
values are legal. | [
"Check",
"for",
"non",
"-",
"negative",
"fluxes",
".",
"If",
"found",
"the",
"negative",
"flux",
"values",
"are",
"set",
"to",
"zero",
"and",
"a",
"warning",
"is",
"printed",
"to",
"screen",
".",
"This",
"check",
"is",
"not",
"done",
"if",
"flux",
"uni... | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L249-L263 | train | 31,764 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SourceSpectrum.addmag | def addmag(self, magval):
"""Add a scalar magnitude to existing flux values.
.. math::
\\textnormal{flux}_{\\textnormal{new}} = 10^{-0.4 \\; \\textnormal{magval}} \\; \\textnormal{flux}
Parameters
----------
magval : number
Magnitude value.
Returns
-------
sp : `CompositeSourceSpectrum`
New source spectrum with adjusted flux values.
Raises
------
TypeError
Magnitude value is not a scalar number.
"""
if N.isscalar(magval):
factor = 10**(-0.4*magval)
return self*factor
else:
raise TypeError(".addmag() only takes a constant scalar argument") | python | def addmag(self, magval):
"""Add a scalar magnitude to existing flux values.
.. math::
\\textnormal{flux}_{\\textnormal{new}} = 10^{-0.4 \\; \\textnormal{magval}} \\; \\textnormal{flux}
Parameters
----------
magval : number
Magnitude value.
Returns
-------
sp : `CompositeSourceSpectrum`
New source spectrum with adjusted flux values.
Raises
------
TypeError
Magnitude value is not a scalar number.
"""
if N.isscalar(magval):
factor = 10**(-0.4*magval)
return self*factor
else:
raise TypeError(".addmag() only takes a constant scalar argument") | [
"def",
"addmag",
"(",
"self",
",",
"magval",
")",
":",
"if",
"N",
".",
"isscalar",
"(",
"magval",
")",
":",
"factor",
"=",
"10",
"**",
"(",
"-",
"0.4",
"*",
"magval",
")",
"return",
"self",
"*",
"factor",
"else",
":",
"raise",
"TypeError",
"(",
"... | Add a scalar magnitude to existing flux values.
.. math::
\\textnormal{flux}_{\\textnormal{new}} = 10^{-0.4 \\; \\textnormal{magval}} \\; \\textnormal{flux}
Parameters
----------
magval : number
Magnitude value.
Returns
-------
sp : `CompositeSourceSpectrum`
New source spectrum with adjusted flux values.
Raises
------
TypeError
Magnitude value is not a scalar number. | [
"Add",
"a",
"scalar",
"magnitude",
"to",
"existing",
"flux",
"values",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L305-L332 | train | 31,765 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SourceSpectrum.getArrays | def getArrays(self):
"""Return wavelength and flux arrays in user units.
Returns
-------
wave : array_like
Wavelength array in ``self.waveunits``.
flux : array_like
Flux array in ``self.fluxunits``.
When necessary, ``self.primary_area`` is used for unit conversion.
"""
if hasattr(self, 'primary_area'):
area = self.primary_area
else:
area = None
wave = self.GetWaveSet()
flux = self(wave)
flux = units.Photlam().Convert(
wave, flux, self.fluxunits.name, area=area)
wave = units.Angstrom().Convert(wave, self.waveunits.name)
return wave, flux | python | def getArrays(self):
"""Return wavelength and flux arrays in user units.
Returns
-------
wave : array_like
Wavelength array in ``self.waveunits``.
flux : array_like
Flux array in ``self.fluxunits``.
When necessary, ``self.primary_area`` is used for unit conversion.
"""
if hasattr(self, 'primary_area'):
area = self.primary_area
else:
area = None
wave = self.GetWaveSet()
flux = self(wave)
flux = units.Photlam().Convert(
wave, flux, self.fluxunits.name, area=area)
wave = units.Angstrom().Convert(wave, self.waveunits.name)
return wave, flux | [
"def",
"getArrays",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'primary_area'",
")",
":",
"area",
"=",
"self",
".",
"primary_area",
"else",
":",
"area",
"=",
"None",
"wave",
"=",
"self",
".",
"GetWaveSet",
"(",
")",
"flux",
"=",
"self... | Return wavelength and flux arrays in user units.
Returns
-------
wave : array_like
Wavelength array in ``self.waveunits``.
flux : array_like
Flux array in ``self.fluxunits``.
When necessary, ``self.primary_area`` is used for unit conversion. | [
"Return",
"wavelength",
"and",
"flux",
"arrays",
"in",
"user",
"units",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L334-L359 | train | 31,766 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SourceSpectrum.validate_units | def validate_units(self):
"""Ensure that wavelenth and flux units belong to the
correct classes.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits` or
flux unit is not `~pysynphot.units.FluxUnits`.
"""
if (not isinstance(self.waveunits, units.WaveUnits)):
raise TypeError("%s is not a valid WaveUnit" % self.waveunits)
if (not isinstance(self.fluxunits, units.FluxUnits)):
raise TypeError("%s is not a valid FluxUnit" % self.fluxunits) | python | def validate_units(self):
"""Ensure that wavelenth and flux units belong to the
correct classes.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits` or
flux unit is not `~pysynphot.units.FluxUnits`.
"""
if (not isinstance(self.waveunits, units.WaveUnits)):
raise TypeError("%s is not a valid WaveUnit" % self.waveunits)
if (not isinstance(self.fluxunits, units.FluxUnits)):
raise TypeError("%s is not a valid FluxUnit" % self.fluxunits) | [
"def",
"validate_units",
"(",
"self",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"self",
".",
"waveunits",
",",
"units",
".",
"WaveUnits",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is not a valid WaveUnit\"",
"%",
"self",
".",
"waveunits",
")",
"... | Ensure that wavelenth and flux units belong to the
correct classes.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits` or
flux unit is not `~pysynphot.units.FluxUnits`. | [
"Ensure",
"that",
"wavelenth",
"and",
"flux",
"units",
"belong",
"to",
"the",
"correct",
"classes",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L373-L387 | train | 31,767 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SourceSpectrum.writefits | def writefits(self, filename, clobber=True, trimzero=True,
binned=False, precision=None, hkeys=None):
"""Write the spectrum to a FITS table.
Primary header in EXT 0. ``FILENAME``, ``ORIGIN``, and any
extra keyword(s) from ``hkeys`` will also be added.
Table header and data are in EXT 1. The table has 2 columns,
i.e., ``WAVELENGTH`` and ``FLUX``. Data are stored in user units.
Its header also will have these additional keywords:
* ``EXPR`` - Description of the spectrum.
* ``TDISP1`` and ``TDISP2`` - Columns display format,
always "G15.7".
* ``GRFTABLE`` and ``CMPTABLE`` - Graph and component
table names to use with associated observation mode.
These are only added if applicable.
If data is already double-precision but user explicitly
set output precision to single, ``pysynphot.spectrum.syn_epsilon``
defines the allowed minimum wavelength separation.
This limit (:math:`3.2 \\times 10^{-4}`) was taken from
IRAF STSDAS SYNPHOT FAQ.
Values equal or smaller than this limit are considered as the
same, and duplicates are ignored, resulting in data loss.
In the way that this comparison is coded, when such precision clash
happens, even when no duplicates are detected, the last row is
always omitted (also data loss). Therefore, it is *not* recommended
for user to force single-precision when the data is in
double-precision.
Parameters
----------
filename : str
Output filename.
clobber : bool
Overwrite existing file. Default is `True`.
trimzero : bool
Trim off duplicate rows with flux values of zero from both ends
of the spectrum. This keeps one row of zero-flux at each end,
if it exists; However, it does not add a zero-flux row if it
does not. Default is `True`.
binned : bool
Write ``self.binwave`` and ``self.binflux`` (binned) dataset,
instead of ``self.wave`` and ``self.flux`` (native). Using
this option when object does not have binned data will cause
an exception to be raised. Default is `False`.
precision : {'s', 'd', `None`}
Write data out in single (``'s'``) or double (``'d'``)
precision. Default is `None`, which will enforce native
precision from ``self.flux``.
hkeys : dict
Additional keyword(s) to be added to primary FITS header,
in the format of ``{keyword:(value,comment)}``.
"""
pcodes={'d':'D', 's':'E'}
if precision is None:
precision = self.flux.dtype.char
_precision = precision.lower()[0]
pcodes = {'d':'D','s':'E','f':'E'}
if clobber:
try:
os.remove(filename)
except OSError:
pass
if binned:
wave = self.binwave
flux = self.binflux
else:
wave = self.wave
flux = self.flux
# Add a check for single/double precision clash, so
# that if written out in single precision, the wavelength table
# will still be sorted with no duplicates
# The value of epsilon is taken from the Synphot FAQ.
if wave.dtype == N.float64 and _precision == 's':
idx = N.where(abs(wave[1:]-wave[:-1]) > syn_epsilon)
else:
idx = N.where(wave) #=> idx=[:]
wave = wave[idx]
flux = flux[idx]
first, last = 0, len(flux)
if trimzero:
# Keep one zero at each end
nz = flux.nonzero()[0]
try:
first = max(nz[0] - 1, first)
last = min(nz[-1] + 2, last)
except IndexError:
pass
# Construct the columns and HDUlist
cw = pyfits.Column(name='WAVELENGTH',
array=wave[first:last],
unit=self.waveunits.name,
format=pcodes[_precision])
cf = pyfits.Column(name='FLUX',
array=flux[first:last],
unit=self.fluxunits.name,
format=pcodes[_precision])
# Make the primary header
hdu = pyfits.PrimaryHDU()
hdulist = pyfits.HDUList([hdu])
# User-provided keys are written to the primary header
# so are filename and origin
bkeys = dict(filename=(os.path.basename(filename), 'name of file'),
origin=('pysynphot', 'Version (%s, %s)' %
(__version__, __svn_revision__)))
# User-values if present may override default values
if hkeys is not None:
bkeys.update(hkeys)
# Now update the primary header
for key, val in bkeys.items():
hdu.header[key] = val
# Make the extension HDU
cols = pyfits.ColDefs([cw, cf])
hdu = pyfits.BinTableHDU.from_columns(cols)
# There are some standard keywords that should be added
# to the extension header.
bkeys = dict(expr=(str(self), 'pysyn expression'),
tdisp1=('G15.7',),
tdisp2=('G15.7',))
try:
bkeys['grftable'] = (self.bandpass.obsmode.gtname,)
bkeys['cmptable'] = (self.bandpass.obsmode.ctname,)
except AttributeError:
pass # Not all spectra have these
for key, val in bkeys.items():
hdu.header[key] = val
# Add the header to the list, and write the file
hdulist.append(hdu)
hdulist.writeto(filename) | python | def writefits(self, filename, clobber=True, trimzero=True,
binned=False, precision=None, hkeys=None):
"""Write the spectrum to a FITS table.
Primary header in EXT 0. ``FILENAME``, ``ORIGIN``, and any
extra keyword(s) from ``hkeys`` will also be added.
Table header and data are in EXT 1. The table has 2 columns,
i.e., ``WAVELENGTH`` and ``FLUX``. Data are stored in user units.
Its header also will have these additional keywords:
* ``EXPR`` - Description of the spectrum.
* ``TDISP1`` and ``TDISP2`` - Columns display format,
always "G15.7".
* ``GRFTABLE`` and ``CMPTABLE`` - Graph and component
table names to use with associated observation mode.
These are only added if applicable.
If data is already double-precision but user explicitly
set output precision to single, ``pysynphot.spectrum.syn_epsilon``
defines the allowed minimum wavelength separation.
This limit (:math:`3.2 \\times 10^{-4}`) was taken from
IRAF STSDAS SYNPHOT FAQ.
Values equal or smaller than this limit are considered as the
same, and duplicates are ignored, resulting in data loss.
In the way that this comparison is coded, when such precision clash
happens, even when no duplicates are detected, the last row is
always omitted (also data loss). Therefore, it is *not* recommended
for user to force single-precision when the data is in
double-precision.
Parameters
----------
filename : str
Output filename.
clobber : bool
Overwrite existing file. Default is `True`.
trimzero : bool
Trim off duplicate rows with flux values of zero from both ends
of the spectrum. This keeps one row of zero-flux at each end,
if it exists; However, it does not add a zero-flux row if it
does not. Default is `True`.
binned : bool
Write ``self.binwave`` and ``self.binflux`` (binned) dataset,
instead of ``self.wave`` and ``self.flux`` (native). Using
this option when object does not have binned data will cause
an exception to be raised. Default is `False`.
precision : {'s', 'd', `None`}
Write data out in single (``'s'``) or double (``'d'``)
precision. Default is `None`, which will enforce native
precision from ``self.flux``.
hkeys : dict
Additional keyword(s) to be added to primary FITS header,
in the format of ``{keyword:(value,comment)}``.
"""
pcodes={'d':'D', 's':'E'}
if precision is None:
precision = self.flux.dtype.char
_precision = precision.lower()[0]
pcodes = {'d':'D','s':'E','f':'E'}
if clobber:
try:
os.remove(filename)
except OSError:
pass
if binned:
wave = self.binwave
flux = self.binflux
else:
wave = self.wave
flux = self.flux
# Add a check for single/double precision clash, so
# that if written out in single precision, the wavelength table
# will still be sorted with no duplicates
# The value of epsilon is taken from the Synphot FAQ.
if wave.dtype == N.float64 and _precision == 's':
idx = N.where(abs(wave[1:]-wave[:-1]) > syn_epsilon)
else:
idx = N.where(wave) #=> idx=[:]
wave = wave[idx]
flux = flux[idx]
first, last = 0, len(flux)
if trimzero:
# Keep one zero at each end
nz = flux.nonzero()[0]
try:
first = max(nz[0] - 1, first)
last = min(nz[-1] + 2, last)
except IndexError:
pass
# Construct the columns and HDUlist
cw = pyfits.Column(name='WAVELENGTH',
array=wave[first:last],
unit=self.waveunits.name,
format=pcodes[_precision])
cf = pyfits.Column(name='FLUX',
array=flux[first:last],
unit=self.fluxunits.name,
format=pcodes[_precision])
# Make the primary header
hdu = pyfits.PrimaryHDU()
hdulist = pyfits.HDUList([hdu])
# User-provided keys are written to the primary header
# so are filename and origin
bkeys = dict(filename=(os.path.basename(filename), 'name of file'),
origin=('pysynphot', 'Version (%s, %s)' %
(__version__, __svn_revision__)))
# User-values if present may override default values
if hkeys is not None:
bkeys.update(hkeys)
# Now update the primary header
for key, val in bkeys.items():
hdu.header[key] = val
# Make the extension HDU
cols = pyfits.ColDefs([cw, cf])
hdu = pyfits.BinTableHDU.from_columns(cols)
# There are some standard keywords that should be added
# to the extension header.
bkeys = dict(expr=(str(self), 'pysyn expression'),
tdisp1=('G15.7',),
tdisp2=('G15.7',))
try:
bkeys['grftable'] = (self.bandpass.obsmode.gtname,)
bkeys['cmptable'] = (self.bandpass.obsmode.ctname,)
except AttributeError:
pass # Not all spectra have these
for key, val in bkeys.items():
hdu.header[key] = val
# Add the header to the list, and write the file
hdulist.append(hdu)
hdulist.writeto(filename) | [
"def",
"writefits",
"(",
"self",
",",
"filename",
",",
"clobber",
"=",
"True",
",",
"trimzero",
"=",
"True",
",",
"binned",
"=",
"False",
",",
"precision",
"=",
"None",
",",
"hkeys",
"=",
"None",
")",
":",
"pcodes",
"=",
"{",
"'d'",
":",
"'D'",
","... | Write the spectrum to a FITS table.
Primary header in EXT 0. ``FILENAME``, ``ORIGIN``, and any
extra keyword(s) from ``hkeys`` will also be added.
Table header and data are in EXT 1. The table has 2 columns,
i.e., ``WAVELENGTH`` and ``FLUX``. Data are stored in user units.
Its header also will have these additional keywords:
* ``EXPR`` - Description of the spectrum.
* ``TDISP1`` and ``TDISP2`` - Columns display format,
always "G15.7".
* ``GRFTABLE`` and ``CMPTABLE`` - Graph and component
table names to use with associated observation mode.
These are only added if applicable.
If data is already double-precision but user explicitly
set output precision to single, ``pysynphot.spectrum.syn_epsilon``
defines the allowed minimum wavelength separation.
This limit (:math:`3.2 \\times 10^{-4}`) was taken from
IRAF STSDAS SYNPHOT FAQ.
Values equal or smaller than this limit are considered as the
same, and duplicates are ignored, resulting in data loss.
In the way that this comparison is coded, when such precision clash
happens, even when no duplicates are detected, the last row is
always omitted (also data loss). Therefore, it is *not* recommended
for user to force single-precision when the data is in
double-precision.
Parameters
----------
filename : str
Output filename.
clobber : bool
Overwrite existing file. Default is `True`.
trimzero : bool
Trim off duplicate rows with flux values of zero from both ends
of the spectrum. This keeps one row of zero-flux at each end,
if it exists; However, it does not add a zero-flux row if it
does not. Default is `True`.
binned : bool
Write ``self.binwave`` and ``self.binflux`` (binned) dataset,
instead of ``self.wave`` and ``self.flux`` (native). Using
this option when object does not have binned data will cause
an exception to be raised. Default is `False`.
precision : {'s', 'd', `None`}
Write data out in single (``'s'``) or double (``'d'``)
precision. Default is `None`, which will enforce native
precision from ``self.flux``.
hkeys : dict
Additional keyword(s) to be added to primary FITS header,
in the format of ``{keyword:(value,comment)}``. | [
"Write",
"the",
"spectrum",
"to",
"a",
"FITS",
"table",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L389-L541 | train | 31,768 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SourceSpectrum.integrate | def integrate(self, fluxunits='photlam'):
"""Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int F_{\\lambda} d\\lambda
Parameters
----------
fluxunits : str
Flux unit to integrate in.
Returns
-------
result : float
Integrated sum. Its unit should take account of the
integration over wavelength. For example, if
``fluxunits='photlam'`` is given, then its unit
is ``photon/s/cm^2``.
"""
# Extract the flux in the desired units
u = self.fluxunits
self.convert(fluxunits)
wave, flux = self.getArrays()
self.convert(u)
# then do the integration
return self.trapezoidIntegration(wave, flux) | python | def integrate(self, fluxunits='photlam'):
"""Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int F_{\\lambda} d\\lambda
Parameters
----------
fluxunits : str
Flux unit to integrate in.
Returns
-------
result : float
Integrated sum. Its unit should take account of the
integration over wavelength. For example, if
``fluxunits='photlam'`` is given, then its unit
is ``photon/s/cm^2``.
"""
# Extract the flux in the desired units
u = self.fluxunits
self.convert(fluxunits)
wave, flux = self.getArrays()
self.convert(u)
# then do the integration
return self.trapezoidIntegration(wave, flux) | [
"def",
"integrate",
"(",
"self",
",",
"fluxunits",
"=",
"'photlam'",
")",
":",
"# Extract the flux in the desired units",
"u",
"=",
"self",
".",
"fluxunits",
"self",
".",
"convert",
"(",
"fluxunits",
")",
"wave",
",",
"flux",
"=",
"self",
".",
"getArrays",
"... | Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int F_{\\lambda} d\\lambda
Parameters
----------
fluxunits : str
Flux unit to integrate in.
Returns
-------
result : float
Integrated sum. Its unit should take account of the
integration over wavelength. For example, if
``fluxunits='photlam'`` is given, then its unit
is ``photon/s/cm^2``. | [
"Integrate",
"the",
"flux",
"in",
"given",
"unit",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L543-L574 | train | 31,769 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SourceSpectrum.convert | def convert(self, targetunits):
"""Set new user unit, for either wavelength or flux.
This effectively converts the spectrum wavelength or flux
to given unit. Note that actual data are always kept in
internal units (Angstrom and ``photlam``), and only converted
to user units by :meth:`getArrays` during actual computation.
User units are stored in ``self.waveunits`` and ``self.fluxunits``.
Parameters
----------
targetunits : str
New unit name, as accepted by `~pysynphot.units.Units`.
"""
nunits = units.Units(targetunits)
if nunits.isFlux:
self.fluxunits = nunits
else:
self.waveunits = nunits | python | def convert(self, targetunits):
"""Set new user unit, for either wavelength or flux.
This effectively converts the spectrum wavelength or flux
to given unit. Note that actual data are always kept in
internal units (Angstrom and ``photlam``), and only converted
to user units by :meth:`getArrays` during actual computation.
User units are stored in ``self.waveunits`` and ``self.fluxunits``.
Parameters
----------
targetunits : str
New unit name, as accepted by `~pysynphot.units.Units`.
"""
nunits = units.Units(targetunits)
if nunits.isFlux:
self.fluxunits = nunits
else:
self.waveunits = nunits | [
"def",
"convert",
"(",
"self",
",",
"targetunits",
")",
":",
"nunits",
"=",
"units",
".",
"Units",
"(",
"targetunits",
")",
"if",
"nunits",
".",
"isFlux",
":",
"self",
".",
"fluxunits",
"=",
"nunits",
"else",
":",
"self",
".",
"waveunits",
"=",
"nunits... | Set new user unit, for either wavelength or flux.
This effectively converts the spectrum wavelength or flux
to given unit. Note that actual data are always kept in
internal units (Angstrom and ``photlam``), and only converted
to user units by :meth:`getArrays` during actual computation.
User units are stored in ``self.waveunits`` and ``self.fluxunits``.
Parameters
----------
targetunits : str
New unit name, as accepted by `~pysynphot.units.Units`. | [
"Set",
"new",
"user",
"unit",
"for",
"either",
"wavelength",
"or",
"flux",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L642-L662 | train | 31,770 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SourceSpectrum.setMagnitude | def setMagnitude(self, band, value):
"""Makes the magnitude of the source in the band equal to value.
band is a SpectralElement.
This method is marked for deletion once the .renorm method is
well tested.
Object returned is a CompositeSourceSpectrum.
.. warning:: DO NOT USED
"""
objectFlux = band.calcTotalFlux(self)
vegaFlux = band.calcVegaFlux()
magDiff = -2.5*math.log10(objectFlux/vegaFlux)
factor = 10**(-0.4*(value - magDiff))
return self * factor | python | def setMagnitude(self, band, value):
"""Makes the magnitude of the source in the band equal to value.
band is a SpectralElement.
This method is marked for deletion once the .renorm method is
well tested.
Object returned is a CompositeSourceSpectrum.
.. warning:: DO NOT USED
"""
objectFlux = band.calcTotalFlux(self)
vegaFlux = band.calcVegaFlux()
magDiff = -2.5*math.log10(objectFlux/vegaFlux)
factor = 10**(-0.4*(value - magDiff))
return self * factor | [
"def",
"setMagnitude",
"(",
"self",
",",
"band",
",",
"value",
")",
":",
"objectFlux",
"=",
"band",
".",
"calcTotalFlux",
"(",
"self",
")",
"vegaFlux",
"=",
"band",
".",
"calcVegaFlux",
"(",
")",
"magDiff",
"=",
"-",
"2.5",
"*",
"math",
".",
"log10",
... | Makes the magnitude of the source in the band equal to value.
band is a SpectralElement.
This method is marked for deletion once the .renorm method is
well tested.
Object returned is a CompositeSourceSpectrum.
.. warning:: DO NOT USED | [
"Makes",
"the",
"magnitude",
"of",
"the",
"source",
"in",
"the",
"band",
"equal",
"to",
"value",
".",
"band",
"is",
"a",
"SpectralElement",
".",
"This",
"method",
"is",
"marked",
"for",
"deletion",
"once",
"the",
".",
"renorm",
"method",
"is",
"well",
"t... | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L699-L714 | train | 31,771 |
spacetelescope/pysynphot | pysynphot/spectrum.py | CompositeSourceSpectrum.tabulate | def tabulate(self):
"""Return a simplified version of the spectrum.
Composite spectrum can be overly complicated when it
has too many components and sub-components. This method
copies the following into a simple (tabulated) source spectrum:
* Name
* Wavelength array and unit
* Flux array and unit
Returns
-------
sp : `ArraySourceSpectrum`
Tabulated source spectrum.
"""
sp = ArraySourceSpectrum(wave=self.wave,
flux=self.flux,
waveunits=self.waveunits,
fluxunits=self.fluxunits,
name='%s (tabulated)' % self.name)
return sp | python | def tabulate(self):
"""Return a simplified version of the spectrum.
Composite spectrum can be overly complicated when it
has too many components and sub-components. This method
copies the following into a simple (tabulated) source spectrum:
* Name
* Wavelength array and unit
* Flux array and unit
Returns
-------
sp : `ArraySourceSpectrum`
Tabulated source spectrum.
"""
sp = ArraySourceSpectrum(wave=self.wave,
flux=self.flux,
waveunits=self.waveunits,
fluxunits=self.fluxunits,
name='%s (tabulated)' % self.name)
return sp | [
"def",
"tabulate",
"(",
"self",
")",
":",
"sp",
"=",
"ArraySourceSpectrum",
"(",
"wave",
"=",
"self",
".",
"wave",
",",
"flux",
"=",
"self",
".",
"flux",
",",
"waveunits",
"=",
"self",
".",
"waveunits",
",",
"fluxunits",
"=",
"self",
".",
"fluxunits",
... | Return a simplified version of the spectrum.
Composite spectrum can be overly complicated when it
has too many components and sub-components. This method
copies the following into a simple (tabulated) source spectrum:
* Name
* Wavelength array and unit
* Flux array and unit
Returns
-------
sp : `ArraySourceSpectrum`
Tabulated source spectrum. | [
"Return",
"a",
"simplified",
"version",
"of",
"the",
"spectrum",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L921-L943 | train | 31,772 |
spacetelescope/pysynphot | pysynphot/spectrum.py | TabularSourceSpectrum._readASCII | def _readASCII(self, filename):
"""ASCII files have no headers. Following synphot, this
routine will assume the first column is wavelength in Angstroms,
and the second column is flux in Flam.
"""
self.waveunits = units.Units('angstrom')
self.fluxunits = units.Units('flam')
wlist, flist = self._columnsFromASCII(filename)
self._wavetable = N.array(wlist, dtype=N.float64)
self._fluxtable = N.array(flist, dtype=N.float64) | python | def _readASCII(self, filename):
"""ASCII files have no headers. Following synphot, this
routine will assume the first column is wavelength in Angstroms,
and the second column is flux in Flam.
"""
self.waveunits = units.Units('angstrom')
self.fluxunits = units.Units('flam')
wlist, flist = self._columnsFromASCII(filename)
self._wavetable = N.array(wlist, dtype=N.float64)
self._fluxtable = N.array(flist, dtype=N.float64) | [
"def",
"_readASCII",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"waveunits",
"=",
"units",
".",
"Units",
"(",
"'angstrom'",
")",
"self",
".",
"fluxunits",
"=",
"units",
".",
"Units",
"(",
"'flam'",
")",
"wlist",
",",
"flist",
"=",
"self",
"... | ASCII files have no headers. Following synphot, this
routine will assume the first column is wavelength in Angstroms,
and the second column is flux in Flam. | [
"ASCII",
"files",
"have",
"no",
"headers",
".",
"Following",
"synphot",
"this",
"routine",
"will",
"assume",
"the",
"first",
"column",
"is",
"wavelength",
"in",
"Angstroms",
"and",
"the",
"second",
"column",
"is",
"flux",
"in",
"Flam",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L1029-L1039 | train | 31,773 |
spacetelescope/pysynphot | pysynphot/spectrum.py | FlatSpectrum.redshift | def redshift(self, z):
"""Apply redshift to the flat spectrum.
Unlike :meth:`SourceSpectrum.redshift`, the redshifted spectrum
remains an analytic flat source.
Parameters
----------
z : number
Redshift value.
Returns
-------
ans : `FlatSpectrum`
"""
tmp = SourceSpectrum.redshift(self, z)
ans = FlatSpectrum(tmp.flux.max(), fluxunits=tmp.fluxunits)
return ans | python | def redshift(self, z):
"""Apply redshift to the flat spectrum.
Unlike :meth:`SourceSpectrum.redshift`, the redshifted spectrum
remains an analytic flat source.
Parameters
----------
z : number
Redshift value.
Returns
-------
ans : `FlatSpectrum`
"""
tmp = SourceSpectrum.redshift(self, z)
ans = FlatSpectrum(tmp.flux.max(), fluxunits=tmp.fluxunits)
return ans | [
"def",
"redshift",
"(",
"self",
",",
"z",
")",
":",
"tmp",
"=",
"SourceSpectrum",
".",
"redshift",
"(",
"self",
",",
"z",
")",
"ans",
"=",
"FlatSpectrum",
"(",
"tmp",
".",
"flux",
".",
"max",
"(",
")",
",",
"fluxunits",
"=",
"tmp",
".",
"fluxunits"... | Apply redshift to the flat spectrum.
Unlike :meth:`SourceSpectrum.redshift`, the redshifted spectrum
remains an analytic flat source.
Parameters
----------
z : number
Redshift value.
Returns
-------
ans : `FlatSpectrum` | [
"Apply",
"redshift",
"to",
"the",
"flat",
"spectrum",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L1566-L1584 | train | 31,774 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SpectralElement.validate_units | def validate_units(self):
"""Ensure that wavelenth unit belongs to the correct class.
There is no check for throughput because it is unitless.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits`.
"""
if (not isinstance(self.waveunits, units.WaveUnits)):
raise TypeError("%s is not a valid WaveUnit" % self.waveunits) | python | def validate_units(self):
"""Ensure that wavelenth unit belongs to the correct class.
There is no check for throughput because it is unitless.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits`.
"""
if (not isinstance(self.waveunits, units.WaveUnits)):
raise TypeError("%s is not a valid WaveUnit" % self.waveunits) | [
"def",
"validate_units",
"(",
"self",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"self",
".",
"waveunits",
",",
"units",
".",
"WaveUnits",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is not a valid WaveUnit\"",
"%",
"self",
".",
"waveunits",
")"
] | Ensure that wavelenth unit belongs to the correct class.
There is no check for throughput because it is unitless.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits`. | [
"Ensure",
"that",
"wavelenth",
"unit",
"belongs",
"to",
"the",
"correct",
"class",
".",
"There",
"is",
"no",
"check",
"for",
"throughput",
"because",
"it",
"is",
"unitless",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L1726-L1737 | train | 31,775 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SpectralElement.integrate | def integrate(self, wave=None):
"""Integrate the throughput over the specified wavelength set.
If no wavelength set is specified, the built-in one is used.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=throughput``.
Also see :ref:`pysynphot-formula-equvw`.
Parameters
----------
wave : array_like or `None`
Wavelength set for integration.
Returns
-------
ans : float
Integrated sum.
"""
if wave is None:
wave = self.wave
ans = self.trapezoidIntegration(wave, self(wave))
return ans | python | def integrate(self, wave=None):
"""Integrate the throughput over the specified wavelength set.
If no wavelength set is specified, the built-in one is used.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=throughput``.
Also see :ref:`pysynphot-formula-equvw`.
Parameters
----------
wave : array_like or `None`
Wavelength set for integration.
Returns
-------
ans : float
Integrated sum.
"""
if wave is None:
wave = self.wave
ans = self.trapezoidIntegration(wave, self(wave))
return ans | [
"def",
"integrate",
"(",
"self",
",",
"wave",
"=",
"None",
")",
":",
"if",
"wave",
"is",
"None",
":",
"wave",
"=",
"self",
".",
"wave",
"ans",
"=",
"self",
".",
"trapezoidIntegration",
"(",
"wave",
",",
"self",
"(",
"wave",
")",
")",
"return",
"ans... | Integrate the throughput over the specified wavelength set.
If no wavelength set is specified, the built-in one is used.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=throughput``.
Also see :ref:`pysynphot-formula-equvw`.
Parameters
----------
wave : array_like or `None`
Wavelength set for integration.
Returns
-------
ans : float
Integrated sum. | [
"Integrate",
"the",
"throughput",
"over",
"the",
"specified",
"wavelength",
"set",
".",
"If",
"no",
"wavelength",
"set",
"is",
"specified",
"the",
"built",
"-",
"in",
"one",
"is",
"used",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L1763-L1786 | train | 31,776 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SpectralElement.convert | def convert(self, targetunits):
"""Set new user unit, for wavelength only.
This effectively converts the spectrum wavelength
to given unit. Note that actual data are always kept in
internal unit (Angstrom), and only converted
to user unit by :meth:`GetWaveSet` during actual computation.
User unit is stored in ``self.waveunits``.
Throughput is unitless and cannot be converted.
Parameters
----------
targetunits : str
New unit name, as accepted by `~pysynphot.units.Units`.
"""
nunits = units.Units(targetunits)
self.waveunits = nunits | python | def convert(self, targetunits):
"""Set new user unit, for wavelength only.
This effectively converts the spectrum wavelength
to given unit. Note that actual data are always kept in
internal unit (Angstrom), and only converted
to user unit by :meth:`GetWaveSet` during actual computation.
User unit is stored in ``self.waveunits``.
Throughput is unitless and cannot be converted.
Parameters
----------
targetunits : str
New unit name, as accepted by `~pysynphot.units.Units`.
"""
nunits = units.Units(targetunits)
self.waveunits = nunits | [
"def",
"convert",
"(",
"self",
",",
"targetunits",
")",
":",
"nunits",
"=",
"units",
".",
"Units",
"(",
"targetunits",
")",
"self",
".",
"waveunits",
"=",
"nunits"
] | Set new user unit, for wavelength only.
This effectively converts the spectrum wavelength
to given unit. Note that actual data are always kept in
internal unit (Angstrom), and only converted
to user unit by :meth:`GetWaveSet` during actual computation.
User unit is stored in ``self.waveunits``.
Throughput is unitless and cannot be converted.
Parameters
----------
targetunits : str
New unit name, as accepted by `~pysynphot.units.Units`. | [
"Set",
"new",
"user",
"unit",
"for",
"wavelength",
"only",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L2117-L2134 | train | 31,777 |
spacetelescope/pysynphot | pysynphot/spectrum.py | SpectralElement.sample | def sample(self, wave):
"""Sample the spectrum.
This uses :meth:`resample` to do the actual computation.
Parameters
----------
wave : number or array_like
Wavelength set for sampling, given in user unit.
Returns
-------
throughput : number or array_like
Sampled throughput.
"""
angwave = self.waveunits.ToAngstrom(wave)
return self.__call__(angwave) | python | def sample(self, wave):
"""Sample the spectrum.
This uses :meth:`resample` to do the actual computation.
Parameters
----------
wave : number or array_like
Wavelength set for sampling, given in user unit.
Returns
-------
throughput : number or array_like
Sampled throughput.
"""
angwave = self.waveunits.ToAngstrom(wave)
return self.__call__(angwave) | [
"def",
"sample",
"(",
"self",
",",
"wave",
")",
":",
"angwave",
"=",
"self",
".",
"waveunits",
".",
"ToAngstrom",
"(",
"wave",
")",
"return",
"self",
".",
"__call__",
"(",
"angwave",
")"
] | Sample the spectrum.
This uses :meth:`resample` to do the actual computation.
Parameters
----------
wave : number or array_like
Wavelength set for sampling, given in user unit.
Returns
-------
throughput : number or array_like
Sampled throughput. | [
"Sample",
"the",
"spectrum",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L2171-L2188 | train | 31,778 |
spacetelescope/pysynphot | pysynphot/spectrum.py | UniformTransmission.writefits | def writefits(self, *args, **kwargs):
"""Write to file using default waveset."""
old_wave = self.wave
self.wave = self._wavetable
try:
super(UniformTransmission, self).writefits(*args, **kwargs)
finally:
self.wave = old_wave | python | def writefits(self, *args, **kwargs):
"""Write to file using default waveset."""
old_wave = self.wave
self.wave = self._wavetable
try:
super(UniformTransmission, self).writefits(*args, **kwargs)
finally:
self.wave = old_wave | [
"def",
"writefits",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"old_wave",
"=",
"self",
".",
"wave",
"self",
".",
"wave",
"=",
"self",
".",
"_wavetable",
"try",
":",
"super",
"(",
"UniformTransmission",
",",
"self",
")",
".",
... | Write to file using default waveset. | [
"Write",
"to",
"file",
"using",
"default",
"waveset",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L2687-L2695 | train | 31,779 |
spacetelescope/pysynphot | pysynphot/spectrum.py | TabularSpectralElement.ToInternal | def ToInternal(self):
"""Convert wavelengths to the internal representation of angstroms.
For internal use only."""
self.validate_units()
savewunits = self.waveunits
angwave = self.waveunits.Convert(self._wavetable, 'angstrom')
self._wavetable = angwave.copy()
self.waveunits = savewunits | python | def ToInternal(self):
"""Convert wavelengths to the internal representation of angstroms.
For internal use only."""
self.validate_units()
savewunits = self.waveunits
angwave = self.waveunits.Convert(self._wavetable, 'angstrom')
self._wavetable = angwave.copy()
self.waveunits = savewunits | [
"def",
"ToInternal",
"(",
"self",
")",
":",
"self",
".",
"validate_units",
"(",
")",
"savewunits",
"=",
"self",
".",
"waveunits",
"angwave",
"=",
"self",
".",
"waveunits",
".",
"Convert",
"(",
"self",
".",
"_wavetable",
",",
"'angstrom'",
")",
"self",
".... | Convert wavelengths to the internal representation of angstroms.
For internal use only. | [
"Convert",
"wavelengths",
"to",
"the",
"internal",
"representation",
"of",
"angstroms",
".",
"For",
"internal",
"use",
"only",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L2812-L2819 | train | 31,780 |
spacetelescope/pysynphot | pysynphot/spectrum.py | Box.sample | def sample(self, wavelength):
"""Input wavelengths assumed to be in user unit."""
wave = self.waveunits.Convert(wavelength, 'angstrom')
return self(wave) | python | def sample(self, wavelength):
"""Input wavelengths assumed to be in user unit."""
wave = self.waveunits.Convert(wavelength, 'angstrom')
return self(wave) | [
"def",
"sample",
"(",
"self",
",",
"wavelength",
")",
":",
"wave",
"=",
"self",
".",
"waveunits",
".",
"Convert",
"(",
"wavelength",
",",
"'angstrom'",
")",
"return",
"self",
"(",
"wave",
")"
] | Input wavelengths assumed to be in user unit. | [
"Input",
"wavelengths",
"assumed",
"to",
"be",
"in",
"user",
"unit",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L3317-L3320 | train | 31,781 |
spacetelescope/pysynphot | pysynphot/observationmode.py | ObservationMode.Throughput | def Throughput(self):
"""Combined throughput from multiplying all the components together.
Returns
-------
throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None`
Combined throughput.
"""
try:
throughput = spectrum.TabularSpectralElement()
product = self._multiplyThroughputs(0)
throughput._wavetable = product.GetWaveSet()
throughput._throughputtable = product(throughput._wavetable)
throughput.waveunits = product.waveunits
throughput.name='*'.join([str(x) for x in self.components])
## throughput = throughput.resample(spectrum._default_waveset)
return throughput
except IndexError: # graph table is broken.
return None | python | def Throughput(self):
"""Combined throughput from multiplying all the components together.
Returns
-------
throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None`
Combined throughput.
"""
try:
throughput = spectrum.TabularSpectralElement()
product = self._multiplyThroughputs(0)
throughput._wavetable = product.GetWaveSet()
throughput._throughputtable = product(throughput._wavetable)
throughput.waveunits = product.waveunits
throughput.name='*'.join([str(x) for x in self.components])
## throughput = throughput.resample(spectrum._default_waveset)
return throughput
except IndexError: # graph table is broken.
return None | [
"def",
"Throughput",
"(",
"self",
")",
":",
"try",
":",
"throughput",
"=",
"spectrum",
".",
"TabularSpectralElement",
"(",
")",
"product",
"=",
"self",
".",
"_multiplyThroughputs",
"(",
"0",
")",
"throughput",
".",
"_wavetable",
"=",
"product",
".",
"GetWave... | Combined throughput from multiplying all the components together.
Returns
-------
throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None`
Combined throughput. | [
"Combined",
"throughput",
"from",
"multiplying",
"all",
"the",
"components",
"together",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observationmode.py#L368-L392 | train | 31,782 |
spacetelescope/pysynphot | pysynphot/observationmode.py | ObservationMode.ThermalSpectrum | def ThermalSpectrum(self):
"""Calculate thermal spectrum.
Returns
-------
sp : `~pysynphot.spectrum.CompositeSourceSpectrum`
Thermal spectrum in ``photlam``.
Raises
------
IndexError
Calculation failed.
"""
try:
# delegate to subclass.
thom = _ThermalObservationMode(self._obsmode)
self.pixscale = thom.pixscale
return thom._getSpectrum()
except IndexError: # graph table is broken.
raise IndexError("Cannot calculate thermal spectrum; graphtable may be broken") | python | def ThermalSpectrum(self):
"""Calculate thermal spectrum.
Returns
-------
sp : `~pysynphot.spectrum.CompositeSourceSpectrum`
Thermal spectrum in ``photlam``.
Raises
------
IndexError
Calculation failed.
"""
try:
# delegate to subclass.
thom = _ThermalObservationMode(self._obsmode)
self.pixscale = thom.pixscale
return thom._getSpectrum()
except IndexError: # graph table is broken.
raise IndexError("Cannot calculate thermal spectrum; graphtable may be broken") | [
"def",
"ThermalSpectrum",
"(",
"self",
")",
":",
"try",
":",
"# delegate to subclass.",
"thom",
"=",
"_ThermalObservationMode",
"(",
"self",
".",
"_obsmode",
")",
"self",
".",
"pixscale",
"=",
"thom",
".",
"pixscale",
"return",
"thom",
".",
"_getSpectrum",
"("... | Calculate thermal spectrum.
Returns
-------
sp : `~pysynphot.spectrum.CompositeSourceSpectrum`
Thermal spectrum in ``photlam``.
Raises
------
IndexError
Calculation failed. | [
"Calculate",
"thermal",
"spectrum",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observationmode.py#L404-L424 | train | 31,783 |
spacetelescope/pysynphot | pysynphot/observationmode.py | _ThermalObservationMode._multiplyThroughputs | def _multiplyThroughputs(self):
''' Overrides base class in order to deal with opaque components.
'''
index = 0
for component in self.components:
if component.throughput != None:
break
index += 1
return BaseObservationMode._multiplyThroughputs(self, index) | python | def _multiplyThroughputs(self):
''' Overrides base class in order to deal with opaque components.
'''
index = 0
for component in self.components:
if component.throughput != None:
break
index += 1
return BaseObservationMode._multiplyThroughputs(self, index) | [
"def",
"_multiplyThroughputs",
"(",
"self",
")",
":",
"index",
"=",
"0",
"for",
"component",
"in",
"self",
".",
"components",
":",
"if",
"component",
".",
"throughput",
"!=",
"None",
":",
"break",
"index",
"+=",
"1",
"return",
"BaseObservationMode",
".",
"... | Overrides base class in order to deal with opaque components. | [
"Overrides",
"base",
"class",
"in",
"order",
"to",
"deal",
"with",
"opaque",
"components",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observationmode.py#L515-L524 | train | 31,784 |
spacetelescope/pysynphot | commissioning/doscalars.py | reverse | def reverse(d):
"""Return a reverse lookup dictionary for the input dictionary"""
r={}
for k in d:
r[d[k]]=k
return r | python | def reverse(d):
"""Return a reverse lookup dictionary for the input dictionary"""
r={}
for k in d:
r[d[k]]=k
return r | [
"def",
"reverse",
"(",
"d",
")",
":",
"r",
"=",
"{",
"}",
"for",
"k",
"in",
"d",
":",
"r",
"[",
"d",
"[",
"k",
"]",
"]",
"=",
"k",
"return",
"r"
] | Return a reverse lookup dictionary for the input dictionary | [
"Return",
"a",
"reverse",
"lookup",
"dictionary",
"for",
"the",
"input",
"dictionary"
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/doscalars.py#L85-L90 | train | 31,785 |
spacetelescope/pysynphot | pysynphot/reddening.py | print_red_laws | def print_red_laws():
"""Print available extinction laws to screen.
Available extinction laws are extracted from ``pysynphot.locations.EXTDIR``.
The printed names may be used with :func:`Extinction`
to retrieve available reddening laws.
Examples
--------
>>> S.reddening.print_red_laws()
name reference
-------- --------------------------------------------------------------
None Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
gal3 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
lmc30dor Gordon et al. (2003, ApJ, 594, 279) R_V = 2.76.
lmcavg Gordon et al. (2003, ApJ, 594, 279) R_V = 3.41.
mwavg Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
mwdense Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 5.00.
mwrv21 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 2.1.
mwrv4 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 4.0.
smcbar Gordon et al. (2003, ApJ, 594, 279) R_V=2.74.
xgalsb Calzetti et al. (2000. ApJ, 533, 682)
"""
laws = {}
# start by converting the Cache.RedLaws file names to RedLaw objects
# if they aren't already
for k in Cache.RedLaws:
if isinstance(Cache.RedLaws[k],str):
Cache.RedLaws[k] = RedLaw(Cache.RedLaws[k])
laws[str(k)] = Cache.RedLaws[k].litref
# get the length of the longest name and litref
maxname = max([len(name) for name in laws.keys()])
maxref = max([len(ref) for ref in laws.values()])
s = '%-' + str(maxname) + 's %-' + str(maxref) + 's'
print(s % ('name','reference'))
print(s % ('-'*maxname,'-'*maxref))
for k in sorted(laws.keys()):
print(s % (k, laws[k])) | python | def print_red_laws():
"""Print available extinction laws to screen.
Available extinction laws are extracted from ``pysynphot.locations.EXTDIR``.
The printed names may be used with :func:`Extinction`
to retrieve available reddening laws.
Examples
--------
>>> S.reddening.print_red_laws()
name reference
-------- --------------------------------------------------------------
None Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
gal3 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
lmc30dor Gordon et al. (2003, ApJ, 594, 279) R_V = 2.76.
lmcavg Gordon et al. (2003, ApJ, 594, 279) R_V = 3.41.
mwavg Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
mwdense Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 5.00.
mwrv21 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 2.1.
mwrv4 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 4.0.
smcbar Gordon et al. (2003, ApJ, 594, 279) R_V=2.74.
xgalsb Calzetti et al. (2000. ApJ, 533, 682)
"""
laws = {}
# start by converting the Cache.RedLaws file names to RedLaw objects
# if they aren't already
for k in Cache.RedLaws:
if isinstance(Cache.RedLaws[k],str):
Cache.RedLaws[k] = RedLaw(Cache.RedLaws[k])
laws[str(k)] = Cache.RedLaws[k].litref
# get the length of the longest name and litref
maxname = max([len(name) for name in laws.keys()])
maxref = max([len(ref) for ref in laws.values()])
s = '%-' + str(maxname) + 's %-' + str(maxref) + 's'
print(s % ('name','reference'))
print(s % ('-'*maxname,'-'*maxref))
for k in sorted(laws.keys()):
print(s % (k, laws[k])) | [
"def",
"print_red_laws",
"(",
")",
":",
"laws",
"=",
"{",
"}",
"# start by converting the Cache.RedLaws file names to RedLaw objects",
"# if they aren't already",
"for",
"k",
"in",
"Cache",
".",
"RedLaws",
":",
"if",
"isinstance",
"(",
"Cache",
".",
"RedLaws",
"[",
... | Print available extinction laws to screen.
Available extinction laws are extracted from ``pysynphot.locations.EXTDIR``.
The printed names may be used with :func:`Extinction`
to retrieve available reddening laws.
Examples
--------
>>> S.reddening.print_red_laws()
name reference
-------- --------------------------------------------------------------
None Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
gal3 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
lmc30dor Gordon et al. (2003, ApJ, 594, 279) R_V = 2.76.
lmcavg Gordon et al. (2003, ApJ, 594, 279) R_V = 3.41.
mwavg Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 3.10.
mwdense Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 5.00.
mwrv21 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 2.1.
mwrv4 Cardelli, Clayton, & Mathis (1989, ApJ, 345, 245) R_V = 4.0.
smcbar Gordon et al. (2003, ApJ, 594, 279) R_V=2.74.
xgalsb Calzetti et al. (2000. ApJ, 533, 682) | [
"Print",
"available",
"extinction",
"laws",
"to",
"screen",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/reddening.py#L158-L202 | train | 31,786 |
spacetelescope/pysynphot | pysynphot/reddening.py | Extinction | def Extinction(extval,name=None):
"""Generate extinction curve to be used with spectra.
By default, :meth:`~CustomRedLaw.reddening` is used to
generate the extinction curve. If a deprecated
reddening law is given, then
`~pysynphot.extinction.DeprecatedExtinction` is used
instead.
.. note::
Reddening laws are cached in ``pysynphot.Cache.RedLaws``
for better performance. Repeated calls to the same
reddening law here returns the cached result.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
name : str or `None`
Name of reddening law (see :func:`print_red_laws`).
If `None` (default), the average Milky Way extinction
(``'mwavg'``) will be used.
Returns
-------
ext : `~pysynphot.spectrum.ArraySpectralElement` or `~pysynphot.extinction.DeprecatedExtinction`
Extinction curve.
Raises
------
ValueError
Invalid reddening law.
Examples
--------
>>> ext = S.Extinction(0.3, 'mwavg')
"""
try:
ext=Cache.RedLaws[name].reddening(extval)
except AttributeError:
#The cache hasn't yet been filled.
Cache.RedLaws[name]=RedLaw(Cache.RedLaws[name])
ext=Cache.RedLaws[name].reddening(extval)
except KeyError:
#There's no reddening law by that name. See if we've been
#given a filename from which we can read one.
try:
Cache.RedLaws[name]=RedLaw(name)
ext=Cache.RedLaws[name].reddening(extval)
except IOError:
#If not, see if it's an old extinction law
try:
ext=extinction.DeprecatedExtinction(extval,name)
except KeyError:
raise ValueError('No extinction law has been defined for "%s", and no such file exists'%name)
return ext | python | def Extinction(extval,name=None):
"""Generate extinction curve to be used with spectra.
By default, :meth:`~CustomRedLaw.reddening` is used to
generate the extinction curve. If a deprecated
reddening law is given, then
`~pysynphot.extinction.DeprecatedExtinction` is used
instead.
.. note::
Reddening laws are cached in ``pysynphot.Cache.RedLaws``
for better performance. Repeated calls to the same
reddening law here returns the cached result.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
name : str or `None`
Name of reddening law (see :func:`print_red_laws`).
If `None` (default), the average Milky Way extinction
(``'mwavg'``) will be used.
Returns
-------
ext : `~pysynphot.spectrum.ArraySpectralElement` or `~pysynphot.extinction.DeprecatedExtinction`
Extinction curve.
Raises
------
ValueError
Invalid reddening law.
Examples
--------
>>> ext = S.Extinction(0.3, 'mwavg')
"""
try:
ext=Cache.RedLaws[name].reddening(extval)
except AttributeError:
#The cache hasn't yet been filled.
Cache.RedLaws[name]=RedLaw(Cache.RedLaws[name])
ext=Cache.RedLaws[name].reddening(extval)
except KeyError:
#There's no reddening law by that name. See if we've been
#given a filename from which we can read one.
try:
Cache.RedLaws[name]=RedLaw(name)
ext=Cache.RedLaws[name].reddening(extval)
except IOError:
#If not, see if it's an old extinction law
try:
ext=extinction.DeprecatedExtinction(extval,name)
except KeyError:
raise ValueError('No extinction law has been defined for "%s", and no such file exists'%name)
return ext | [
"def",
"Extinction",
"(",
"extval",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"ext",
"=",
"Cache",
".",
"RedLaws",
"[",
"name",
"]",
".",
"reddening",
"(",
"extval",
")",
"except",
"AttributeError",
":",
"#The cache hasn't yet been filled.",
"Cache",
... | Generate extinction curve to be used with spectra.
By default, :meth:`~CustomRedLaw.reddening` is used to
generate the extinction curve. If a deprecated
reddening law is given, then
`~pysynphot.extinction.DeprecatedExtinction` is used
instead.
.. note::
Reddening laws are cached in ``pysynphot.Cache.RedLaws``
for better performance. Repeated calls to the same
reddening law here returns the cached result.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
name : str or `None`
Name of reddening law (see :func:`print_red_laws`).
If `None` (default), the average Milky Way extinction
(``'mwavg'``) will be used.
Returns
-------
ext : `~pysynphot.spectrum.ArraySpectralElement` or `~pysynphot.extinction.DeprecatedExtinction`
Extinction curve.
Raises
------
ValueError
Invalid reddening law.
Examples
--------
>>> ext = S.Extinction(0.3, 'mwavg') | [
"Generate",
"extinction",
"curve",
"to",
"be",
"used",
"with",
"spectra",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/reddening.py#L205-L263 | train | 31,787 |
spacetelescope/pysynphot | pysynphot/reddening.py | ExtinctionSpectralElement._getWaveProp | def _getWaveProp(self):
"""Return wavelength in user units."""
wave = units.Angstrom().Convert(self._wavetable, self.waveunits.name)
return wave | python | def _getWaveProp(self):
"""Return wavelength in user units."""
wave = units.Angstrom().Convert(self._wavetable, self.waveunits.name)
return wave | [
"def",
"_getWaveProp",
"(",
"self",
")",
":",
"wave",
"=",
"units",
".",
"Angstrom",
"(",
")",
".",
"Convert",
"(",
"self",
".",
"_wavetable",
",",
"self",
".",
"waveunits",
".",
"name",
")",
"return",
"wave"
] | Return wavelength in user units. | [
"Return",
"wavelength",
"in",
"user",
"units",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/reddening.py#L23-L26 | train | 31,788 |
spacetelescope/pysynphot | pysynphot/reddening.py | CustomRedLaw.reddening | def reddening(self,extval):
"""Compute the reddening for the given extinction.
.. math::
A(V) = R(V) \\; \\times \\; E(B-V)
\\textnormal{THRU} = 10^{-0.4 \\; A(V)}
.. note::
``self.litref`` is passed into ``ans.citation``.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
Returns
-------
ans : `~pysynphot.spectrum.ArraySpectralElement`
Extinction curve to apply to a source spectrum.
"""
T = 10.0**(-0.4*extval*self.obscuration)
ans = ExtinctionSpectralElement(wave=self.wave,
waveunits=self.waveunits,
throughput=T,
name='%s(EBV=%g)'%(self.name, extval))
ans.citation = self.litref
return ans | python | def reddening(self,extval):
"""Compute the reddening for the given extinction.
.. math::
A(V) = R(V) \\; \\times \\; E(B-V)
\\textnormal{THRU} = 10^{-0.4 \\; A(V)}
.. note::
``self.litref`` is passed into ``ans.citation``.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
Returns
-------
ans : `~pysynphot.spectrum.ArraySpectralElement`
Extinction curve to apply to a source spectrum.
"""
T = 10.0**(-0.4*extval*self.obscuration)
ans = ExtinctionSpectralElement(wave=self.wave,
waveunits=self.waveunits,
throughput=T,
name='%s(EBV=%g)'%(self.name, extval))
ans.citation = self.litref
return ans | [
"def",
"reddening",
"(",
"self",
",",
"extval",
")",
":",
"T",
"=",
"10.0",
"**",
"(",
"-",
"0.4",
"*",
"extval",
"*",
"self",
".",
"obscuration",
")",
"ans",
"=",
"ExtinctionSpectralElement",
"(",
"wave",
"=",
"self",
".",
"wave",
",",
"waveunits",
... | Compute the reddening for the given extinction.
.. math::
A(V) = R(V) \\; \\times \\; E(B-V)
\\textnormal{THRU} = 10^{-0.4 \\; A(V)}
.. note::
``self.litref`` is passed into ``ans.citation``.
Parameters
----------
extval : float
Value of :math:`E(B-V)` in magnitudes.
Returns
-------
ans : `~pysynphot.spectrum.ArraySpectralElement`
Extinction curve to apply to a source spectrum. | [
"Compute",
"the",
"reddening",
"for",
"the",
"given",
"extinction",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/reddening.py#L79-L109 | train | 31,789 |
spacetelescope/pysynphot | pysynphot/tables.py | GraphTable.GetNextNode | def GetNextNode(self, modes, innode):
"""GetNextNode returns the outnode that matches an element from
the modes list, starting at the given innode.
This method isnt actually used, its just a helper method for
debugging purposes.
"""
nodes = N.where(self.innodes == innode)
## If there's no entry for the given innode, return -1
if nodes[0].size == 0:
return -1
## If we don't match anything in the modes list, we find the
## outnode corresponding the the string 'default'
defaultindex = N.where(self.keywords[nodes] == 'default')
if len(defaultindex[0]) != 0:
outnode = self.outnodes[nodes[0][defaultindex[0]]]
## Now try and match one of the strings in the modes list with
## the keywords corresponding to the list of entries with the given
## innode
for mode in modes:
result = self.keywords[nodes].count(mode)
if result != 0:
index = N.where(self.keywords[nodes]==mode)
outnode = self.outnodes[nodes[0][index[0]]]
## Return the outnode corresponding either to the matched mode,
## or to 'default'
return outnode | python | def GetNextNode(self, modes, innode):
"""GetNextNode returns the outnode that matches an element from
the modes list, starting at the given innode.
This method isnt actually used, its just a helper method for
debugging purposes.
"""
nodes = N.where(self.innodes == innode)
## If there's no entry for the given innode, return -1
if nodes[0].size == 0:
return -1
## If we don't match anything in the modes list, we find the
## outnode corresponding the the string 'default'
defaultindex = N.where(self.keywords[nodes] == 'default')
if len(defaultindex[0]) != 0:
outnode = self.outnodes[nodes[0][defaultindex[0]]]
## Now try and match one of the strings in the modes list with
## the keywords corresponding to the list of entries with the given
## innode
for mode in modes:
result = self.keywords[nodes].count(mode)
if result != 0:
index = N.where(self.keywords[nodes]==mode)
outnode = self.outnodes[nodes[0][index[0]]]
## Return the outnode corresponding either to the matched mode,
## or to 'default'
return outnode | [
"def",
"GetNextNode",
"(",
"self",
",",
"modes",
",",
"innode",
")",
":",
"nodes",
"=",
"N",
".",
"where",
"(",
"self",
".",
"innodes",
"==",
"innode",
")",
"## If there's no entry for the given innode, return -1",
"if",
"nodes",
"[",
"0",
"]",
".",
"size",
... | GetNextNode returns the outnode that matches an element from
the modes list, starting at the given innode.
This method isnt actually used, its just a helper method for
debugging purposes. | [
"GetNextNode",
"returns",
"the",
"outnode",
"that",
"matches",
"an",
"element",
"from",
"the",
"modes",
"list",
"starting",
"at",
"the",
"given",
"innode",
".",
"This",
"method",
"isnt",
"actually",
"used",
"its",
"just",
"a",
"helper",
"method",
"for",
"deb... | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/tables.py#L120-L152 | train | 31,790 |
spacetelescope/pysynphot | pysynphot/tables.py | GraphTable.GetComponentsFromGT | def GetComponentsFromGT(self, modes, innode):
"""Obtain components from graph table for the given
observation mode keywords and starting node.
.. note::
This prints extra information to screen if
``pysynphot.tables.DEBUG`` is set to `True`.
Parameters
----------
modes : list of str
List of individual keywords within the observation mode.
innode : int
Starting node, usually 1.
Returns
-------
components, thcomponents : list of str
List of optical and thermal component names.
Raises
------
KeyError
No matches found for one of the keywords.
ValueError
Incomplete observation mode or unused keyword(s) detected.
"""
components = []
thcomponents = []
outnode = 0
inmodes=set(modes)
used_modes=set()
count = 0
while outnode >= 0:
if (DEBUG and (outnode < 0)):
print("outnode == %d: stop condition"%outnode)
previous_outnode = outnode
nodes = N.where(self.innodes == innode)
# If there are no entries with this innode, we're done
if nodes[0].size == 0:
if DEBUG:
print("no such innode %d: stop condition"%innode)
#return (components,thcomponents)
break
# Find the entry corresponding to the component named
# 'default', bacause thats the one we'll use if we don't
# match anything in the modes list
defaultindex = N.where(self.keywords[nodes] =='default')
if 'default' in self.keywords[nodes]:
dfi=N.where(self.keywords[nodes] == 'default')[0][0]
outnode = self.outnodes[nodes[0][dfi]]
component = self.compnames[nodes[0][dfi]]
thcomponent = self.thcompnames[nodes[0][dfi]]
used_default=True
else:
#There's no default, so fail if you don't match anything
# in the keyword matching step.
outnode = -2
component = thcomponent = None
# Now try and match something from the modes list
for mode in modes:
if mode in self.keywords[nodes]:
used_modes.add(mode)
index = N.where(self.keywords[nodes]==mode)
if len(index[0])>1:
raise KeyError('%d matches found for %s'%(len(index[0]),mode))
idx=index[0][0]
component = self.compnames[nodes[0][idx]]
thcomponent = self.thcompnames[nodes[0][idx]]
outnode = self.outnodes[nodes[0][idx]]
used_default=False
if DEBUG:
print("Innode %d Outnode %d Compname %s"%(innode, outnode, component))
components.append(component)
thcomponents.append(thcomponent)
innode = outnode
if outnode == previous_outnode:
if DEBUG:
print("Innode: %d Outnode:%d Used default: %s"%(innode, outnode,used_default))
count += 1
if count > 3:
if DEBUG:
print("same outnode %d > 3 times: stop condition"%outnode)
break
if (outnode < 0):
if DEBUG:
print("outnode == %d: stop condition"%outnode)
raise ValueError("Incomplete obsmode %s"%str(modes))
#Check for unused modes
if inmodes != used_modes:
unused=str(inmodes.difference(used_modes))
raise ValueError("Warning: unused keywords %s"%unused)
return (components,thcomponents) | python | def GetComponentsFromGT(self, modes, innode):
"""Obtain components from graph table for the given
observation mode keywords and starting node.
.. note::
This prints extra information to screen if
``pysynphot.tables.DEBUG`` is set to `True`.
Parameters
----------
modes : list of str
List of individual keywords within the observation mode.
innode : int
Starting node, usually 1.
Returns
-------
components, thcomponents : list of str
List of optical and thermal component names.
Raises
------
KeyError
No matches found for one of the keywords.
ValueError
Incomplete observation mode or unused keyword(s) detected.
"""
components = []
thcomponents = []
outnode = 0
inmodes=set(modes)
used_modes=set()
count = 0
while outnode >= 0:
if (DEBUG and (outnode < 0)):
print("outnode == %d: stop condition"%outnode)
previous_outnode = outnode
nodes = N.where(self.innodes == innode)
# If there are no entries with this innode, we're done
if nodes[0].size == 0:
if DEBUG:
print("no such innode %d: stop condition"%innode)
#return (components,thcomponents)
break
# Find the entry corresponding to the component named
# 'default', bacause thats the one we'll use if we don't
# match anything in the modes list
defaultindex = N.where(self.keywords[nodes] =='default')
if 'default' in self.keywords[nodes]:
dfi=N.where(self.keywords[nodes] == 'default')[0][0]
outnode = self.outnodes[nodes[0][dfi]]
component = self.compnames[nodes[0][dfi]]
thcomponent = self.thcompnames[nodes[0][dfi]]
used_default=True
else:
#There's no default, so fail if you don't match anything
# in the keyword matching step.
outnode = -2
component = thcomponent = None
# Now try and match something from the modes list
for mode in modes:
if mode in self.keywords[nodes]:
used_modes.add(mode)
index = N.where(self.keywords[nodes]==mode)
if len(index[0])>1:
raise KeyError('%d matches found for %s'%(len(index[0]),mode))
idx=index[0][0]
component = self.compnames[nodes[0][idx]]
thcomponent = self.thcompnames[nodes[0][idx]]
outnode = self.outnodes[nodes[0][idx]]
used_default=False
if DEBUG:
print("Innode %d Outnode %d Compname %s"%(innode, outnode, component))
components.append(component)
thcomponents.append(thcomponent)
innode = outnode
if outnode == previous_outnode:
if DEBUG:
print("Innode: %d Outnode:%d Used default: %s"%(innode, outnode,used_default))
count += 1
if count > 3:
if DEBUG:
print("same outnode %d > 3 times: stop condition"%outnode)
break
if (outnode < 0):
if DEBUG:
print("outnode == %d: stop condition"%outnode)
raise ValueError("Incomplete obsmode %s"%str(modes))
#Check for unused modes
if inmodes != used_modes:
unused=str(inmodes.difference(used_modes))
raise ValueError("Warning: unused keywords %s"%unused)
return (components,thcomponents) | [
"def",
"GetComponentsFromGT",
"(",
"self",
",",
"modes",
",",
"innode",
")",
":",
"components",
"=",
"[",
"]",
"thcomponents",
"=",
"[",
"]",
"outnode",
"=",
"0",
"inmodes",
"=",
"set",
"(",
"modes",
")",
"used_modes",
"=",
"set",
"(",
")",
"count",
... | Obtain components from graph table for the given
observation mode keywords and starting node.
.. note::
This prints extra information to screen if
``pysynphot.tables.DEBUG`` is set to `True`.
Parameters
----------
modes : list of str
List of individual keywords within the observation mode.
innode : int
Starting node, usually 1.
Returns
-------
components, thcomponents : list of str
List of optical and thermal component names.
Raises
------
KeyError
No matches found for one of the keywords.
ValueError
Incomplete observation mode or unused keyword(s) detected. | [
"Obtain",
"components",
"from",
"graph",
"table",
"for",
"the",
"given",
"observation",
"mode",
"keywords",
"and",
"starting",
"node",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/tables.py#L154-L265 | train | 31,791 |
spacetelescope/pysynphot | commissioning/extrap/extrap.py | fincre | def fincre(oldname):
"""Increment the synphot version number from a filename"""
x=re.search('_(?P<version>[0-9][0-9][0-9])_syn',oldname)
version=x.group('version')
newversion="%03d"%(int(version)+1)
ans=oldname.replace(version,newversion)
return ans | python | def fincre(oldname):
"""Increment the synphot version number from a filename"""
x=re.search('_(?P<version>[0-9][0-9][0-9])_syn',oldname)
version=x.group('version')
newversion="%03d"%(int(version)+1)
ans=oldname.replace(version,newversion)
return ans | [
"def",
"fincre",
"(",
"oldname",
")",
":",
"x",
"=",
"re",
".",
"search",
"(",
"'_(?P<version>[0-9][0-9][0-9])_syn'",
",",
"oldname",
")",
"version",
"=",
"x",
".",
"group",
"(",
"'version'",
")",
"newversion",
"=",
"\"%03d\"",
"%",
"(",
"int",
"(",
"ver... | Increment the synphot version number from a filename | [
"Increment",
"the",
"synphot",
"version",
"number",
"from",
"a",
"filename"
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/extrap/extrap.py#L207-L213 | train | 31,792 |
spacetelescope/pysynphot | commissioning/basecase.py | calcspecCase.run_crbox | def run_crbox(self,spstring,form,output="",wavecat="INDEF",
lowave=0,hiwave=30000):
"""Calcspec has a bug. We will use countrate instead, and force it
to use a box function of uniform transmission as the obsmode."""
range=hiwave-lowave
midwave=range/2.0
iraf.countrate(spectrum=spstring, magnitude="",
instrument="box(%f,%f)"%(midwave,range),
form=form,
wavecat=wavecat,
output=output) | python | def run_crbox(self,spstring,form,output="",wavecat="INDEF",
lowave=0,hiwave=30000):
"""Calcspec has a bug. We will use countrate instead, and force it
to use a box function of uniform transmission as the obsmode."""
range=hiwave-lowave
midwave=range/2.0
iraf.countrate(spectrum=spstring, magnitude="",
instrument="box(%f,%f)"%(midwave,range),
form=form,
wavecat=wavecat,
output=output) | [
"def",
"run_crbox",
"(",
"self",
",",
"spstring",
",",
"form",
",",
"output",
"=",
"\"\"",
",",
"wavecat",
"=",
"\"INDEF\"",
",",
"lowave",
"=",
"0",
",",
"hiwave",
"=",
"30000",
")",
":",
"range",
"=",
"hiwave",
"-",
"lowave",
"midwave",
"=",
"range... | Calcspec has a bug. We will use countrate instead, and force it
to use a box function of uniform transmission as the obsmode. | [
"Calcspec",
"has",
"a",
"bug",
".",
"We",
"will",
"use",
"countrate",
"instead",
"and",
"force",
"it",
"to",
"use",
"a",
"box",
"function",
"of",
"uniform",
"transmission",
"as",
"the",
"obsmode",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/basecase.py#L70-L81 | train | 31,793 |
spacetelescope/pysynphot | pysynphot/observation.py | validate_overlap | def validate_overlap(comp1, comp2, force):
"""Validate the overlap between the wavelength sets
of the two given components.
Parameters
----------
comp1, comp2 : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`
Source spectrum and bandpass of an observation.
force : {'extrap', 'taper', `None`}
If not `None`, the components may be adjusted by
extrapolation or tapering.
Returns
-------
comp1, comp2
Same as inputs. However, ``comp1`` might be tapered
if that option is selected.
warnings : dict
Maps warning keyword to its description.
Raises
------
KeyError
Invalid ``force``.
pysynphot.exceptions.DisjointError
No overlap detected when ``force`` is `None`.
pysynphot.exceptions.PartialOverlap
Partial overlap detected when ``force`` is `None`.
"""
warnings = dict()
if force is None:
stat = comp2.check_overlap(comp1)
if stat=='full':
pass
elif stat == 'partial':
raise(exceptions.PartialOverlap('Spectrum and bandpass do not fully overlap. You may use force=[extrap|taper] to force this Observation anyway.'))
elif stat == 'none':
raise(exceptions.DisjointError('Spectrum and bandpass are disjoint'))
elif force.lower() == 'taper':
try:
comp1=comp1.taper()
except AttributeError:
comp1=comp1.tabulate().taper()
warnings['PartialOverlap']=force
elif force.lower().startswith('extrap'):
#default behavior works, but check the overlap so we can set the warning
stat=comp2.check_overlap(comp1)
if stat == 'partial':
warnings['PartialOverlap']=force
else:
raise(KeyError("Illegal value force=%s; legal values=('taper','extrap')"%force))
return comp1, comp2, warnings | python | def validate_overlap(comp1, comp2, force):
"""Validate the overlap between the wavelength sets
of the two given components.
Parameters
----------
comp1, comp2 : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`
Source spectrum and bandpass of an observation.
force : {'extrap', 'taper', `None`}
If not `None`, the components may be adjusted by
extrapolation or tapering.
Returns
-------
comp1, comp2
Same as inputs. However, ``comp1`` might be tapered
if that option is selected.
warnings : dict
Maps warning keyword to its description.
Raises
------
KeyError
Invalid ``force``.
pysynphot.exceptions.DisjointError
No overlap detected when ``force`` is `None`.
pysynphot.exceptions.PartialOverlap
Partial overlap detected when ``force`` is `None`.
"""
warnings = dict()
if force is None:
stat = comp2.check_overlap(comp1)
if stat=='full':
pass
elif stat == 'partial':
raise(exceptions.PartialOverlap('Spectrum and bandpass do not fully overlap. You may use force=[extrap|taper] to force this Observation anyway.'))
elif stat == 'none':
raise(exceptions.DisjointError('Spectrum and bandpass are disjoint'))
elif force.lower() == 'taper':
try:
comp1=comp1.taper()
except AttributeError:
comp1=comp1.tabulate().taper()
warnings['PartialOverlap']=force
elif force.lower().startswith('extrap'):
#default behavior works, but check the overlap so we can set the warning
stat=comp2.check_overlap(comp1)
if stat == 'partial':
warnings['PartialOverlap']=force
else:
raise(KeyError("Illegal value force=%s; legal values=('taper','extrap')"%force))
return comp1, comp2, warnings | [
"def",
"validate_overlap",
"(",
"comp1",
",",
"comp2",
",",
"force",
")",
":",
"warnings",
"=",
"dict",
"(",
")",
"if",
"force",
"is",
"None",
":",
"stat",
"=",
"comp2",
".",
"check_overlap",
"(",
"comp1",
")",
"if",
"stat",
"==",
"'full'",
":",
"pas... | Validate the overlap between the wavelength sets
of the two given components.
Parameters
----------
comp1, comp2 : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`
Source spectrum and bandpass of an observation.
force : {'extrap', 'taper', `None`}
If not `None`, the components may be adjusted by
extrapolation or tapering.
Returns
-------
comp1, comp2
Same as inputs. However, ``comp1`` might be tapered
if that option is selected.
warnings : dict
Maps warning keyword to its description.
Raises
------
KeyError
Invalid ``force``.
pysynphot.exceptions.DisjointError
No overlap detected when ``force`` is `None`.
pysynphot.exceptions.PartialOverlap
Partial overlap detected when ``force`` is `None`. | [
"Validate",
"the",
"overlap",
"between",
"the",
"wavelength",
"sets",
"of",
"the",
"two",
"given",
"components",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observation.py#L81-L140 | train | 31,794 |
spacetelescope/pysynphot | pysynphot/observation.py | Observation.validate_overlap | def validate_overlap(self,force):
"""Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. Partial overlap is allowed if this is set to
``'extrap'`` or ``'taper'``. See :func:`validate_overlap`.
"""
#Wrap the function for convenience
self.spectrum, self.bandpass, warn = validate_overlap(self.spectrum,
self.bandpass, force)
self.warnings.update(warn) | python | def validate_overlap(self,force):
"""Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. Partial overlap is allowed if this is set to
``'extrap'`` or ``'taper'``. See :func:`validate_overlap`.
"""
#Wrap the function for convenience
self.spectrum, self.bandpass, warn = validate_overlap(self.spectrum,
self.bandpass, force)
self.warnings.update(warn) | [
"def",
"validate_overlap",
"(",
"self",
",",
"force",
")",
":",
"#Wrap the function for convenience",
"self",
".",
"spectrum",
",",
"self",
".",
"bandpass",
",",
"warn",
"=",
"validate_overlap",
"(",
"self",
".",
"spectrum",
",",
"self",
".",
"bandpass",
",",
... | Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. Partial overlap is allowed if this is set to
``'extrap'`` or ``'taper'``. See :func:`validate_overlap`. | [
"Validate",
"that",
"spectrum",
"and",
"bandpass",
"overlap",
".",
"Warnings",
"are",
"stored",
"in",
"self",
".",
"warnings",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observation.py#L236-L252 | train | 31,795 |
spacetelescope/pysynphot | pysynphot/observation.py | Observation.initbinset | def initbinset(self,binset=None):
"""Set ``self.binwave``.
By default, wavelength values for binning are inherited
from bandpass. If the bandpass has no binning information,
then source spectrum wavelengths are used. However, if
user provides values, then those are used without question.
Parameters
----------
binset : array_like or `None`
Wavelength values to be used for binning when converting to counts.
"""
if binset is None:
msg="(%s) does not have a defined binset in the wavecat table. The waveset of the spectrum will be used instead."%str(self.bandpass)
try:
self.binwave = self.bandpass.binset
except (KeyError, AttributeError):
self.binwave = self.spectrum.wave
print(msg)
if self.binwave is None:
self.binwave = self.spectrum.wave
print(msg)
else:
self.binwave=binset | python | def initbinset(self,binset=None):
"""Set ``self.binwave``.
By default, wavelength values for binning are inherited
from bandpass. If the bandpass has no binning information,
then source spectrum wavelengths are used. However, if
user provides values, then those are used without question.
Parameters
----------
binset : array_like or `None`
Wavelength values to be used for binning when converting to counts.
"""
if binset is None:
msg="(%s) does not have a defined binset in the wavecat table. The waveset of the spectrum will be used instead."%str(self.bandpass)
try:
self.binwave = self.bandpass.binset
except (KeyError, AttributeError):
self.binwave = self.spectrum.wave
print(msg)
if self.binwave is None:
self.binwave = self.spectrum.wave
print(msg)
else:
self.binwave=binset | [
"def",
"initbinset",
"(",
"self",
",",
"binset",
"=",
"None",
")",
":",
"if",
"binset",
"is",
"None",
":",
"msg",
"=",
"\"(%s) does not have a defined binset in the wavecat table. The waveset of the spectrum will be used instead.\"",
"%",
"str",
"(",
"self",
".",
"bandp... | Set ``self.binwave``.
By default, wavelength values for binning are inherited
from bandpass. If the bandpass has no binning information,
then source spectrum wavelengths are used. However, if
user provides values, then those are used without question.
Parameters
----------
binset : array_like or `None`
Wavelength values to be used for binning when converting to counts. | [
"Set",
"self",
".",
"binwave",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observation.py#L254-L281 | train | 31,796 |
spacetelescope/pysynphot | pysynphot/observation.py | Observation.initbinflux | def initbinflux(self):
"""Calculate binned flux and edges.
Flux is computed by integrating the spectrum
on the specified binned wavelength set, using
information from the natural wavelength set.
Native wave/flux arrays should be considered samples
of a continuous function, but not their binned counterparts.
Thus, it makes sense to interpolate ``(wave, flux)`` but not
``(binwave, binflux)``.
.. note::
Assumes that the wavelength values in the binned
wavelength set are the *centers* of the bins.
Uses ``pysynphot.pysynphot_utils.calcbinflux()`` C-extension,
if available, for binned flux calculation.
"""
endpoints = binning.calculate_bin_edges(self.binwave)
# merge these endpoints in with the natural waveset
spwave = spectrum.MergeWaveSets(self.wave, endpoints)
spwave = spectrum.MergeWaveSets(spwave,self.binwave)
# compute indices associated to each endpoint.
indices = np.searchsorted(spwave, endpoints)
self._indices = indices[:-1]
self._indices_last = indices[1:]
# prepare integration variables.
flux = self(spwave)
avflux = (flux[1:] + flux[:-1]) / 2.0
self._deltaw = spwave[1:] - spwave[:-1]
# sum over each bin.
if utils_imported is True:
self._binflux, self._intwave = \
pysynphot_utils.calcbinflux(len(self.binwave),
self._indices,
self._indices_last,
avflux,
self._deltaw)
else:
#Note that, like all Python striding, the range over which
#we integrate is [first:last).
self._binflux = np.empty(shape=self.binwave.shape,dtype=np.float64)
self._intwave = np.empty(shape=self.binwave.shape,dtype=np.float64)
for i in range(len(self._indices)):
first = self._indices[i]
last = self._indices_last[i]
self._binflux[i]=(avflux[first:last]*self._deltaw[first:last]).sum()/self._deltaw[first:last].sum()
self._intwave[i]=self._deltaw[first:last].sum()
#Save the endpoints for future use
self._bin_edges = endpoints | python | def initbinflux(self):
"""Calculate binned flux and edges.
Flux is computed by integrating the spectrum
on the specified binned wavelength set, using
information from the natural wavelength set.
Native wave/flux arrays should be considered samples
of a continuous function, but not their binned counterparts.
Thus, it makes sense to interpolate ``(wave, flux)`` but not
``(binwave, binflux)``.
.. note::
Assumes that the wavelength values in the binned
wavelength set are the *centers* of the bins.
Uses ``pysynphot.pysynphot_utils.calcbinflux()`` C-extension,
if available, for binned flux calculation.
"""
endpoints = binning.calculate_bin_edges(self.binwave)
# merge these endpoints in with the natural waveset
spwave = spectrum.MergeWaveSets(self.wave, endpoints)
spwave = spectrum.MergeWaveSets(spwave,self.binwave)
# compute indices associated to each endpoint.
indices = np.searchsorted(spwave, endpoints)
self._indices = indices[:-1]
self._indices_last = indices[1:]
# prepare integration variables.
flux = self(spwave)
avflux = (flux[1:] + flux[:-1]) / 2.0
self._deltaw = spwave[1:] - spwave[:-1]
# sum over each bin.
if utils_imported is True:
self._binflux, self._intwave = \
pysynphot_utils.calcbinflux(len(self.binwave),
self._indices,
self._indices_last,
avflux,
self._deltaw)
else:
#Note that, like all Python striding, the range over which
#we integrate is [first:last).
self._binflux = np.empty(shape=self.binwave.shape,dtype=np.float64)
self._intwave = np.empty(shape=self.binwave.shape,dtype=np.float64)
for i in range(len(self._indices)):
first = self._indices[i]
last = self._indices_last[i]
self._binflux[i]=(avflux[first:last]*self._deltaw[first:last]).sum()/self._deltaw[first:last].sum()
self._intwave[i]=self._deltaw[first:last].sum()
#Save the endpoints for future use
self._bin_edges = endpoints | [
"def",
"initbinflux",
"(",
"self",
")",
":",
"endpoints",
"=",
"binning",
".",
"calculate_bin_edges",
"(",
"self",
".",
"binwave",
")",
"# merge these endpoints in with the natural waveset",
"spwave",
"=",
"spectrum",
".",
"MergeWaveSets",
"(",
"self",
".",
"wave",
... | Calculate binned flux and edges.
Flux is computed by integrating the spectrum
on the specified binned wavelength set, using
information from the natural wavelength set.
Native wave/flux arrays should be considered samples
of a continuous function, but not their binned counterparts.
Thus, it makes sense to interpolate ``(wave, flux)`` but not
``(binwave, binflux)``.
.. note::
Assumes that the wavelength values in the binned
wavelength set are the *centers* of the bins.
Uses ``pysynphot.pysynphot_utils.calcbinflux()`` C-extension,
if available, for binned flux calculation. | [
"Calculate",
"binned",
"flux",
"and",
"edges",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observation.py#L283-L340 | train | 31,797 |
spacetelescope/pysynphot | pysynphot/observation.py | Observation.as_spectrum | def as_spectrum(self, binned=True):
"""Reduce the observation to a simple spectrum object.
An observation is a complex object with some restrictions on its
capabilities. At times, it would be useful to work with the
simulated observation as a simple object that is easier to
manipulate and takes up less memory.
Parameters
----------
binned : bool
If `True` (default), export binned dataset. Otherwise, native.
Returns
-------
result : `~pysynphot.spectrum.ArraySourceSpectrum`
Observation dataset as a simple spectrum object.
"""
if binned:
wave, flux = self.binwave, self.binflux
else:
wave, flux = self.wave, self.flux
result = ArraySourceSpectrum(wave, flux,
self.waveunits,
self.fluxunits,
name = self.name,
keepneg = True)
return result | python | def as_spectrum(self, binned=True):
"""Reduce the observation to a simple spectrum object.
An observation is a complex object with some restrictions on its
capabilities. At times, it would be useful to work with the
simulated observation as a simple object that is easier to
manipulate and takes up less memory.
Parameters
----------
binned : bool
If `True` (default), export binned dataset. Otherwise, native.
Returns
-------
result : `~pysynphot.spectrum.ArraySourceSpectrum`
Observation dataset as a simple spectrum object.
"""
if binned:
wave, flux = self.binwave, self.binflux
else:
wave, flux = self.wave, self.flux
result = ArraySourceSpectrum(wave, flux,
self.waveunits,
self.fluxunits,
name = self.name,
keepneg = True)
return result | [
"def",
"as_spectrum",
"(",
"self",
",",
"binned",
"=",
"True",
")",
":",
"if",
"binned",
":",
"wave",
",",
"flux",
"=",
"self",
".",
"binwave",
",",
"self",
".",
"binflux",
"else",
":",
"wave",
",",
"flux",
"=",
"self",
".",
"wave",
",",
"self",
... | Reduce the observation to a simple spectrum object.
An observation is a complex object with some restrictions on its
capabilities. At times, it would be useful to work with the
simulated observation as a simple object that is easier to
manipulate and takes up less memory.
Parameters
----------
binned : bool
If `True` (default), export binned dataset. Otherwise, native.
Returns
-------
result : `~pysynphot.spectrum.ArraySourceSpectrum`
Observation dataset as a simple spectrum object. | [
"Reduce",
"the",
"observation",
"to",
"a",
"simple",
"spectrum",
"object",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/observation.py#L833-L863 | train | 31,798 |
spacetelescope/pysynphot | pysynphot/locations.py | irafconvert | def irafconvert(iraffilename):
"""Convert the IRAF file name to its Unix equivalent.
Input can be in ``directory$file`` or ``$directory/file`` format.
If ``'$'`` is not found in the input string, it is returned as-is.
Parameters
----------
iraffilename : str
Filename in IRAF format.
Returns
-------
unixfilename : str
Filename in Unix format.
Raises
------
AttributeError
Input is not a string.
"""
convertdict = CONVERTDICT
# remove duplicate separators and extraneous relative paths
if not iraffilename.lower().startswith(('http', 'ftp')):
iraffilename = os.path.normpath(iraffilename)
# BUG: supports environment variables only as the leading element in the
# filename
if iraffilename.startswith('$'):
# Then this is an environment variable.
# Use a regex to pull off the front piece.
pat = re.compile(r'\$(\w*)')
match = re.match(pat, iraffilename)
dirname = match.group(1)
unixdir = os.environ[dirname]
basename = iraffilename[match.end() + 1:] # 1 to omit leading slash
unixfilename = os.path.join(unixdir, basename)
return unixfilename
elif '$' in iraffilename:
# Then it's an iraf-style variable
irafdir, basename = iraffilename.split('$')
if irafdir == 'synphot':
return get_data_filename(os.path.basename(basename))
unixdir = convertdict[irafdir]
unixfilename = os.path.join(unixdir, basename)
return unixfilename
else:
# If no $ sign found, just return the filename unchanged
return iraffilename | python | def irafconvert(iraffilename):
"""Convert the IRAF file name to its Unix equivalent.
Input can be in ``directory$file`` or ``$directory/file`` format.
If ``'$'`` is not found in the input string, it is returned as-is.
Parameters
----------
iraffilename : str
Filename in IRAF format.
Returns
-------
unixfilename : str
Filename in Unix format.
Raises
------
AttributeError
Input is not a string.
"""
convertdict = CONVERTDICT
# remove duplicate separators and extraneous relative paths
if not iraffilename.lower().startswith(('http', 'ftp')):
iraffilename = os.path.normpath(iraffilename)
# BUG: supports environment variables only as the leading element in the
# filename
if iraffilename.startswith('$'):
# Then this is an environment variable.
# Use a regex to pull off the front piece.
pat = re.compile(r'\$(\w*)')
match = re.match(pat, iraffilename)
dirname = match.group(1)
unixdir = os.environ[dirname]
basename = iraffilename[match.end() + 1:] # 1 to omit leading slash
unixfilename = os.path.join(unixdir, basename)
return unixfilename
elif '$' in iraffilename:
# Then it's an iraf-style variable
irafdir, basename = iraffilename.split('$')
if irafdir == 'synphot':
return get_data_filename(os.path.basename(basename))
unixdir = convertdict[irafdir]
unixfilename = os.path.join(unixdir, basename)
return unixfilename
else:
# If no $ sign found, just return the filename unchanged
return iraffilename | [
"def",
"irafconvert",
"(",
"iraffilename",
")",
":",
"convertdict",
"=",
"CONVERTDICT",
"# remove duplicate separators and extraneous relative paths",
"if",
"not",
"iraffilename",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"(",
"'http'",
",",
"'ftp'",
")",
")",... | Convert the IRAF file name to its Unix equivalent.
Input can be in ``directory$file`` or ``$directory/file`` format.
If ``'$'`` is not found in the input string, it is returned as-is.
Parameters
----------
iraffilename : str
Filename in IRAF format.
Returns
-------
unixfilename : str
Filename in Unix format.
Raises
------
AttributeError
Input is not a string. | [
"Convert",
"the",
"IRAF",
"file",
"name",
"to",
"its",
"Unix",
"equivalent",
"."
] | a125ff956f4d94beb157bd51899747a13234bb97 | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/locations.py#L137-L187 | train | 31,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.