repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
IdentityPython/oidcendpoint | src/oidcendpoint/oidc/discovery.py | Discovery.do_response | def do_response(self, response_args=None, request=None, **kwargs):
"""
**Placeholder for the time being**
:param response_args:
:param request:
:param kwargs: request arguments
:return: Response information
"""
links = [Link(href=h, rel=OIC_ISSUER) for h in kwargs['hrefs']]
_response = JRD(subject=kwargs['subject'], links=links)
info = {
'response': _response.to_json(),
'http_headers': [('Content-type', 'application/json')]
}
return info | python | def do_response(self, response_args=None, request=None, **kwargs):
"""
**Placeholder for the time being**
:param response_args:
:param request:
:param kwargs: request arguments
:return: Response information
"""
links = [Link(href=h, rel=OIC_ISSUER) for h in kwargs['hrefs']]
_response = JRD(subject=kwargs['subject'], links=links)
info = {
'response': _response.to_json(),
'http_headers': [('Content-type', 'application/json')]
}
return info | [
"def",
"do_response",
"(",
"self",
",",
"response_args",
"=",
"None",
",",
"request",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"links",
"=",
"[",
"Link",
"(",
"href",
"=",
"h",
",",
"rel",
"=",
"OIC_ISSUER",
")",
"for",
"h",
"in",
"kwargs",
... | **Placeholder for the time being**
:param response_args:
:param request:
:param kwargs: request arguments
:return: Response information | [
"**",
"Placeholder",
"for",
"the",
"time",
"being",
"**"
] | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/oidc/discovery.py#L17-L36 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | get_session | def get_session():
"""Build the session object."""
# NOTE(msimonin): We provide only a basic support which focus
# Chameleon cloud and its rc files
if os.environ.get("OS_IDENTITY_API_VERSION") == "3":
logging.info("Creating a v3 Keystone Session")
auth = v3.Password(
auth_url=os.environ["OS_AUTH_URL"],
username=os.environ["OS_USERNAME"],
password=os.environ["OS_PASSWORD"],
project_id=os.environ["OS_PROJECT_ID"],
user_domain_name=os.environ["OS_USER_DOMAIN_NAME"]
)
else:
logging.info("Creating a v2 Keystone Session")
auth = v2.Password(
auth_url=os.environ["OS_AUTH_URL"],
username=os.environ["OS_USERNAME"],
password=os.environ["OS_PASSWORD"],
tenant_id=os.environ["OS_TENANT_ID"])
return session.Session(auth=auth) | python | def get_session():
"""Build the session object."""
# NOTE(msimonin): We provide only a basic support which focus
# Chameleon cloud and its rc files
if os.environ.get("OS_IDENTITY_API_VERSION") == "3":
logging.info("Creating a v3 Keystone Session")
auth = v3.Password(
auth_url=os.environ["OS_AUTH_URL"],
username=os.environ["OS_USERNAME"],
password=os.environ["OS_PASSWORD"],
project_id=os.environ["OS_PROJECT_ID"],
user_domain_name=os.environ["OS_USER_DOMAIN_NAME"]
)
else:
logging.info("Creating a v2 Keystone Session")
auth = v2.Password(
auth_url=os.environ["OS_AUTH_URL"],
username=os.environ["OS_USERNAME"],
password=os.environ["OS_PASSWORD"],
tenant_id=os.environ["OS_TENANT_ID"])
return session.Session(auth=auth) | [
"def",
"get_session",
"(",
")",
":",
"# NOTE(msimonin): We provide only a basic support which focus",
"# Chameleon cloud and its rc files",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"OS_IDENTITY_API_VERSION\"",
")",
"==",
"\"3\"",
":",
"logging",
".",
"info",
"(",
... | Build the session object. | [
"Build",
"the",
"session",
"object",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L27-L49 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_glance | def check_glance(session, image_name):
"""Check that the base image is available.
Fails if the base image isn't added.
This means the image should be added manually.
"""
gclient = glance.Client(GLANCE_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
images = gclient.images.list()
name_ids = [{'name': i['name'], 'id': i['id']} for i in images]
if image_name not in list(map(itemgetter('name'), name_ids)):
logger.error("[glance]: Image %s is missing" % image_name)
raise Exception("Image %s is missing" % image_name)
else:
image = [i for i in name_ids if i['name'] == image_name]
image_id = image[0]['id']
logger.info("[glance]: Using image %s:%s" % (image_name, image_id))
return image_id | python | def check_glance(session, image_name):
"""Check that the base image is available.
Fails if the base image isn't added.
This means the image should be added manually.
"""
gclient = glance.Client(GLANCE_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
images = gclient.images.list()
name_ids = [{'name': i['name'], 'id': i['id']} for i in images]
if image_name not in list(map(itemgetter('name'), name_ids)):
logger.error("[glance]: Image %s is missing" % image_name)
raise Exception("Image %s is missing" % image_name)
else:
image = [i for i in name_ids if i['name'] == image_name]
image_id = image[0]['id']
logger.info("[glance]: Using image %s:%s" % (image_name, image_id))
return image_id | [
"def",
"check_glance",
"(",
"session",
",",
"image_name",
")",
":",
"gclient",
"=",
"glance",
".",
"Client",
"(",
"GLANCE_VERSION",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
"images",
... | Check that the base image is available.
Fails if the base image isn't added.
This means the image should be added manually. | [
"Check",
"that",
"the",
"base",
"image",
"is",
"available",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L52-L69 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_flavors | def check_flavors(session):
"""Build the flavors mapping
returns the mappings id <-> flavor
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
flavors = nclient.flavors.list()
to_id = dict(list(map(lambda n: [n.name, n.id], flavors)))
to_flavor = dict(list(map(lambda n: [n.id, n.name], flavors)))
return to_id, to_flavor | python | def check_flavors(session):
"""Build the flavors mapping
returns the mappings id <-> flavor
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
flavors = nclient.flavors.list()
to_id = dict(list(map(lambda n: [n.name, n.id], flavors)))
to_flavor = dict(list(map(lambda n: [n.id, n.name], flavors)))
return to_id, to_flavor | [
"def",
"check_flavors",
"(",
"session",
")",
":",
"nclient",
"=",
"nova",
".",
"Client",
"(",
"NOVA_VERSION",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
"flavors",
"=",
"nclient",
".",
... | Build the flavors mapping
returns the mappings id <-> flavor | [
"Build",
"the",
"flavors",
"mapping"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L72-L82 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_network | def check_network(session, configure_network, network, subnet,
dns_nameservers=None, allocation_pool=None):
"""Check the network status for the deployment.
If needed, it creates a dedicated :
* private network /subnet
* router between this network and the external network
"""
nclient = neutron.Client('2', session=session,
region_name=os.environ['OS_REGION_NAME'])
# Check the security groups
secgroups = nclient.list_security_groups()['security_groups']
secgroup_name = SECGROUP_NAME
if secgroup_name not in list(map(itemgetter('name'), secgroups)):
secgroup = {'name': secgroup_name,
'description': 'Enos Security Group'}
res = nclient.create_security_group({'security_group': secgroup})
secgroup = res['security_group']
logger.info("[neutron]: %s security group created" % secgroup_name)
# create the rules
tcp = {'protocol': 'tcp',
'direction': 'ingress',
'port_range_min': '1',
'port_range_max': '65535',
'security_group_id': secgroup['id']}
icmp = {'protocol': 'icmp',
'direction': 'ingress',
'security_group_id': secgroup['id']}
nclient.create_security_group_rule({'security_group_rule': tcp})
logger.info("[neutron]: %s rule (all tcp) created" % secgroup_name)
nclient.create_security_group_rule({'security_group_rule': icmp})
logger.info("[neutron]: %s rule (all icmp) created" % secgroup_name)
else:
logger.info("[neutron]: Reusing security-groups %s " % secgroup_name)
networks = nclient.list_networks()['networks']
network_name = network['name']
if network_name not in list(map(itemgetter('name'), networks)):
network = {'name': network_name}
res = nclient.create_network({'network': network})
network = res['network']
logger.info("[neutron]: %s network created" % network_name)
else:
network = [n for n in networks if n['name'] == network_name][0]
logger.info("[neutron]: Reusing existing %s network", network)
# find ext_net
ext_net = [n for n in networks if n['router:external']]
if len(ext_net) < 1:
raise Exception("No external network found")
ext_net = ext_net[0]
subnets = nclient.list_subnets()['subnets']
subnet_name = subnet['name']
if (subnet_name not in list(map(itemgetter('name'), subnets))
and configure_network):
subnet = {'name': subnet['name'],
'network_id': network['id'],
# NOTE(msimonin): using the dns of chameleon
# for a generic openstack provider we should think to
# parameteried this or use public available dns
'cidr': subnet['cidr'],
'ip_version': 4}
if dns_nameservers is not None:
subnet.update({'dns_nameservers': dns_nameservers})
if allocation_pool is not None:
subnet.update({'allocation_pools': [allocation_pool]})
s = nclient.create_subnet({'subnet': subnet})
logger.debug(s)
subnet = s['subnet']
logger.info("[neutron]: %s subnet created" % subnet_name)
else:
subnet = [s for s in subnets if s['name'] == subnet_name][0]
logger.info("[neutron]: Reusing %s subnet", subnet)
# create a router
routers = nclient.list_routers()
router_name = ROUTER_NAME
logger.debug(routers)
router_present = router_name not in [r['name'] for r in routers['routers']]
if (router_present and configure_network):
router = {
'name': router_name,
'external_gateway_info': {
'network_id': ext_net['id']
}
}
r = nclient.create_router({'router': router})
logger.info("[neutron] %s router created" % router_name)
# NOTE(msimonin): We should check the interface outside this block
# in case the router is created but the interface is not added
interface = {
'subnet_id': subnet['id'].encode('UTF-8')
}
nclient.add_interface_router(str(r['router']['id']), interface)
return (ext_net, network, subnet) | python | def check_network(session, configure_network, network, subnet,
dns_nameservers=None, allocation_pool=None):
"""Check the network status for the deployment.
If needed, it creates a dedicated :
* private network /subnet
* router between this network and the external network
"""
nclient = neutron.Client('2', session=session,
region_name=os.environ['OS_REGION_NAME'])
# Check the security groups
secgroups = nclient.list_security_groups()['security_groups']
secgroup_name = SECGROUP_NAME
if secgroup_name not in list(map(itemgetter('name'), secgroups)):
secgroup = {'name': secgroup_name,
'description': 'Enos Security Group'}
res = nclient.create_security_group({'security_group': secgroup})
secgroup = res['security_group']
logger.info("[neutron]: %s security group created" % secgroup_name)
# create the rules
tcp = {'protocol': 'tcp',
'direction': 'ingress',
'port_range_min': '1',
'port_range_max': '65535',
'security_group_id': secgroup['id']}
icmp = {'protocol': 'icmp',
'direction': 'ingress',
'security_group_id': secgroup['id']}
nclient.create_security_group_rule({'security_group_rule': tcp})
logger.info("[neutron]: %s rule (all tcp) created" % secgroup_name)
nclient.create_security_group_rule({'security_group_rule': icmp})
logger.info("[neutron]: %s rule (all icmp) created" % secgroup_name)
else:
logger.info("[neutron]: Reusing security-groups %s " % secgroup_name)
networks = nclient.list_networks()['networks']
network_name = network['name']
if network_name not in list(map(itemgetter('name'), networks)):
network = {'name': network_name}
res = nclient.create_network({'network': network})
network = res['network']
logger.info("[neutron]: %s network created" % network_name)
else:
network = [n for n in networks if n['name'] == network_name][0]
logger.info("[neutron]: Reusing existing %s network", network)
# find ext_net
ext_net = [n for n in networks if n['router:external']]
if len(ext_net) < 1:
raise Exception("No external network found")
ext_net = ext_net[0]
subnets = nclient.list_subnets()['subnets']
subnet_name = subnet['name']
if (subnet_name not in list(map(itemgetter('name'), subnets))
and configure_network):
subnet = {'name': subnet['name'],
'network_id': network['id'],
# NOTE(msimonin): using the dns of chameleon
# for a generic openstack provider we should think to
# parameteried this or use public available dns
'cidr': subnet['cidr'],
'ip_version': 4}
if dns_nameservers is not None:
subnet.update({'dns_nameservers': dns_nameservers})
if allocation_pool is not None:
subnet.update({'allocation_pools': [allocation_pool]})
s = nclient.create_subnet({'subnet': subnet})
logger.debug(s)
subnet = s['subnet']
logger.info("[neutron]: %s subnet created" % subnet_name)
else:
subnet = [s for s in subnets if s['name'] == subnet_name][0]
logger.info("[neutron]: Reusing %s subnet", subnet)
# create a router
routers = nclient.list_routers()
router_name = ROUTER_NAME
logger.debug(routers)
router_present = router_name not in [r['name'] for r in routers['routers']]
if (router_present and configure_network):
router = {
'name': router_name,
'external_gateway_info': {
'network_id': ext_net['id']
}
}
r = nclient.create_router({'router': router})
logger.info("[neutron] %s router created" % router_name)
# NOTE(msimonin): We should check the interface outside this block
# in case the router is created but the interface is not added
interface = {
'subnet_id': subnet['id'].encode('UTF-8')
}
nclient.add_interface_router(str(r['router']['id']), interface)
return (ext_net, network, subnet) | [
"def",
"check_network",
"(",
"session",
",",
"configure_network",
",",
"network",
",",
"subnet",
",",
"dns_nameservers",
"=",
"None",
",",
"allocation_pool",
"=",
"None",
")",
":",
"nclient",
"=",
"neutron",
".",
"Client",
"(",
"'2'",
",",
"session",
"=",
... | Check the network status for the deployment.
If needed, it creates a dedicated :
* private network /subnet
* router between this network and the external network | [
"Check",
"the",
"network",
"status",
"for",
"the",
"deployment",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L85-L183 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | wait_for_servers | def wait_for_servers(session, servers):
"""Wait for the servers to be ready.
Note(msimonin): we don't garantee the SSH connection to be ready.
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
while True:
deployed = []
undeployed = []
for server in servers:
c = nclient.servers.get(server.id)
if c.addresses != {} and c.status == 'ACTIVE':
deployed.append(server)
if c.status == 'ERROR':
undeployed.append(server)
logger.info("[nova]: Polling the Deployment")
logger.info("[nova]: %s deployed servers" % len(deployed))
logger.info("[nova]: %s undeployed servers" % len(undeployed))
if len(deployed) + len(undeployed) >= len(servers):
break
time.sleep(3)
return deployed, undeployed | python | def wait_for_servers(session, servers):
"""Wait for the servers to be ready.
Note(msimonin): we don't garantee the SSH connection to be ready.
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
while True:
deployed = []
undeployed = []
for server in servers:
c = nclient.servers.get(server.id)
if c.addresses != {} and c.status == 'ACTIVE':
deployed.append(server)
if c.status == 'ERROR':
undeployed.append(server)
logger.info("[nova]: Polling the Deployment")
logger.info("[nova]: %s deployed servers" % len(deployed))
logger.info("[nova]: %s undeployed servers" % len(undeployed))
if len(deployed) + len(undeployed) >= len(servers):
break
time.sleep(3)
return deployed, undeployed | [
"def",
"wait_for_servers",
"(",
"session",
",",
"servers",
")",
":",
"nclient",
"=",
"nova",
".",
"Client",
"(",
"NOVA_VERSION",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
"while",
"Tru... | Wait for the servers to be ready.
Note(msimonin): we don't garantee the SSH connection to be ready. | [
"Wait",
"for",
"the",
"servers",
"to",
"be",
"ready",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L208-L230 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_servers | def check_servers(session, machines, extra_prefix="",
force_deploy=False, key_name=None, image_id=None,
flavors='m1.medium', network=None, ext_net=None,
scheduler_hints=None):
"""Checks the servers status for the deployment.
If needed, it creates new servers and add a floating ip to one of them.
This server can be used as a gateway to the others.
"""
scheduler_hints = scheduler_hints or []
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
servers = nclient.servers.list(
search_opts={'name': '-'.join([DEFAULT_PREFIX, extra_prefix])})
wanted = _get_total_wanted_machines(machines)
if force_deploy:
for server in servers:
server.delete()
servers = []
if len(servers) == wanted:
logger.info("[nova]: Reusing existing servers : %s", servers)
return servers
elif len(servers) > 0 and len(servers) < wanted:
raise Exception("Only %s/%s servers found" % (servers, wanted))
# starting the servers
total = 0
for machine in machines:
number = machine.number
roles = machine.roles
logger.info("[nova]: Starting %s servers" % number)
logger.info("[nova]: for roles %s" % roles)
logger.info("[nova]: with extra hints %s" % scheduler_hints)
for _ in range(number):
flavor = machine.flavour
if isinstance(flavors, str):
flavor = flavors
else:
flavor_to_id, _ = flavors
flavor = flavor_to_id[flavor]
if scheduler_hints:
_scheduler_hints = \
scheduler_hints[total % len(scheduler_hints)]
else:
_scheduler_hints = []
server = nclient.servers.create(
name='-'.join([DEFAULT_PREFIX, extra_prefix, str(total)]),
image=image_id,
flavor=flavor,
nics=[{'net-id': network['id']}],
key_name=key_name,
security_groups=[SECGROUP_NAME],
scheduler_hints=_scheduler_hints)
servers.append(server)
total = total + 1
return servers | python | def check_servers(session, machines, extra_prefix="",
force_deploy=False, key_name=None, image_id=None,
flavors='m1.medium', network=None, ext_net=None,
scheduler_hints=None):
"""Checks the servers status for the deployment.
If needed, it creates new servers and add a floating ip to one of them.
This server can be used as a gateway to the others.
"""
scheduler_hints = scheduler_hints or []
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
servers = nclient.servers.list(
search_opts={'name': '-'.join([DEFAULT_PREFIX, extra_prefix])})
wanted = _get_total_wanted_machines(machines)
if force_deploy:
for server in servers:
server.delete()
servers = []
if len(servers) == wanted:
logger.info("[nova]: Reusing existing servers : %s", servers)
return servers
elif len(servers) > 0 and len(servers) < wanted:
raise Exception("Only %s/%s servers found" % (servers, wanted))
# starting the servers
total = 0
for machine in machines:
number = machine.number
roles = machine.roles
logger.info("[nova]: Starting %s servers" % number)
logger.info("[nova]: for roles %s" % roles)
logger.info("[nova]: with extra hints %s" % scheduler_hints)
for _ in range(number):
flavor = machine.flavour
if isinstance(flavors, str):
flavor = flavors
else:
flavor_to_id, _ = flavors
flavor = flavor_to_id[flavor]
if scheduler_hints:
_scheduler_hints = \
scheduler_hints[total % len(scheduler_hints)]
else:
_scheduler_hints = []
server = nclient.servers.create(
name='-'.join([DEFAULT_PREFIX, extra_prefix, str(total)]),
image=image_id,
flavor=flavor,
nics=[{'net-id': network['id']}],
key_name=key_name,
security_groups=[SECGROUP_NAME],
scheduler_hints=_scheduler_hints)
servers.append(server)
total = total + 1
return servers | [
"def",
"check_servers",
"(",
"session",
",",
"machines",
",",
"extra_prefix",
"=",
"\"\"",
",",
"force_deploy",
"=",
"False",
",",
"key_name",
"=",
"None",
",",
"image_id",
"=",
"None",
",",
"flavors",
"=",
"'m1.medium'",
",",
"network",
"=",
"None",
",",
... | Checks the servers status for the deployment.
If needed, it creates new servers and add a floating ip to one of them.
This server can be used as a gateway to the others. | [
"Checks",
"the",
"servers",
"status",
"for",
"the",
"deployment",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L238-L297 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | is_in_current_deployment | def is_in_current_deployment(server, extra_prefix=""):
"""Check if an existing server in the system take part to
the current deployment
"""
return re.match(r"^%s" % '-'.join([DEFAULT_PREFIX, extra_prefix]),
server.name) is not None | python | def is_in_current_deployment(server, extra_prefix=""):
"""Check if an existing server in the system take part to
the current deployment
"""
return re.match(r"^%s" % '-'.join([DEFAULT_PREFIX, extra_prefix]),
server.name) is not None | [
"def",
"is_in_current_deployment",
"(",
"server",
",",
"extra_prefix",
"=",
"\"\"",
")",
":",
"return",
"re",
".",
"match",
"(",
"r\"^%s\"",
"%",
"'-'",
".",
"join",
"(",
"[",
"DEFAULT_PREFIX",
",",
"extra_prefix",
"]",
")",
",",
"server",
".",
"name",
"... | Check if an existing server in the system take part to
the current deployment | [
"Check",
"if",
"an",
"existing",
"server",
"in",
"the",
"system",
"take",
"part",
"to",
"the",
"current",
"deployment"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L321-L326 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | allow_address_pairs | def allow_address_pairs(session, network, subnet):
"""Allow several interfaces to be added and accessed from the other machines.
This is particularly useful when working with virtual ips.
"""
nclient = neutron.Client('2', session=session,
region_name=os.environ['OS_REGION_NAME'])
ports = nclient.list_ports()
ports_to_update = filter(
lambda p: p['network_id'] == network['id'],
ports['ports'])
logger.info('[nova]: Allowing address pairs for ports %s' %
list(map(lambda p: p['fixed_ips'], ports_to_update)))
for port in ports_to_update:
try:
nclient.update_port(port['id'], {
'port': {
'allowed_address_pairs': [{
'ip_address': subnet
}]
}
})
except Exception:
# NOTE(msimonin): dhcp and router interface port
# seems to have enabled_sec_groups = False which
# prevent them to be updated, just throw a warning
# a skip them
logger.warn("Can't update port %s" % port) | python | def allow_address_pairs(session, network, subnet):
"""Allow several interfaces to be added and accessed from the other machines.
This is particularly useful when working with virtual ips.
"""
nclient = neutron.Client('2', session=session,
region_name=os.environ['OS_REGION_NAME'])
ports = nclient.list_ports()
ports_to_update = filter(
lambda p: p['network_id'] == network['id'],
ports['ports'])
logger.info('[nova]: Allowing address pairs for ports %s' %
list(map(lambda p: p['fixed_ips'], ports_to_update)))
for port in ports_to_update:
try:
nclient.update_port(port['id'], {
'port': {
'allowed_address_pairs': [{
'ip_address': subnet
}]
}
})
except Exception:
# NOTE(msimonin): dhcp and router interface port
# seems to have enabled_sec_groups = False which
# prevent them to be updated, just throw a warning
# a skip them
logger.warn("Can't update port %s" % port) | [
"def",
"allow_address_pairs",
"(",
"session",
",",
"network",
",",
"subnet",
")",
":",
"nclient",
"=",
"neutron",
".",
"Client",
"(",
"'2'",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
... | Allow several interfaces to be added and accessed from the other machines.
This is particularly useful when working with virtual ips. | [
"Allow",
"several",
"interfaces",
"to",
"be",
"added",
"and",
"accessed",
"from",
"the",
"other",
"machines",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L329-L356 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_environment | def check_environment(provider_conf):
"""Check all ressources needed by Enos."""
session = get_session()
image_id = check_glance(session, provider_conf.image)
flavor_to_id, id_to_flavor = check_flavors(session)
ext_net, network, subnet = check_network(
session,
provider_conf.configure_network,
provider_conf.network,
subnet=provider_conf.subnet,
dns_nameservers=provider_conf.dns_nameservers,
allocation_pool=provider_conf.allocation_pool)
return {
'session': session,
'image_id': image_id,
'flavor_to_id': flavor_to_id,
'id_to_flavor': id_to_flavor,
'ext_net': ext_net,
'network': network,
'subnet': subnet
} | python | def check_environment(provider_conf):
"""Check all ressources needed by Enos."""
session = get_session()
image_id = check_glance(session, provider_conf.image)
flavor_to_id, id_to_flavor = check_flavors(session)
ext_net, network, subnet = check_network(
session,
provider_conf.configure_network,
provider_conf.network,
subnet=provider_conf.subnet,
dns_nameservers=provider_conf.dns_nameservers,
allocation_pool=provider_conf.allocation_pool)
return {
'session': session,
'image_id': image_id,
'flavor_to_id': flavor_to_id,
'id_to_flavor': id_to_flavor,
'ext_net': ext_net,
'network': network,
'subnet': subnet
} | [
"def",
"check_environment",
"(",
"provider_conf",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"image_id",
"=",
"check_glance",
"(",
"session",
",",
"provider_conf",
".",
"image",
")",
"flavor_to_id",
",",
"id_to_flavor",
"=",
"check_flavors",
"(",
"sessio... | Check all ressources needed by Enos. | [
"Check",
"all",
"ressources",
"needed",
"by",
"Enos",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L359-L380 |
IdentityPython/oidcendpoint | src/oidcendpoint/userinfo.py | claims_match | def claims_match(value, claimspec):
"""
Implements matching according to section 5.5.1 of
http://openid.net/specs/openid-connect-core-1_0.html
The lack of value is not checked here.
Also the text doesn't prohibit having both 'value' and 'values'.
:param value: single value
:param claimspec: None or dictionary with 'essential', 'value' or 'values'
as key
:return: Boolean
"""
if claimspec is None: # match anything
return True
matched = False
for key, val in claimspec.items():
if key == "value":
if value == val:
matched = True
elif key == "values":
if value in val:
matched = True
elif key == 'essential':
# Whether it's essential or not doesn't change anything here
continue
if matched:
break
if matched is False:
if list(claimspec.keys()) == ['essential']:
return True
return matched | python | def claims_match(value, claimspec):
"""
Implements matching according to section 5.5.1 of
http://openid.net/specs/openid-connect-core-1_0.html
The lack of value is not checked here.
Also the text doesn't prohibit having both 'value' and 'values'.
:param value: single value
:param claimspec: None or dictionary with 'essential', 'value' or 'values'
as key
:return: Boolean
"""
if claimspec is None: # match anything
return True
matched = False
for key, val in claimspec.items():
if key == "value":
if value == val:
matched = True
elif key == "values":
if value in val:
matched = True
elif key == 'essential':
# Whether it's essential or not doesn't change anything here
continue
if matched:
break
if matched is False:
if list(claimspec.keys()) == ['essential']:
return True
return matched | [
"def",
"claims_match",
"(",
"value",
",",
"claimspec",
")",
":",
"if",
"claimspec",
"is",
"None",
":",
"# match anything",
"return",
"True",
"matched",
"=",
"False",
"for",
"key",
",",
"val",
"in",
"claimspec",
".",
"items",
"(",
")",
":",
"if",
"key",
... | Implements matching according to section 5.5.1 of
http://openid.net/specs/openid-connect-core-1_0.html
The lack of value is not checked here.
Also the text doesn't prohibit having both 'value' and 'values'.
:param value: single value
:param claimspec: None or dictionary with 'essential', 'value' or 'values'
as key
:return: Boolean | [
"Implements",
"matching",
"according",
"to",
"section",
"5",
".",
"5",
".",
"1",
"of",
"http",
":",
"//",
"openid",
".",
"net",
"/",
"specs",
"/",
"openid",
"-",
"connect",
"-",
"core",
"-",
"1_0",
".",
"html",
"The",
"lack",
"of",
"value",
"is",
"... | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/userinfo.py#L57-L91 |
IdentityPython/oidcendpoint | src/oidcendpoint/userinfo.py | collect_user_info | def collect_user_info(endpoint_context, session, userinfo_claims=None):
"""
Collect information about a user.
This can happen in two cases, either when constructing an IdToken or
when returning user info through the UserInfo endpoint
:param session: Session information
:param userinfo_claims: user info claims
:return: User info
"""
authn_req = session['authn_req']
if userinfo_claims is None:
uic = scope2claims(authn_req["scope"])
# Get only keys allowed by user and update the dict if such info
# is stored in session
perm_set = session.get('permission')
if perm_set:
uic = {key: uic[key] for key in uic if key in perm_set}
uic = update_claims(session, "userinfo", uic)
if uic:
userinfo_claims = Claims(**uic)
else:
userinfo_claims = None
logger.debug(
"userinfo_claim: %s" % sanitize(userinfo_claims.to_dict()))
logger.debug("Session info: %s" % sanitize(session))
authn_event = session['authn_event']
if authn_event:
uid = authn_event["uid"]
else:
uid = session['uid']
info = endpoint_context.userinfo(uid, authn_req['client_id'],
userinfo_claims)
if "sub" in userinfo_claims:
if not claims_match(session["sub"], userinfo_claims["sub"]):
raise FailedAuthentication("Unmatched sub claim")
info["sub"] = session["sub"]
try:
logger.debug("user_info_response: {}".format(info))
except UnicodeEncodeError:
try:
logger.debug(
"user_info_response: {}".format(info.encode('utf-8')))
except Exception:
pass
return info | python | def collect_user_info(endpoint_context, session, userinfo_claims=None):
"""
Collect information about a user.
This can happen in two cases, either when constructing an IdToken or
when returning user info through the UserInfo endpoint
:param session: Session information
:param userinfo_claims: user info claims
:return: User info
"""
authn_req = session['authn_req']
if userinfo_claims is None:
uic = scope2claims(authn_req["scope"])
# Get only keys allowed by user and update the dict if such info
# is stored in session
perm_set = session.get('permission')
if perm_set:
uic = {key: uic[key] for key in uic if key in perm_set}
uic = update_claims(session, "userinfo", uic)
if uic:
userinfo_claims = Claims(**uic)
else:
userinfo_claims = None
logger.debug(
"userinfo_claim: %s" % sanitize(userinfo_claims.to_dict()))
logger.debug("Session info: %s" % sanitize(session))
authn_event = session['authn_event']
if authn_event:
uid = authn_event["uid"]
else:
uid = session['uid']
info = endpoint_context.userinfo(uid, authn_req['client_id'],
userinfo_claims)
if "sub" in userinfo_claims:
if not claims_match(session["sub"], userinfo_claims["sub"]):
raise FailedAuthentication("Unmatched sub claim")
info["sub"] = session["sub"]
try:
logger.debug("user_info_response: {}".format(info))
except UnicodeEncodeError:
try:
logger.debug(
"user_info_response: {}".format(info.encode('utf-8')))
except Exception:
pass
return info | [
"def",
"collect_user_info",
"(",
"endpoint_context",
",",
"session",
",",
"userinfo_claims",
"=",
"None",
")",
":",
"authn_req",
"=",
"session",
"[",
"'authn_req'",
"]",
"if",
"userinfo_claims",
"is",
"None",
":",
"uic",
"=",
"scope2claims",
"(",
"authn_req",
... | Collect information about a user.
This can happen in two cases, either when constructing an IdToken or
when returning user info through the UserInfo endpoint
:param session: Session information
:param userinfo_claims: user info claims
:return: User info | [
"Collect",
"information",
"about",
"a",
"user",
".",
"This",
"can",
"happen",
"in",
"two",
"cases",
"either",
"when",
"constructing",
"an",
"IdToken",
"or",
"when",
"returning",
"user",
"info",
"through",
"the",
"UserInfo",
"endpoint"
] | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/userinfo.py#L105-L161 |
IdentityPython/oidcendpoint | src/oidcendpoint/userinfo.py | userinfo_in_id_token_claims | def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None):
"""
Collect user info claims that are to be placed in the id token.
:param endpoint_context: Endpoint context
:param session: Session information
:param def_itc: Default ID Token claims
:return: User information or None
"""
if def_itc:
itc = def_itc
else:
itc = {}
itc.update(id_token_claims(session))
if not itc:
return None
_claims = by_schema(endpoint_context.id_token_schema, **itc)
if _claims:
return collect_user_info(endpoint_context, session, _claims)
else:
return None | python | def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None):
"""
Collect user info claims that are to be placed in the id token.
:param endpoint_context: Endpoint context
:param session: Session information
:param def_itc: Default ID Token claims
:return: User information or None
"""
if def_itc:
itc = def_itc
else:
itc = {}
itc.update(id_token_claims(session))
if not itc:
return None
_claims = by_schema(endpoint_context.id_token_schema, **itc)
if _claims:
return collect_user_info(endpoint_context, session, _claims)
else:
return None | [
"def",
"userinfo_in_id_token_claims",
"(",
"endpoint_context",
",",
"session",
",",
"def_itc",
"=",
"None",
")",
":",
"if",
"def_itc",
":",
"itc",
"=",
"def_itc",
"else",
":",
"itc",
"=",
"{",
"}",
"itc",
".",
"update",
"(",
"id_token_claims",
"(",
"sessio... | Collect user info claims that are to be placed in the id token.
:param endpoint_context: Endpoint context
:param session: Session information
:param def_itc: Default ID Token claims
:return: User information or None | [
"Collect",
"user",
"info",
"claims",
"that",
"are",
"to",
"be",
"placed",
"in",
"the",
"id",
"token",
"."
] | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/userinfo.py#L164-L188 |
thombashi/tabledata | tabledata/_core.py | TableData.value_matrix | def value_matrix(self):
"""Converted rows of tabular data.
Returns:
|list| or |tuple|: Table rows.
"""
if self.__value_matrix:
return self.__value_matrix
self.__value_matrix = [
[value_dp.data for value_dp in value_dp_list] for value_dp_list in self.value_dp_matrix
]
return self.__value_matrix | python | def value_matrix(self):
"""Converted rows of tabular data.
Returns:
|list| or |tuple|: Table rows.
"""
if self.__value_matrix:
return self.__value_matrix
self.__value_matrix = [
[value_dp.data for value_dp in value_dp_list] for value_dp_list in self.value_dp_matrix
]
return self.__value_matrix | [
"def",
"value_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"__value_matrix",
":",
"return",
"self",
".",
"__value_matrix",
"self",
".",
"__value_matrix",
"=",
"[",
"[",
"value_dp",
".",
"data",
"for",
"value_dp",
"in",
"value_dp_list",
"]",
"for",
"v... | Converted rows of tabular data.
Returns:
|list| or |tuple|: Table rows. | [
"Converted",
"rows",
"of",
"tabular",
"data",
"."
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L79-L93 |
thombashi/tabledata | tabledata/_core.py | TableData.value_dp_matrix | def value_dp_matrix(self):
"""
:return: DataProperty for table data.
:rtype: list
"""
if self.__value_dp_matrix is None:
self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix(
to_value_matrix(self.headers, self.rows)
)
return self.__value_dp_matrix | python | def value_dp_matrix(self):
"""
:return: DataProperty for table data.
:rtype: list
"""
if self.__value_dp_matrix is None:
self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix(
to_value_matrix(self.headers, self.rows)
)
return self.__value_dp_matrix | [
"def",
"value_dp_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"__value_dp_matrix",
"is",
"None",
":",
"self",
".",
"__value_dp_matrix",
"=",
"self",
".",
"__dp_extractor",
".",
"to_dp_matrix",
"(",
"to_value_matrix",
"(",
"self",
".",
"headers",
",",
"... | :return: DataProperty for table data.
:rtype: list | [
":",
"return",
":",
"DataProperty",
"for",
"table",
"data",
".",
":",
"rtype",
":",
"list"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L126-L137 |
thombashi/tabledata | tabledata/_core.py | TableData.validate_rows | def validate_rows(self):
"""
:raises ValueError:
"""
invalid_row_idx_list = []
for row_idx, row in enumerate(self.rows):
if isinstance(row, (list, tuple)) and len(self.headers) != len(row):
invalid_row_idx_list.append(row_idx)
if isinstance(row, dict):
if not all([header in row for header in self.headers]):
invalid_row_idx_list.append(row_idx)
if not invalid_row_idx_list:
return
for invalid_row_idx in invalid_row_idx_list:
logger.debug(
"invalid row (line={}): {}".format(invalid_row_idx, self.rows[invalid_row_idx])
)
raise ValueError(
"table header length and row length are mismatch:\n"
+ " header(len={}): {}\n".format(len(self.headers), self.headers)
+ " # of miss match rows: {} ouf of {}\n".format(
len(invalid_row_idx_list), self.num_rows
)
) | python | def validate_rows(self):
"""
:raises ValueError:
"""
invalid_row_idx_list = []
for row_idx, row in enumerate(self.rows):
if isinstance(row, (list, tuple)) and len(self.headers) != len(row):
invalid_row_idx_list.append(row_idx)
if isinstance(row, dict):
if not all([header in row for header in self.headers]):
invalid_row_idx_list.append(row_idx)
if not invalid_row_idx_list:
return
for invalid_row_idx in invalid_row_idx_list:
logger.debug(
"invalid row (line={}): {}".format(invalid_row_idx, self.rows[invalid_row_idx])
)
raise ValueError(
"table header length and row length are mismatch:\n"
+ " header(len={}): {}\n".format(len(self.headers), self.headers)
+ " # of miss match rows: {} ouf of {}\n".format(
len(invalid_row_idx_list), self.num_rows
)
) | [
"def",
"validate_rows",
"(",
"self",
")",
":",
"invalid_row_idx_list",
"=",
"[",
"]",
"for",
"row_idx",
",",
"row",
"in",
"enumerate",
"(",
"self",
".",
"rows",
")",
":",
"if",
"isinstance",
"(",
"row",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and"... | :raises ValueError: | [
":",
"raises",
"ValueError",
":"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L288-L317 |
thombashi/tabledata | tabledata/_core.py | TableData.as_dict | def as_dict(self):
"""
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_dict()
:Output:
.. code:: json
{'sample': [OrderedDict([('a', 1), ('b', 2)]), OrderedDict([('a', 3.3), ('b', 4.4)])]}
"""
dict_body = []
for row in self.rows:
if not row:
continue
values = [
(header, value) for header, value in zip(self.headers, row) if value is not None
]
if not values:
continue
dict_body.append(OrderedDict(values))
return {self.table_name: dict_body} | python | def as_dict(self):
"""
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_dict()
:Output:
.. code:: json
{'sample': [OrderedDict([('a', 1), ('b', 2)]), OrderedDict([('a', 3.3), ('b', 4.4)])]}
"""
dict_body = []
for row in self.rows:
if not row:
continue
values = [
(header, value) for header, value in zip(self.headers, row) if value is not None
]
if not values:
continue
dict_body.append(OrderedDict(values))
return {self.table_name: dict_body} | [
"def",
"as_dict",
"(",
"self",
")",
":",
"dict_body",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"if",
"not",
"row",
":",
"continue",
"values",
"=",
"[",
"(",
"header",
",",
"value",
")",
"for",
"header",
",",
"value",
"in",
"zi... | :return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_dict()
:Output:
.. code:: json
{'sample': [OrderedDict([('a', 1), ('b', 2)]), OrderedDict([('a', 3.3), ('b', 4.4)])]} | [
":",
"return",
":",
"Table",
"data",
"as",
"a",
"|dict|",
"instance",
".",
":",
"rtype",
":",
"dict"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L319-L355 |
thombashi/tabledata | tabledata/_core.py | TableData.as_tuple | def as_tuple(self):
"""
:return: Rows of the table.
:rtype: list of |namedtuple|
:Sample Code:
.. code:: python
from tabledata import TableData
records = TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_tuple()
for record in records:
print(record)
:Output:
.. code-block:: none
Row(a=1, b=2)
Row(a=Decimal('3.3'), b=Decimal('4.4'))
"""
Row = namedtuple("Row", self.headers)
for value_dp_list in self.value_dp_matrix:
if typepy.is_empty_sequence(value_dp_list):
continue
row = Row(*[value_dp.data for value_dp in value_dp_list])
yield row | python | def as_tuple(self):
"""
:return: Rows of the table.
:rtype: list of |namedtuple|
:Sample Code:
.. code:: python
from tabledata import TableData
records = TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_tuple()
for record in records:
print(record)
:Output:
.. code-block:: none
Row(a=1, b=2)
Row(a=Decimal('3.3'), b=Decimal('4.4'))
"""
Row = namedtuple("Row", self.headers)
for value_dp_list in self.value_dp_matrix:
if typepy.is_empty_sequence(value_dp_list):
continue
row = Row(*[value_dp.data for value_dp in value_dp_list])
yield row | [
"def",
"as_tuple",
"(",
"self",
")",
":",
"Row",
"=",
"namedtuple",
"(",
"\"Row\"",
",",
"self",
".",
"headers",
")",
"for",
"value_dp_list",
"in",
"self",
".",
"value_dp_matrix",
":",
"if",
"typepy",
".",
"is_empty_sequence",
"(",
"value_dp_list",
")",
":... | :return: Rows of the table.
:rtype: list of |namedtuple|
:Sample Code:
.. code:: python
from tabledata import TableData
records = TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_tuple()
for record in records:
print(record)
:Output:
.. code-block:: none
Row(a=1, b=2)
Row(a=Decimal('3.3'), b=Decimal('4.4')) | [
":",
"return",
":",
"Rows",
"of",
"the",
"table",
".",
":",
"rtype",
":",
"list",
"of",
"|namedtuple|"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L357-L390 |
thombashi/tabledata | tabledata/_core.py | TableData.as_dataframe | def as_dataframe(self):
"""
:return: Table data as a ``pandas.DataFrame`` instance.
:rtype: pandas.DataFrame
:Sample Code:
.. code-block:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_dataframe()
:Output:
.. code-block:: none
a b
0 1 2
1 3.3 4.4
:Dependency Packages:
- `pandas <https://pandas.pydata.org/>`__
"""
import pandas
dataframe = pandas.DataFrame(self.value_matrix)
if not self.is_empty_header():
dataframe.columns = self.headers
return dataframe | python | def as_dataframe(self):
"""
:return: Table data as a ``pandas.DataFrame`` instance.
:rtype: pandas.DataFrame
:Sample Code:
.. code-block:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_dataframe()
:Output:
.. code-block:: none
a b
0 1 2
1 3.3 4.4
:Dependency Packages:
- `pandas <https://pandas.pydata.org/>`__
"""
import pandas
dataframe = pandas.DataFrame(self.value_matrix)
if not self.is_empty_header():
dataframe.columns = self.headers
return dataframe | [
"def",
"as_dataframe",
"(",
"self",
")",
":",
"import",
"pandas",
"dataframe",
"=",
"pandas",
".",
"DataFrame",
"(",
"self",
".",
"value_matrix",
")",
"if",
"not",
"self",
".",
"is_empty_header",
"(",
")",
":",
"dataframe",
".",
"columns",
"=",
"self",
"... | :return: Table data as a ``pandas.DataFrame`` instance.
:rtype: pandas.DataFrame
:Sample Code:
.. code-block:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_dataframe()
:Output:
.. code-block:: none
a b
0 1 2
1 3.3 4.4
:Dependency Packages:
- `pandas <https://pandas.pydata.org/>`__ | [
":",
"return",
":",
"Table",
"data",
"as",
"a",
"pandas",
".",
"DataFrame",
"instance",
".",
":",
"rtype",
":",
"pandas",
".",
"DataFrame"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L392-L425 |
thombashi/tabledata | tabledata/_core.py | TableData.from_dataframe | def from_dataframe(dataframe, table_name=""):
"""
Initialize TableData instance from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe:
:param str table_name: Table name to create.
"""
return TableData(table_name, list(dataframe.columns.values), dataframe.values.tolist()) | python | def from_dataframe(dataframe, table_name=""):
"""
Initialize TableData instance from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe:
:param str table_name: Table name to create.
"""
return TableData(table_name, list(dataframe.columns.values), dataframe.values.tolist()) | [
"def",
"from_dataframe",
"(",
"dataframe",
",",
"table_name",
"=",
"\"\"",
")",
":",
"return",
"TableData",
"(",
"table_name",
",",
"list",
"(",
"dataframe",
".",
"columns",
".",
"values",
")",
",",
"dataframe",
".",
"values",
".",
"tolist",
"(",
")",
")... | Initialize TableData instance from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe:
:param str table_name: Table name to create. | [
"Initialize",
"TableData",
"instance",
"from",
"a",
"pandas",
".",
"DataFrame",
"instance",
"."
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L475-L483 |
volafiled/python-volapi | volapi/auxo.py | call_async | def call_async(func):
"""Decorates a function to be called async on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
def call():
"""Calls function on loop thread"""
try:
func(self, *args, **kw)
except Exception:
logger.exception(
"failed to call async [%r] with [%r] [%r]", func, args, kw
)
self.loop.call_soon_threadsafe(call)
return wrapper | python | def call_async(func):
"""Decorates a function to be called async on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
def call():
"""Calls function on loop thread"""
try:
func(self, *args, **kw)
except Exception:
logger.exception(
"failed to call async [%r] with [%r] [%r]", func, args, kw
)
self.loop.call_soon_threadsafe(call)
return wrapper | [
"def",
"call_async",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"Wraps instance method to be called on loop thread\"\"\"",
"def",
"call",
"(",
")",
":",
"\"\"... | Decorates a function to be called async on the loop thread | [
"Decorates",
"a",
"function",
"to",
"be",
"called",
"async",
"on",
"the",
"loop",
"thread"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L33-L51 |
volafiled/python-volapi | volapi/auxo.py | call_sync | def call_sync(func):
"""Decorates a function to be called sync on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
# Just return when already on the event thread
if self.thread.ident == get_ident():
return func(self, *args, **kw)
barrier = Barrier(2)
result = None
ex = None
def call():
"""Calls function on loop thread"""
nonlocal result, ex
try:
result = func(self, *args, **kw)
except Exception as exc:
ex = exc
finally:
barrier.wait()
self.loop.call_soon_threadsafe(call)
barrier.wait()
if ex:
raise ex or Exception("Unknown error")
return result
return wrapper | python | def call_sync(func):
"""Decorates a function to be called sync on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
# Just return when already on the event thread
if self.thread.ident == get_ident():
return func(self, *args, **kw)
barrier = Barrier(2)
result = None
ex = None
def call():
"""Calls function on loop thread"""
nonlocal result, ex
try:
result = func(self, *args, **kw)
except Exception as exc:
ex = exc
finally:
barrier.wait()
self.loop.call_soon_threadsafe(call)
barrier.wait()
if ex:
raise ex or Exception("Unknown error")
return result
return wrapper | [
"def",
"call_sync",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"Wraps instance method to be called on loop thread\"\"\"",
"# Just return when already on the event threa... | Decorates a function to be called sync on the loop thread | [
"Decorates",
"a",
"function",
"to",
"be",
"called",
"sync",
"on",
"the",
"loop",
"thread"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L54-L85 |
volafiled/python-volapi | volapi/auxo.py | Awakener.target | def target(self):
"""Thread routine"""
while self.event.wait():
self.event.clear()
while True:
with self.lock:
if not self.count:
break
self.count -= 1
with self.condition:
self.condition.notify_all() | python | def target(self):
"""Thread routine"""
while self.event.wait():
self.event.clear()
while True:
with self.lock:
if not self.count:
break
self.count -= 1
with self.condition:
self.condition.notify_all() | [
"def",
"target",
"(",
"self",
")",
":",
"while",
"self",
".",
"event",
".",
"wait",
"(",
")",
":",
"self",
".",
"event",
".",
"clear",
"(",
")",
"while",
"True",
":",
"with",
"self",
".",
"lock",
":",
"if",
"not",
"self",
".",
"count",
":",
"br... | Thread routine | [
"Thread",
"routine"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L113-L123 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator._loop | def _loop(self, barrier):
"""Actual thread"""
if sys.platform != "win32":
self.loop = asyncio.new_event_loop()
else:
self.loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(self.loop)
barrier.wait()
try:
self.loop.run_forever()
except Exception:
sys.exit(1) | python | def _loop(self, barrier):
"""Actual thread"""
if sys.platform != "win32":
self.loop = asyncio.new_event_loop()
else:
self.loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(self.loop)
barrier.wait()
try:
self.loop.run_forever()
except Exception:
sys.exit(1) | [
"def",
"_loop",
"(",
"self",
",",
"barrier",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"\"win32\"",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"new_event_loop",
"(",
")",
"else",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"ProactorEventLoop... | Actual thread | [
"Actual",
"thread"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L138-L150 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator.create_connection | def create_connection(self, room, ws_url, agent, cookies):
"""Creates a new connection"""
urlparts = urlsplit(ws_url)
req = Request("GET", ws_url)
cookies = get_cookie_header(cookies, req)
if cookies:
headers = dict(Cookie=cookies)
else:
headers = None
factory = WebSocketClientFactory(ws_url, headers=headers, loop=self.loop)
factory.useragent = agent
factory.protocol = lambda: room
conn = self.loop.create_connection(
factory,
host=urlparts.netloc,
port=urlparts.port or 443,
ssl=urlparts.scheme == "wss",
)
asyncio.ensure_future(conn, loop=self.loop) | python | def create_connection(self, room, ws_url, agent, cookies):
"""Creates a new connection"""
urlparts = urlsplit(ws_url)
req = Request("GET", ws_url)
cookies = get_cookie_header(cookies, req)
if cookies:
headers = dict(Cookie=cookies)
else:
headers = None
factory = WebSocketClientFactory(ws_url, headers=headers, loop=self.loop)
factory.useragent = agent
factory.protocol = lambda: room
conn = self.loop.create_connection(
factory,
host=urlparts.netloc,
port=urlparts.port or 443,
ssl=urlparts.scheme == "wss",
)
asyncio.ensure_future(conn, loop=self.loop) | [
"def",
"create_connection",
"(",
"self",
",",
"room",
",",
"ws_url",
",",
"agent",
",",
"cookies",
")",
":",
"urlparts",
"=",
"urlsplit",
"(",
"ws_url",
")",
"req",
"=",
"Request",
"(",
"\"GET\"",
",",
"ws_url",
")",
"cookies",
"=",
"get_cookie_header",
... | Creates a new connection | [
"Creates",
"a",
"new",
"connection"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L153-L173 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator.__send_message | def __send_message(self, proto, payload):
# pylint: disable=no-self-use
"""Sends a message"""
try:
if not isinstance(payload, bytes):
payload = payload.encode("utf-8")
if not proto.connected:
raise IOError("not connected")
proto.sendMessage(payload)
logger.debug("sent: %r", payload)
except Exception as ex:
logger.exception("Failed to send message")
proto.reraise(ex) | python | def __send_message(self, proto, payload):
# pylint: disable=no-self-use
"""Sends a message"""
try:
if not isinstance(payload, bytes):
payload = payload.encode("utf-8")
if not proto.connected:
raise IOError("not connected")
proto.sendMessage(payload)
logger.debug("sent: %r", payload)
except Exception as ex:
logger.exception("Failed to send message")
proto.reraise(ex) | [
"def",
"__send_message",
"(",
"self",
",",
"proto",
",",
"payload",
")",
":",
"# pylint: disable=no-self-use",
"try",
":",
"if",
"not",
"isinstance",
"(",
"payload",
",",
"bytes",
")",
":",
"payload",
"=",
"payload",
".",
"encode",
"(",
"\"utf-8\"",
")",
"... | Sends a message | [
"Sends",
"a",
"message"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L175-L188 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator.close | def close(self, proto):
# pylint: disable=no-self-use
"""Closes a connection"""
try:
proto.sendClose()
except Exception as ex:
logger.exception("Failed to send close")
proto.reraise(ex) | python | def close(self, proto):
# pylint: disable=no-self-use
"""Closes a connection"""
try:
proto.sendClose()
except Exception as ex:
logger.exception("Failed to send close")
proto.reraise(ex) | [
"def",
"close",
"(",
"self",
",",
"proto",
")",
":",
"# pylint: disable=no-self-use",
"try",
":",
"proto",
".",
"sendClose",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"exception",
"(",
"\"Failed to send close\"",
")",
"proto",
".",
"re... | Closes a connection | [
"Closes",
"a",
"connection"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L199-L207 |
volafiled/python-volapi | volapi/auxo.py | Listeners.process | def process(self):
"""Process queue for these listeners. Only the items with type that
matches """
with self.lock, self.enlock:
queue = copy(self.queue)
self.queue.clear()
callbacks = copy(self.callbacks)
with self.lock:
rm_cb = False
for ki, vi in queue.items():
if ki in self.callbacks:
for item in vi:
for cb in self.callbacks[ki]:
if cb(item) is False:
callbacks[ki].remove(cb)
if not callbacks[ki]:
del callbacks[ki]
rm_cb = True
with self.lock:
if rm_cb:
self.callbacks.clear()
for k, v in callbacks.items():
self.callbacks[k].extend(v)
return len(self.callbacks) | python | def process(self):
"""Process queue for these listeners. Only the items with type that
matches """
with self.lock, self.enlock:
queue = copy(self.queue)
self.queue.clear()
callbacks = copy(self.callbacks)
with self.lock:
rm_cb = False
for ki, vi in queue.items():
if ki in self.callbacks:
for item in vi:
for cb in self.callbacks[ki]:
if cb(item) is False:
callbacks[ki].remove(cb)
if not callbacks[ki]:
del callbacks[ki]
rm_cb = True
with self.lock:
if rm_cb:
self.callbacks.clear()
for k, v in callbacks.items():
self.callbacks[k].extend(v)
return len(self.callbacks) | [
"def",
"process",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
",",
"self",
".",
"enlock",
":",
"queue",
"=",
"copy",
"(",
"self",
".",
"queue",
")",
"self",
".",
"queue",
".",
"clear",
"(",
")",
"callbacks",
"=",
"copy",
"(",
"self",
".",... | Process queue for these listeners. Only the items with type that
matches | [
"Process",
"queue",
"for",
"these",
"listeners",
".",
"Only",
"the",
"items",
"with",
"type",
"that",
"matches"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L228-L254 |
volafiled/python-volapi | volapi/auxo.py | Listeners.add | def add(self, callback_type, callback):
"""Add a new listener"""
with self.lock:
self.callbacks[callback_type].append(callback) | python | def add(self, callback_type, callback):
"""Add a new listener"""
with self.lock:
self.callbacks[callback_type].append(callback) | [
"def",
"add",
"(",
"self",
",",
"callback_type",
",",
"callback",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"callbacks",
"[",
"callback_type",
"]",
".",
"append",
"(",
"callback",
")"
] | Add a new listener | [
"Add",
"a",
"new",
"listener"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L256-L260 |
volafiled/python-volapi | volapi/auxo.py | Listeners.enqueue | def enqueue(self, item_type, item):
"""Queue a new data item, make item iterable"""
with self.enlock:
self.queue[item_type].append(item) | python | def enqueue(self, item_type, item):
"""Queue a new data item, make item iterable"""
with self.enlock:
self.queue[item_type].append(item) | [
"def",
"enqueue",
"(",
"self",
",",
"item_type",
",",
"item",
")",
":",
"with",
"self",
".",
"enlock",
":",
"self",
".",
"queue",
"[",
"item_type",
"]",
".",
"append",
"(",
"item",
")"
] | Queue a new data item, make item iterable | [
"Queue",
"a",
"new",
"data",
"item",
"make",
"item",
"iterable"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L262-L266 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.extract_slitlet2d | def extract_slitlet2d(self, image_2k2k):
"""Extract slitlet 2d image from image with original EMIR dimensions.
Parameters
----------
image_2k2k : numpy array
Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2)
Returns
-------
slitlet2d : numpy array
Image corresponding to the slitlet region defined by its
bounding box.
"""
# protections
naxis2, naxis1 = image_2k2k.shape
if naxis1 != EMIR_NAXIS1:
raise ValueError('Unexpected naxis1')
if naxis2 != EMIR_NAXIS2:
raise ValueError('Unexpected naxis2')
# extract slitlet region
slitlet2d = image_2k2k[(self.bb_ns1_orig - 1):self.bb_ns2_orig,
(self.bb_nc1_orig - 1):self.bb_nc2_orig]
# transform to float
slitlet2d = slitlet2d.astype(np.float)
# display slitlet2d with boundaries and middle spectrum trail
if abs(self.debugplot) in [21, 22]:
ax = ximshow(slitlet2d, title="Slitlet#" + str(self.islitlet),
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
xdum = np.linspace(1, EMIR_NAXIS1, num=EMIR_NAXIS1)
ylower = \
self.list_spectrails[self.i_lower_spectrail].poly_funct(xdum)
ax.plot(xdum, ylower, 'b-')
ymiddle = \
self.list_spectrails[self.i_middle_spectrail].poly_funct(xdum)
ax.plot(xdum, ymiddle, 'b--')
yupper = \
self.list_spectrails[self.i_upper_spectrail].poly_funct(xdum)
ax.plot(xdum, yupper, 'b-')
ylower_frontier = self.list_frontiers[0].poly_funct(xdum)
ax.plot(xdum, ylower_frontier, 'b:')
yupper_frontier = self.list_frontiers[1].poly_funct(xdum)
ax.plot(xdum, yupper_frontier, 'b:')
pause_debugplot(debugplot=self.debugplot, pltshow=True)
# return slitlet image
return slitlet2d | python | def extract_slitlet2d(self, image_2k2k):
"""Extract slitlet 2d image from image with original EMIR dimensions.
Parameters
----------
image_2k2k : numpy array
Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2)
Returns
-------
slitlet2d : numpy array
Image corresponding to the slitlet region defined by its
bounding box.
"""
# protections
naxis2, naxis1 = image_2k2k.shape
if naxis1 != EMIR_NAXIS1:
raise ValueError('Unexpected naxis1')
if naxis2 != EMIR_NAXIS2:
raise ValueError('Unexpected naxis2')
# extract slitlet region
slitlet2d = image_2k2k[(self.bb_ns1_orig - 1):self.bb_ns2_orig,
(self.bb_nc1_orig - 1):self.bb_nc2_orig]
# transform to float
slitlet2d = slitlet2d.astype(np.float)
# display slitlet2d with boundaries and middle spectrum trail
if abs(self.debugplot) in [21, 22]:
ax = ximshow(slitlet2d, title="Slitlet#" + str(self.islitlet),
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
xdum = np.linspace(1, EMIR_NAXIS1, num=EMIR_NAXIS1)
ylower = \
self.list_spectrails[self.i_lower_spectrail].poly_funct(xdum)
ax.plot(xdum, ylower, 'b-')
ymiddle = \
self.list_spectrails[self.i_middle_spectrail].poly_funct(xdum)
ax.plot(xdum, ymiddle, 'b--')
yupper = \
self.list_spectrails[self.i_upper_spectrail].poly_funct(xdum)
ax.plot(xdum, yupper, 'b-')
ylower_frontier = self.list_frontiers[0].poly_funct(xdum)
ax.plot(xdum, ylower_frontier, 'b:')
yupper_frontier = self.list_frontiers[1].poly_funct(xdum)
ax.plot(xdum, yupper_frontier, 'b:')
pause_debugplot(debugplot=self.debugplot, pltshow=True)
# return slitlet image
return slitlet2d | [
"def",
"extract_slitlet2d",
"(",
"self",
",",
"image_2k2k",
")",
":",
"# protections",
"naxis2",
",",
"naxis1",
"=",
"image_2k2k",
".",
"shape",
"if",
"naxis1",
"!=",
"EMIR_NAXIS1",
":",
"raise",
"ValueError",
"(",
"'Unexpected naxis1'",
")",
"if",
"naxis2",
"... | Extract slitlet 2d image from image with original EMIR dimensions.
Parameters
----------
image_2k2k : numpy array
Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2)
Returns
-------
slitlet2d : numpy array
Image corresponding to the slitlet region defined by its
bounding box. | [
"Extract",
"slitlet",
"2d",
"image",
"from",
"image",
"with",
"original",
"EMIR",
"dimensions",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L524-L576 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.locate_unknown_arc_lines | def locate_unknown_arc_lines(self, slitlet2d,
times_sigma_threshold=15,
minimum_threshold=None,
delta_x_max=30,
delta_y_min=30,
min_dist_from_middle=15):
"""Determine the location of known arc lines in slitlet.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
times_sigma_threshold : float
Times (robust) sigma above the median of the image to look
for arc lines.
minimum_threshold : float or None
Minimum threshold to look for arc lines.
delta_x_max : float
Maximum size of potential arc line in the X direction.
delta_y_min : float
Minimum size of potential arc line in the Y direction.
min_dist_from_middle : float
Minimum Y distance from the middle spectrum trail to the
extreme of the potential arc line. This constraint avoid
detecting arc line reflections as bone fide arc lines.
"""
# smooth denoising of slitlet2d
slitlet2d_rs, coef_rs = rescale_array_to_z1z2(slitlet2d, z1z2=(-1, 1))
slitlet2d_dn = restoration.denoise_nl_means(slitlet2d_rs,
patch_size=3,
patch_distance=2,
multichannel=False)
slitlet2d_dn = rescale_array_from_z1z2(slitlet2d_dn, coef_rs)
# compute basic statistics
q25, q50, q75 = np.percentile(slitlet2d_dn, q=[25.0, 50.0, 75.0])
sigmag = 0.7413 * (q75 - q25) # robust standard deviation
if abs(self.debugplot) >= 10:
q16, q84 = np.percentile(slitlet2d_dn, q=[15.87, 84.13])
print('>>> q16...:', q16)
print('>>> q25...:', q25)
print('>>> q50...:', q50)
print('>>> q75...:', q75)
print('>>> q84...:', q84)
print('>>> sigmaG:', sigmag)
if abs(self.debugplot) in [21, 22]:
# display initial image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #1)"
ximshow(slitlet2d, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
debugplot=self.debugplot)
# display denoised image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #2)"
ximshow(slitlet2d_dn, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
debugplot=self.debugplot)
# display image with different cuts
z1z2 = (q50 + times_sigma_threshold * sigmag,
q50 + 2 * times_sigma_threshold * sigmag)
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #3)"
ximshow(slitlet2d_dn, title=title, z1z2=z1z2,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
debugplot=self.debugplot)
# determine threshold (using the maximum of q50 + t *sigmag or
# minimum_threshold)
threshold = q50 + times_sigma_threshold * sigmag
if minimum_threshold is not None:
if minimum_threshold > threshold:
threshold = minimum_threshold
# identify objects in slitlet2d above threshold
labels2d_objects, no_objects = ndimage.label(slitlet2d_dn > threshold)
if abs(self.debugplot) >= 10:
print("Number of objects initially found:", no_objects)
if abs(self.debugplot) in [21, 22]:
# display all objects identified in the image
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #4)"
z1z2 = (labels2d_objects.min(), labels2d_objects.max())
ximshow(labels2d_objects, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
cbar_label="Object number",
z1z2=z1z2, cmap="nipy_spectral",
debugplot=self.debugplot)
# select arc lines by imposing the criteria based on the
# dimensions of the detected objects and the intersection with
# the middle spectrum trail
slices_possible_arc_lines = ndimage.find_objects(labels2d_objects)
slices_ok = np.repeat([False], no_objects) # flag
for i in range(no_objects):
if abs(self.debugplot) >= 10:
print('object', i + 1,
'[in np.array coordinates]:',
slices_possible_arc_lines[i])
slice_x = slices_possible_arc_lines[i][1]
slice_y = slices_possible_arc_lines[i][0]
# note that the width computation doesn't require to
# add +1 since slice_x.stop (and slice_y.stop) is
# already the upper limit +1 (in np.array coordinates)
delta_x = slice_x.stop - slice_x.start
delta_y = slice_y.stop - slice_y.start
# dimensions criterion
if delta_x <= delta_x_max and delta_y >= delta_y_min:
# intersection with middle spectrum trail criterion;
# note that slice_x and slice_y are given in np.array
# coordinates and are transformed into image coordinates;
# in addition, -0.5 shift the origin to the lower left
# corner of the pixel
xini_slice = slice_x.start + self.bb_nc1_orig - 0.5
xmiddle_slice = xini_slice + delta_x / 2
polydum = \
self.list_spectrails[self.i_middle_spectrail].poly_funct
ymiddle_slice = polydum(xmiddle_slice)
yini_slice = slice_y.start + self.bb_ns1_orig - 0.5
yend_slice = yini_slice + delta_y
if yini_slice + min_dist_from_middle <= ymiddle_slice <= \
yend_slice - min_dist_from_middle:
slices_ok[i] = True
# generate list with ID of arc lines (note that first object is
# number 0 and not 1)
list_slices_ok = []
for i in range(no_objects):
if slices_ok[i]:
list_slices_ok.append(i + 1)
number_arc_lines = len(list_slices_ok)
if abs(self.debugplot) >= 10:
print("\nNumber of arc lines initially identified is:",
number_arc_lines)
if number_arc_lines > 0:
print("Slice ID of lines passing the selection:\n",
list_slices_ok)
if number_arc_lines == 0:
return
# display arc lines
if abs(self.debugplot) in [21, 22]:
# display all objects identified in the image
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #5)"
z1z2 = (labels2d_objects.min(),
labels2d_objects.max())
ax = ximshow(labels2d_objects, show=False, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
cbar_label="Object number",
z1z2=z1z2, cmap="nipy_spectral",
debugplot=self.debugplot)
# plot rectangle around identified arc lines
for i in range(no_objects):
if slices_ok[i]:
slice_x = slices_possible_arc_lines[i][1]
slice_y = slices_possible_arc_lines[i][0]
# note that slice_x and slice_y are given in np.array
# coordinates and are transformed into image coordinates;
# in addition, -0.5 shift the origin to the lower left
# corner of the pixel
xini_slice = slice_x.start + self.bb_nc1_orig - 0.5
yini_slice = slice_y.start + self.bb_ns1_orig - 0.5
# note that the width computation doesn't require to
# add +1 since slice_x.stop (and slice_y.stop) is
# already the upper limit +1 (in np.array coordinates)
xwidth_slice = slice_x.stop - slice_x.start
ywidth_slice = slice_y.stop - slice_y.start
rect = Rectangle((xini_slice, yini_slice),
xwidth_slice, ywidth_slice,
edgecolor='w', facecolor='none')
ax.add_patch(rect)
# show plot
pause_debugplot(self.debugplot, pltshow=True)
# adjust individual arc lines passing the initial selection
self.list_arc_lines = [] # list of ArcLines
for k in range(number_arc_lines): # fit each arc line
# select points to be fitted for a particular arc line
xy_tmp = np.where(labels2d_objects == list_slices_ok[k])
x_tmp = xy_tmp[1] + self.bb_nc1_orig # use image coordinates
y_tmp = xy_tmp[0] + self.bb_ns1_orig # use image coordinates
w_tmp = slitlet2d_dn[xy_tmp]
# declare new ArcLine instance
arc_line = ArcLine()
# define new ArcLine using a weighted fit
# (note that it must be X vs Y)
arc_line.fit(x=x_tmp, y=y_tmp, deg=1, w=w_tmp, y_vs_x=False)
if len(arc_line.poly_funct.coef) == 2:
# update list with identified ArcLines
self.list_arc_lines.append(arc_line)
else:
# ignore (sometimes the arc_line.fit returns a constant!)
pass
# recompute number_arc_lines just in case in the previous fits
# some lines have just given a zero degree polynomial
number_arc_lines = len(self.list_arc_lines)
# remove arc lines with unexpected slopes
yfit = np.array([self.list_arc_lines[k].poly_funct.coef[1]
for k in range(number_arc_lines)])
xfit = np.zeros(number_arc_lines)
# intersection between middle spectrum trail and arc line
for k in range(number_arc_lines):
arcline = self.list_arc_lines[k]
xfit[k], ydum = intersection_spectrail_arcline(
self.list_spectrails[self.i_middle_spectrail], arcline
)
# fit slope versus x-coordinate of the intersection of the arc line
# with the middle spectrum trail
if len(yfit) > 5:
degeff = 5
else:
degeff = len(yfit) - 1
polydum, residum, rejected = polfit_residuals_with_sigma_rejection(
x=xfit, y=yfit, deg=degeff, times_sigma_reject=4.0,
xlabel='arc line center (islitlet #' + str(self.islitlet) + ')',
ylabel='arc line slope', debugplot=0
)
# remove rejected arc lines
if len(rejected) > 0:
if abs(self.debugplot) >= 10:
print('Rejecting', sum(rejected),
'arc lines with suspicious slopes: Slice ID',
[list_slices_ok[k] for k in range(number_arc_lines)
if rejected[k]])
self.list_arc_lines = \
[self.list_arc_lines[k] for k in range(number_arc_lines)
if not rejected[k]]
# recompute number of arc lines
number_arc_lines = len(self.list_arc_lines)
if abs(self.debugplot) >= 10:
print("\nNumber of arc lines finally identified is:",
number_arc_lines)
if abs(self.debugplot) >= 20:
# print list of arc lines
print('\nlist_arc_lines:')
for k in range(number_arc_lines):
print(k, '->', self.list_arc_lines[k], '\n')
# display results
if abs(self.debugplot) in [21, 22]:
# generate mask with all the arc-line points passing the selection
mask_arc_lines = np.zeros_like(slitlet2d_dn)
for k in list_slices_ok:
mask_arc_lines[labels2d_objects == k] = 1
# compute image with only the arc lines passing the selection
labels2d_arc_lines = labels2d_objects * mask_arc_lines
# display background image with filtered arc lines
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #6)"
z1z2 = (labels2d_arc_lines.min(),
labels2d_arc_lines.max())
ax = ximshow(labels2d_arc_lines, show=False,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
cbar_label="Object number",
title=title, z1z2=z1z2, cmap="nipy_spectral",
debugplot=self.debugplot)
# plot weighted fit for each arc line (note that the fit is
# X vs Y)
for k in range(number_arc_lines):
xpol, ypol = self.list_arc_lines[k].linspace_pix()
ax.plot(xpol, ypol, 'g--')
# display lower and upper points of each arc line
x_tmp = [arc_line.xlower_line for arc_line in self.list_arc_lines]
y_tmp = [arc_line.ylower_line for arc_line in self.list_arc_lines]
ax.plot(x_tmp, y_tmp, 'w+')
x_tmp = [arc_line.xupper_line for arc_line in self.list_arc_lines]
y_tmp = [arc_line.yupper_line for arc_line in self.list_arc_lines]
ax.plot(x_tmp, y_tmp, 'w+')
# show plot
pause_debugplot(self.debugplot, pltshow=True) | python | def locate_unknown_arc_lines(self, slitlet2d,
times_sigma_threshold=15,
minimum_threshold=None,
delta_x_max=30,
delta_y_min=30,
min_dist_from_middle=15):
"""Determine the location of known arc lines in slitlet.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
times_sigma_threshold : float
Times (robust) sigma above the median of the image to look
for arc lines.
minimum_threshold : float or None
Minimum threshold to look for arc lines.
delta_x_max : float
Maximum size of potential arc line in the X direction.
delta_y_min : float
Minimum size of potential arc line in the Y direction.
min_dist_from_middle : float
Minimum Y distance from the middle spectrum trail to the
extreme of the potential arc line. This constraint avoid
detecting arc line reflections as bone fide arc lines.
"""
# smooth denoising of slitlet2d
slitlet2d_rs, coef_rs = rescale_array_to_z1z2(slitlet2d, z1z2=(-1, 1))
slitlet2d_dn = restoration.denoise_nl_means(slitlet2d_rs,
patch_size=3,
patch_distance=2,
multichannel=False)
slitlet2d_dn = rescale_array_from_z1z2(slitlet2d_dn, coef_rs)
# compute basic statistics
q25, q50, q75 = np.percentile(slitlet2d_dn, q=[25.0, 50.0, 75.0])
sigmag = 0.7413 * (q75 - q25) # robust standard deviation
if abs(self.debugplot) >= 10:
q16, q84 = np.percentile(slitlet2d_dn, q=[15.87, 84.13])
print('>>> q16...:', q16)
print('>>> q25...:', q25)
print('>>> q50...:', q50)
print('>>> q75...:', q75)
print('>>> q84...:', q84)
print('>>> sigmaG:', sigmag)
if abs(self.debugplot) in [21, 22]:
# display initial image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #1)"
ximshow(slitlet2d, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
debugplot=self.debugplot)
# display denoised image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #2)"
ximshow(slitlet2d_dn, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
debugplot=self.debugplot)
# display image with different cuts
z1z2 = (q50 + times_sigma_threshold * sigmag,
q50 + 2 * times_sigma_threshold * sigmag)
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #3)"
ximshow(slitlet2d_dn, title=title, z1z2=z1z2,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
debugplot=self.debugplot)
# determine threshold (using the maximum of q50 + t *sigmag or
# minimum_threshold)
threshold = q50 + times_sigma_threshold * sigmag
if minimum_threshold is not None:
if minimum_threshold > threshold:
threshold = minimum_threshold
# identify objects in slitlet2d above threshold
labels2d_objects, no_objects = ndimage.label(slitlet2d_dn > threshold)
if abs(self.debugplot) >= 10:
print("Number of objects initially found:", no_objects)
if abs(self.debugplot) in [21, 22]:
# display all objects identified in the image
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #4)"
z1z2 = (labels2d_objects.min(), labels2d_objects.max())
ximshow(labels2d_objects, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
cbar_label="Object number",
z1z2=z1z2, cmap="nipy_spectral",
debugplot=self.debugplot)
# select arc lines by imposing the criteria based on the
# dimensions of the detected objects and the intersection with
# the middle spectrum trail
slices_possible_arc_lines = ndimage.find_objects(labels2d_objects)
slices_ok = np.repeat([False], no_objects) # flag
for i in range(no_objects):
if abs(self.debugplot) >= 10:
print('object', i + 1,
'[in np.array coordinates]:',
slices_possible_arc_lines[i])
slice_x = slices_possible_arc_lines[i][1]
slice_y = slices_possible_arc_lines[i][0]
# note that the width computation doesn't require to
# add +1 since slice_x.stop (and slice_y.stop) is
# already the upper limit +1 (in np.array coordinates)
delta_x = slice_x.stop - slice_x.start
delta_y = slice_y.stop - slice_y.start
# dimensions criterion
if delta_x <= delta_x_max and delta_y >= delta_y_min:
# intersection with middle spectrum trail criterion;
# note that slice_x and slice_y are given in np.array
# coordinates and are transformed into image coordinates;
# in addition, -0.5 shift the origin to the lower left
# corner of the pixel
xini_slice = slice_x.start + self.bb_nc1_orig - 0.5
xmiddle_slice = xini_slice + delta_x / 2
polydum = \
self.list_spectrails[self.i_middle_spectrail].poly_funct
ymiddle_slice = polydum(xmiddle_slice)
yini_slice = slice_y.start + self.bb_ns1_orig - 0.5
yend_slice = yini_slice + delta_y
if yini_slice + min_dist_from_middle <= ymiddle_slice <= \
yend_slice - min_dist_from_middle:
slices_ok[i] = True
# generate list with ID of arc lines (note that first object is
# number 0 and not 1)
list_slices_ok = []
for i in range(no_objects):
if slices_ok[i]:
list_slices_ok.append(i + 1)
number_arc_lines = len(list_slices_ok)
if abs(self.debugplot) >= 10:
print("\nNumber of arc lines initially identified is:",
number_arc_lines)
if number_arc_lines > 0:
print("Slice ID of lines passing the selection:\n",
list_slices_ok)
if number_arc_lines == 0:
return
# display arc lines
if abs(self.debugplot) in [21, 22]:
# display all objects identified in the image
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #5)"
z1z2 = (labels2d_objects.min(),
labels2d_objects.max())
ax = ximshow(labels2d_objects, show=False, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
cbar_label="Object number",
z1z2=z1z2, cmap="nipy_spectral",
debugplot=self.debugplot)
# plot rectangle around identified arc lines
for i in range(no_objects):
if slices_ok[i]:
slice_x = slices_possible_arc_lines[i][1]
slice_y = slices_possible_arc_lines[i][0]
# note that slice_x and slice_y are given in np.array
# coordinates and are transformed into image coordinates;
# in addition, -0.5 shift the origin to the lower left
# corner of the pixel
xini_slice = slice_x.start + self.bb_nc1_orig - 0.5
yini_slice = slice_y.start + self.bb_ns1_orig - 0.5
# note that the width computation doesn't require to
# add +1 since slice_x.stop (and slice_y.stop) is
# already the upper limit +1 (in np.array coordinates)
xwidth_slice = slice_x.stop - slice_x.start
ywidth_slice = slice_y.stop - slice_y.start
rect = Rectangle((xini_slice, yini_slice),
xwidth_slice, ywidth_slice,
edgecolor='w', facecolor='none')
ax.add_patch(rect)
# show plot
pause_debugplot(self.debugplot, pltshow=True)
# adjust individual arc lines passing the initial selection
self.list_arc_lines = [] # list of ArcLines
for k in range(number_arc_lines): # fit each arc line
# select points to be fitted for a particular arc line
xy_tmp = np.where(labels2d_objects == list_slices_ok[k])
x_tmp = xy_tmp[1] + self.bb_nc1_orig # use image coordinates
y_tmp = xy_tmp[0] + self.bb_ns1_orig # use image coordinates
w_tmp = slitlet2d_dn[xy_tmp]
# declare new ArcLine instance
arc_line = ArcLine()
# define new ArcLine using a weighted fit
# (note that it must be X vs Y)
arc_line.fit(x=x_tmp, y=y_tmp, deg=1, w=w_tmp, y_vs_x=False)
if len(arc_line.poly_funct.coef) == 2:
# update list with identified ArcLines
self.list_arc_lines.append(arc_line)
else:
# ignore (sometimes the arc_line.fit returns a constant!)
pass
# recompute number_arc_lines just in case in the previous fits
# some lines have just given a zero degree polynomial
number_arc_lines = len(self.list_arc_lines)
# remove arc lines with unexpected slopes
yfit = np.array([self.list_arc_lines[k].poly_funct.coef[1]
for k in range(number_arc_lines)])
xfit = np.zeros(number_arc_lines)
# intersection between middle spectrum trail and arc line
for k in range(number_arc_lines):
arcline = self.list_arc_lines[k]
xfit[k], ydum = intersection_spectrail_arcline(
self.list_spectrails[self.i_middle_spectrail], arcline
)
# fit slope versus x-coordinate of the intersection of the arc line
# with the middle spectrum trail
if len(yfit) > 5:
degeff = 5
else:
degeff = len(yfit) - 1
polydum, residum, rejected = polfit_residuals_with_sigma_rejection(
x=xfit, y=yfit, deg=degeff, times_sigma_reject=4.0,
xlabel='arc line center (islitlet #' + str(self.islitlet) + ')',
ylabel='arc line slope', debugplot=0
)
# remove rejected arc lines
if len(rejected) > 0:
if abs(self.debugplot) >= 10:
print('Rejecting', sum(rejected),
'arc lines with suspicious slopes: Slice ID',
[list_slices_ok[k] for k in range(number_arc_lines)
if rejected[k]])
self.list_arc_lines = \
[self.list_arc_lines[k] for k in range(number_arc_lines)
if not rejected[k]]
# recompute number of arc lines
number_arc_lines = len(self.list_arc_lines)
if abs(self.debugplot) >= 10:
print("\nNumber of arc lines finally identified is:",
number_arc_lines)
if abs(self.debugplot) >= 20:
# print list of arc lines
print('\nlist_arc_lines:')
for k in range(number_arc_lines):
print(k, '->', self.list_arc_lines[k], '\n')
# display results
if abs(self.debugplot) in [21, 22]:
# generate mask with all the arc-line points passing the selection
mask_arc_lines = np.zeros_like(slitlet2d_dn)
for k in list_slices_ok:
mask_arc_lines[labels2d_objects == k] = 1
# compute image with only the arc lines passing the selection
labels2d_arc_lines = labels2d_objects * mask_arc_lines
# display background image with filtered arc lines
title = "Slitlet#" + str(self.islitlet) + \
" (locate_unknown_arc_lines, step #6)"
z1z2 = (labels2d_arc_lines.min(),
labels2d_arc_lines.max())
ax = ximshow(labels2d_arc_lines, show=False,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
cbar_label="Object number",
title=title, z1z2=z1z2, cmap="nipy_spectral",
debugplot=self.debugplot)
# plot weighted fit for each arc line (note that the fit is
# X vs Y)
for k in range(number_arc_lines):
xpol, ypol = self.list_arc_lines[k].linspace_pix()
ax.plot(xpol, ypol, 'g--')
# display lower and upper points of each arc line
x_tmp = [arc_line.xlower_line for arc_line in self.list_arc_lines]
y_tmp = [arc_line.ylower_line for arc_line in self.list_arc_lines]
ax.plot(x_tmp, y_tmp, 'w+')
x_tmp = [arc_line.xupper_line for arc_line in self.list_arc_lines]
y_tmp = [arc_line.yupper_line for arc_line in self.list_arc_lines]
ax.plot(x_tmp, y_tmp, 'w+')
# show plot
pause_debugplot(self.debugplot, pltshow=True) | [
"def",
"locate_unknown_arc_lines",
"(",
"self",
",",
"slitlet2d",
",",
"times_sigma_threshold",
"=",
"15",
",",
"minimum_threshold",
"=",
"None",
",",
"delta_x_max",
"=",
"30",
",",
"delta_y_min",
"=",
"30",
",",
"min_dist_from_middle",
"=",
"15",
")",
":",
"#... | Determine the location of known arc lines in slitlet.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
times_sigma_threshold : float
Times (robust) sigma above the median of the image to look
for arc lines.
minimum_threshold : float or None
Minimum threshold to look for arc lines.
delta_x_max : float
Maximum size of potential arc line in the X direction.
delta_y_min : float
Minimum size of potential arc line in the Y direction.
min_dist_from_middle : float
Minimum Y distance from the middle spectrum trail to the
extreme of the potential arc line. This constraint avoid
detecting arc line reflections as bone fide arc lines. | [
"Determine",
"the",
"location",
"of",
"known",
"arc",
"lines",
"in",
"slitlet",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L578-L854 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.xy_spectrail_arc_intersections | def xy_spectrail_arc_intersections(self, slitlet2d=None):
"""Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points overplotted. This argument is
optional.
"""
# protections
if self.list_arc_lines is None:
raise ValueError("Arc lines not sought")
number_spectrum_trails = len(self.list_spectrails)
if number_spectrum_trails == 0:
raise ValueError("Number of available spectrum trails is 0")
number_arc_lines = len(self.list_arc_lines)
if number_arc_lines == 0:
raise ValueError("Number of available arc lines is 0")
# intersection of the arc lines with the spectrum trails
# (note: the coordinates are computed using pixel values,
# ranging from 1 to EMIR_NAXIS1, as given in the original
# image reference system ---not in the slitlet image reference
# system---)
self.x_inter_rect = np.array([]) # rectified image coordinates
self.y_inter_rect = np.array([]) # rectified image coordinates
for arcline in self.list_arc_lines:
# middle spectrum trail
spectrail = self.list_spectrails[self.i_middle_spectrail]
xroot, yroot = intersection_spectrail_arcline(
spectrail=spectrail, arcline=arcline
)
arcline.x_rectified = xroot
self.x_inter_rect = np.append(
self.x_inter_rect, [xroot] * number_spectrum_trails
)
for spectrail in self.list_spectrails:
# compute expected ordinate y_expected in the rectified
# image
y_expected = self.corr_yrect_a + self.corr_yrect_b * \
spectrail.y_rectified
self.y_inter_rect = np.append(self.y_inter_rect, y_expected)
if abs(self.debugplot) >= 10:
print('>>> y0_frontier_lower_expected........: ',
self.y0_frontier_lower_expected)
print('>>> y0_frontier_upper_expected........: ',
self.y0_frontier_upper_expected)
print('>>> shifted y0_frontier_upper_expected: ',
self.corr_yrect_a +
self.corr_yrect_b * self.y0_frontier_lower)
print('>>> shifted y0_frontier_lower_expected: ',
self.corr_yrect_a +
self.corr_yrect_b * self.y0_frontier_upper)
#
self.x_inter_orig = np.array([]) # original image coordinates
self.y_inter_orig = np.array([]) # original image coordinates
for arcline in self.list_arc_lines:
for spectrail in self.list_spectrails:
xroot, yroot = intersection_spectrail_arcline(
spectrail=spectrail, arcline=arcline
)
self.x_inter_orig = np.append(self.x_inter_orig, xroot)
self.y_inter_orig = np.append(self.y_inter_orig, yroot)
# display intersection points
if abs(self.debugplot % 10) != 0 and slitlet2d is not None:
# display image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (xy_spectrail_arc_intersections)"
ax = ximshow(slitlet2d, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
# spectrum trails
for spectrail in self.list_spectrails:
xdum, ydum = spectrail.linspace_pix(start=self.bb_nc1_orig,
stop=self.bb_nc2_orig)
ax.plot(xdum, ydum, 'g')
# arc lines
for arcline in self.list_arc_lines:
xdum, ydum = arcline.linspace_pix(start=self.bb_ns1_orig,
stop=self.bb_ns2_orig)
ax.plot(xdum, ydum, 'g')
# intersection points
ax.plot(self.x_inter_orig, self.y_inter_orig, 'co')
ax.plot(self.x_inter_rect, self.y_inter_rect, 'bo')
# show plot
pause_debugplot(self.debugplot, pltshow=True) | python | def xy_spectrail_arc_intersections(self, slitlet2d=None):
"""Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points overplotted. This argument is
optional.
"""
# protections
if self.list_arc_lines is None:
raise ValueError("Arc lines not sought")
number_spectrum_trails = len(self.list_spectrails)
if number_spectrum_trails == 0:
raise ValueError("Number of available spectrum trails is 0")
number_arc_lines = len(self.list_arc_lines)
if number_arc_lines == 0:
raise ValueError("Number of available arc lines is 0")
# intersection of the arc lines with the spectrum trails
# (note: the coordinates are computed using pixel values,
# ranging from 1 to EMIR_NAXIS1, as given in the original
# image reference system ---not in the slitlet image reference
# system---)
self.x_inter_rect = np.array([]) # rectified image coordinates
self.y_inter_rect = np.array([]) # rectified image coordinates
for arcline in self.list_arc_lines:
# middle spectrum trail
spectrail = self.list_spectrails[self.i_middle_spectrail]
xroot, yroot = intersection_spectrail_arcline(
spectrail=spectrail, arcline=arcline
)
arcline.x_rectified = xroot
self.x_inter_rect = np.append(
self.x_inter_rect, [xroot] * number_spectrum_trails
)
for spectrail in self.list_spectrails:
# compute expected ordinate y_expected in the rectified
# image
y_expected = self.corr_yrect_a + self.corr_yrect_b * \
spectrail.y_rectified
self.y_inter_rect = np.append(self.y_inter_rect, y_expected)
if abs(self.debugplot) >= 10:
print('>>> y0_frontier_lower_expected........: ',
self.y0_frontier_lower_expected)
print('>>> y0_frontier_upper_expected........: ',
self.y0_frontier_upper_expected)
print('>>> shifted y0_frontier_upper_expected: ',
self.corr_yrect_a +
self.corr_yrect_b * self.y0_frontier_lower)
print('>>> shifted y0_frontier_lower_expected: ',
self.corr_yrect_a +
self.corr_yrect_b * self.y0_frontier_upper)
#
self.x_inter_orig = np.array([]) # original image coordinates
self.y_inter_orig = np.array([]) # original image coordinates
for arcline in self.list_arc_lines:
for spectrail in self.list_spectrails:
xroot, yroot = intersection_spectrail_arcline(
spectrail=spectrail, arcline=arcline
)
self.x_inter_orig = np.append(self.x_inter_orig, xroot)
self.y_inter_orig = np.append(self.y_inter_orig, yroot)
# display intersection points
if abs(self.debugplot % 10) != 0 and slitlet2d is not None:
# display image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (xy_spectrail_arc_intersections)"
ax = ximshow(slitlet2d, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
# spectrum trails
for spectrail in self.list_spectrails:
xdum, ydum = spectrail.linspace_pix(start=self.bb_nc1_orig,
stop=self.bb_nc2_orig)
ax.plot(xdum, ydum, 'g')
# arc lines
for arcline in self.list_arc_lines:
xdum, ydum = arcline.linspace_pix(start=self.bb_ns1_orig,
stop=self.bb_ns2_orig)
ax.plot(xdum, ydum, 'g')
# intersection points
ax.plot(self.x_inter_orig, self.y_inter_orig, 'co')
ax.plot(self.x_inter_rect, self.y_inter_rect, 'bo')
# show plot
pause_debugplot(self.debugplot, pltshow=True) | [
"def",
"xy_spectrail_arc_intersections",
"(",
"self",
",",
"slitlet2d",
"=",
"None",
")",
":",
"# protections",
"if",
"self",
".",
"list_arc_lines",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Arc lines not sought\"",
")",
"number_spectrum_trails",
"=",
"len",... | Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points overplotted. This argument is
optional. | [
"Compute",
"intersection",
"points",
"of",
"spectrum",
"trails",
"with",
"arc",
"lines",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L856-L948 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.estimate_tt_to_rectify | def estimate_tt_to_rectify(self, order, slitlet2d=None):
"""Estimate the polynomial transformation to rectify the image.
Parameters
----------
order : int
Order of the polynomial transformation.
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points overplotted. This argument is
optional.
"""
# protections
if self.x_inter_orig is None \
or self.y_inter_orig is None \
or self.x_inter_rect is None \
or self.y_inter_rect is None:
raise ValueError('Intersection points not computed')
npoints = len(self.x_inter_orig)
if len(self.y_inter_orig) != npoints \
or len(self.x_inter_rect) != npoints \
or len(self.y_inter_rect) != npoints:
raise ValueError('Unexpected different number of points')
# IMPORTANT: correct coordinates from origin in order to manipulate
# coordinates corresponding to image indices
x_inter_orig_shifted = self.x_inter_orig - self.bb_nc1_orig
y_inter_orig_shifted = self.y_inter_orig - self.bb_ns1_orig
x_inter_rect_shifted = self.x_inter_rect - self.bb_nc1_orig
y_inter_rect_shifted = self.y_inter_rect - self.bb_ns1_orig
# compute 2D transformation
self.ttd_order = order
self.ttd_aij, self.ttd_bij = compute_distortion(
x_inter_orig_shifted, y_inter_orig_shifted,
x_inter_rect_shifted, y_inter_rect_shifted,
order,
self.debugplot
)
self.tti_aij, self.tti_bij = compute_distortion(
x_inter_rect_shifted, y_inter_rect_shifted,
x_inter_orig_shifted, y_inter_orig_shifted,
order,
self.debugplot
)
# display slitlet with intersection points and grid indicating
# the fitted transformation
if abs(self.debugplot % 10) != 0 and slitlet2d is not None:
# display image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (estimate_tt_to_rectify)"
ax = ximshow(slitlet2d, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
# intersection points
ax.plot(self.x_inter_orig, self.y_inter_orig, 'co')
ax.plot(self.x_inter_rect, self.y_inter_rect, 'bo')
# grid with fitted transformation: spectrum trails
xx = np.arange(0, self.bb_nc2_orig - self.bb_nc1_orig + 1,
dtype=np.float)
for spectrail in self.list_spectrails:
yy0 = self.corr_yrect_a + \
self.corr_yrect_b * spectrail.y_rectified
yy = np.tile([yy0 - self.bb_ns1_orig], xx.size)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b")
xxx, yyy = fmap(self.ttd_order, self.ttd_aij, self.ttd_bij,
xx, yy)
ax.plot(xxx + self.bb_nc1_orig, yyy + self.bb_ns1_orig, "g")
# grid with fitted transformation: arc lines
ylower_line = \
self.list_spectrails[self.i_lower_spectrail].y_rectified
ylower_line = self.corr_yrect_a + self.corr_yrect_b * ylower_line
yupper_line = \
self.list_spectrails[self.i_upper_spectrail].y_rectified
yupper_line = self.corr_yrect_a + self.corr_yrect_b * yupper_line
n_points = int(yupper_line - ylower_line + 0.5) + 1
yy = np.linspace(ylower_line - self.bb_ns1_orig,
yupper_line - self.bb_ns1_orig,
num=n_points,
dtype=np.float)
for arc_line in self.list_arc_lines:
xline = arc_line.x_rectified - self.bb_nc1_orig
xx = np.array([xline] * n_points)
ax.plot(xx + self.bb_nc1_orig,yy + self.bb_ns1_orig, "b" )
xxx, yyy = fmap(self.ttd_order, self.ttd_aij, self.ttd_bij,
xx, yy)
ax.plot(xxx + self.bb_nc1_orig, yyy + self.bb_ns1_orig, "c")
# show plot
pause_debugplot(self.debugplot, pltshow=True) | python | def estimate_tt_to_rectify(self, order, slitlet2d=None):
"""Estimate the polynomial transformation to rectify the image.
Parameters
----------
order : int
Order of the polynomial transformation.
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points overplotted. This argument is
optional.
"""
# protections
if self.x_inter_orig is None \
or self.y_inter_orig is None \
or self.x_inter_rect is None \
or self.y_inter_rect is None:
raise ValueError('Intersection points not computed')
npoints = len(self.x_inter_orig)
if len(self.y_inter_orig) != npoints \
or len(self.x_inter_rect) != npoints \
or len(self.y_inter_rect) != npoints:
raise ValueError('Unexpected different number of points')
# IMPORTANT: correct coordinates from origin in order to manipulate
# coordinates corresponding to image indices
x_inter_orig_shifted = self.x_inter_orig - self.bb_nc1_orig
y_inter_orig_shifted = self.y_inter_orig - self.bb_ns1_orig
x_inter_rect_shifted = self.x_inter_rect - self.bb_nc1_orig
y_inter_rect_shifted = self.y_inter_rect - self.bb_ns1_orig
# compute 2D transformation
self.ttd_order = order
self.ttd_aij, self.ttd_bij = compute_distortion(
x_inter_orig_shifted, y_inter_orig_shifted,
x_inter_rect_shifted, y_inter_rect_shifted,
order,
self.debugplot
)
self.tti_aij, self.tti_bij = compute_distortion(
x_inter_rect_shifted, y_inter_rect_shifted,
x_inter_orig_shifted, y_inter_orig_shifted,
order,
self.debugplot
)
# display slitlet with intersection points and grid indicating
# the fitted transformation
if abs(self.debugplot % 10) != 0 and slitlet2d is not None:
# display image with zscale cuts
title = "Slitlet#" + str(self.islitlet) + \
" (estimate_tt_to_rectify)"
ax = ximshow(slitlet2d, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
# intersection points
ax.plot(self.x_inter_orig, self.y_inter_orig, 'co')
ax.plot(self.x_inter_rect, self.y_inter_rect, 'bo')
# grid with fitted transformation: spectrum trails
xx = np.arange(0, self.bb_nc2_orig - self.bb_nc1_orig + 1,
dtype=np.float)
for spectrail in self.list_spectrails:
yy0 = self.corr_yrect_a + \
self.corr_yrect_b * spectrail.y_rectified
yy = np.tile([yy0 - self.bb_ns1_orig], xx.size)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b")
xxx, yyy = fmap(self.ttd_order, self.ttd_aij, self.ttd_bij,
xx, yy)
ax.plot(xxx + self.bb_nc1_orig, yyy + self.bb_ns1_orig, "g")
# grid with fitted transformation: arc lines
ylower_line = \
self.list_spectrails[self.i_lower_spectrail].y_rectified
ylower_line = self.corr_yrect_a + self.corr_yrect_b * ylower_line
yupper_line = \
self.list_spectrails[self.i_upper_spectrail].y_rectified
yupper_line = self.corr_yrect_a + self.corr_yrect_b * yupper_line
n_points = int(yupper_line - ylower_line + 0.5) + 1
yy = np.linspace(ylower_line - self.bb_ns1_orig,
yupper_line - self.bb_ns1_orig,
num=n_points,
dtype=np.float)
for arc_line in self.list_arc_lines:
xline = arc_line.x_rectified - self.bb_nc1_orig
xx = np.array([xline] * n_points)
ax.plot(xx + self.bb_nc1_orig,yy + self.bb_ns1_orig, "b" )
xxx, yyy = fmap(self.ttd_order, self.ttd_aij, self.ttd_bij,
xx, yy)
ax.plot(xxx + self.bb_nc1_orig, yyy + self.bb_ns1_orig, "c")
# show plot
pause_debugplot(self.debugplot, pltshow=True) | [
"def",
"estimate_tt_to_rectify",
"(",
"self",
",",
"order",
",",
"slitlet2d",
"=",
"None",
")",
":",
"# protections",
"if",
"self",
".",
"x_inter_orig",
"is",
"None",
"or",
"self",
".",
"y_inter_orig",
"is",
"None",
"or",
"self",
".",
"x_inter_rect",
"is",
... | Estimate the polynomial transformation to rectify the image.
Parameters
----------
order : int
Order of the polynomial transformation.
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points overplotted. This argument is
optional. | [
"Estimate",
"the",
"polynomial",
"transformation",
"to",
"rectify",
"the",
"image",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L950-L1042 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.rectify | def rectify(self, slitlet2d, resampling, transformation, inverse=False):
"""Rectify slitlet using computed transformation.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
resampling : int
1: nearest neighbour, 2: flux preserving interpolation.
transformation : int
1: initial, 2: modeled
inverse : bool
If true, the inverse rectification transformation is
employed.
Returns
-------
slitlet2d_rect : numpy array
Rectified slitlet image.
"""
if resampling not in [1, 2]:
raise ValueError("Unexpected resampling value=" + str(resampling))
if transformation not in [1, 2]:
raise ValueError("Unexpected transformation value=" +
str(transformation))
# verify image dimension
naxis2, naxis1 = slitlet2d.shape
if naxis1 != self.bb_nc2_orig - self.bb_nc1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis1")
if naxis2 != self.bb_ns2_orig - self.bb_ns1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis2")
# transformation to be employed (and direction)
if transformation == 1:
if inverse:
aij = self.tti_aij
bij = self.tti_bij
else:
aij = self.ttd_aij
bij = self.ttd_bij
else:
if inverse:
aij = self.tti_aij_longslit_model
bij = self.tti_bij_longslit_model
else:
aij = self.ttd_aij_longslit_model
bij = self.ttd_bij_longslit_model
# rectify image
slitlet2d_rect = rectify2d(
image2d=slitlet2d,
aij=aij,
bij=bij,
resampling=resampling
)
if abs(self.debugplot % 10) != 0:
title = "Slitlet#" + str(self.islitlet) + " (rectify)"
ax = ximshow(slitlet2d_rect, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
if self.list_arc_lines is not None:
# intersection points
ax.plot(self.x_inter_rect, self.y_inter_rect, 'bo')
# grid with fitted transformation: spectrum trails
xx = np.arange(0, self.bb_nc2_orig - self.bb_nc1_orig + 1,
dtype=np.float)
for spectrail in self.list_spectrails:
yy0 = self.corr_yrect_a + \
self.corr_yrect_b * spectrail.y_rectified
yy = np.tile([yy0 - self.bb_ns1_orig], xx.size)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b")
for spectrail in self.list_frontiers:
yy0 = self.corr_yrect_a + \
self.corr_yrect_b * spectrail.y_rectified
yy = np.tile([yy0 - self.bb_ns1_orig], xx.size)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b:")
# grid with fitted transformation: arc lines
ylower_line = \
self.list_spectrails[self.i_lower_spectrail].y_rectified
ylower_line = self.corr_yrect_a + self.corr_yrect_b * ylower_line
yupper_line = \
self.list_spectrails[self.i_upper_spectrail].y_rectified
yupper_line = self.corr_yrect_a + self.corr_yrect_b * yupper_line
n_points = int(yupper_line - ylower_line + 0.5) + 1
yy = np.linspace(ylower_line - self.bb_ns1_orig,
yupper_line - self.bb_ns1_orig,
num=n_points,
dtype=np.float)
if self.list_arc_lines is not None:
for arc_line in self.list_arc_lines:
xline = arc_line.x_rectified - self.bb_nc1_orig
xx = np.array([xline] * n_points)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b")
# show plot
pause_debugplot(self.debugplot, pltshow=True)
return slitlet2d_rect | python | def rectify(self, slitlet2d, resampling, transformation, inverse=False):
"""Rectify slitlet using computed transformation.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
resampling : int
1: nearest neighbour, 2: flux preserving interpolation.
transformation : int
1: initial, 2: modeled
inverse : bool
If true, the inverse rectification transformation is
employed.
Returns
-------
slitlet2d_rect : numpy array
Rectified slitlet image.
"""
if resampling not in [1, 2]:
raise ValueError("Unexpected resampling value=" + str(resampling))
if transformation not in [1, 2]:
raise ValueError("Unexpected transformation value=" +
str(transformation))
# verify image dimension
naxis2, naxis1 = slitlet2d.shape
if naxis1 != self.bb_nc2_orig - self.bb_nc1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis1")
if naxis2 != self.bb_ns2_orig - self.bb_ns1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis2")
# transformation to be employed (and direction)
if transformation == 1:
if inverse:
aij = self.tti_aij
bij = self.tti_bij
else:
aij = self.ttd_aij
bij = self.ttd_bij
else:
if inverse:
aij = self.tti_aij_longslit_model
bij = self.tti_bij_longslit_model
else:
aij = self.ttd_aij_longslit_model
bij = self.ttd_bij_longslit_model
# rectify image
slitlet2d_rect = rectify2d(
image2d=slitlet2d,
aij=aij,
bij=bij,
resampling=resampling
)
if abs(self.debugplot % 10) != 0:
title = "Slitlet#" + str(self.islitlet) + " (rectify)"
ax = ximshow(slitlet2d_rect, title=title,
first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
show=False)
if self.list_arc_lines is not None:
# intersection points
ax.plot(self.x_inter_rect, self.y_inter_rect, 'bo')
# grid with fitted transformation: spectrum trails
xx = np.arange(0, self.bb_nc2_orig - self.bb_nc1_orig + 1,
dtype=np.float)
for spectrail in self.list_spectrails:
yy0 = self.corr_yrect_a + \
self.corr_yrect_b * spectrail.y_rectified
yy = np.tile([yy0 - self.bb_ns1_orig], xx.size)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b")
for spectrail in self.list_frontiers:
yy0 = self.corr_yrect_a + \
self.corr_yrect_b * spectrail.y_rectified
yy = np.tile([yy0 - self.bb_ns1_orig], xx.size)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b:")
# grid with fitted transformation: arc lines
ylower_line = \
self.list_spectrails[self.i_lower_spectrail].y_rectified
ylower_line = self.corr_yrect_a + self.corr_yrect_b * ylower_line
yupper_line = \
self.list_spectrails[self.i_upper_spectrail].y_rectified
yupper_line = self.corr_yrect_a + self.corr_yrect_b * yupper_line
n_points = int(yupper_line - ylower_line + 0.5) + 1
yy = np.linspace(ylower_line - self.bb_ns1_orig,
yupper_line - self.bb_ns1_orig,
num=n_points,
dtype=np.float)
if self.list_arc_lines is not None:
for arc_line in self.list_arc_lines:
xline = arc_line.x_rectified - self.bb_nc1_orig
xx = np.array([xline] * n_points)
ax.plot(xx + self.bb_nc1_orig, yy + self.bb_ns1_orig, "b")
# show plot
pause_debugplot(self.debugplot, pltshow=True)
return slitlet2d_rect | [
"def",
"rectify",
"(",
"self",
",",
"slitlet2d",
",",
"resampling",
",",
"transformation",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"resampling",
"not",
"in",
"[",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unexpected resampling value=\"",
... | Rectify slitlet using computed transformation.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
resampling : int
1: nearest neighbour, 2: flux preserving interpolation.
transformation : int
1: initial, 2: modeled
inverse : bool
If true, the inverse rectification transformation is
employed.
Returns
-------
slitlet2d_rect : numpy array
Rectified slitlet image. | [
"Rectify",
"slitlet",
"using",
"computed",
"transformation",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L1044-L1145 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.median_spectrum_from_rectified_image | def median_spectrum_from_rectified_image(self, slitlet2d_rect,
sigma_gaussian_filtering=0,
nwinwidth_initial=5,
nwinwidth_refined=7,
times_sigma_threshold=5,
minimum_threshold=None,
npix_avoid_border=0,
nbrightlines=None):
"""Median spectrum and line peaks from rectified image.
In order to avoid the line ghosts, the line peaks are identified
independently in the upper and lower halves of the rectified
image. The final peaks correspond to lines that appear in both
spectra.
Parameters
----------
slitlet2d_rect : numpy array
Rectified slitlet image.
sigma_gaussian_filtering : float
Sigma of the gaussian filter to be applied to the spectrum
in order to avoid problems with saturated lines. This
filtering is skipped when this parameter is <= 0.
nwinwidth_initial : int
Width of the window where each peak must be found using
the initial method (approximate)
nwinwidth_refined : int
Width of the window where each peak location will be
refined.
times_sigma_threshold : float
Times (robust) sigma above the median of the image to set
the minimum threshold when searching for line peaks.
minimum_threshold : float or None
Minimum value of the threshold.
npix_avoid_border : int
Number of pixels at the borders of the spectrum where peaks
are not considered. If zero, the actual number will be
given by nwinwidth_initial.
nbrightlines : list
List with maximum number of brightest lines to be employed
in the wavelength calibration. The length of the list
indicates the number of equal-size subintervals in the
wavelength calibration direction to be considered.
If this value is [0] or None, all the detected lines will be
employed.
Returns
-------
sp0 : numpy array
Median spectrum.
fxpeaks : numpy array
Refined location of arc lines (in array index scale).
"""
# protections
naxis2, naxis1 = slitlet2d_rect.shape
if naxis1 != self.bb_nc2_orig - self.bb_nc1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis1")
if naxis2 != self.bb_ns2_orig - self.bb_ns1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis2")
# lower, middle and upper spectrum trails
ylower_line = \
self.list_spectrails[self.i_lower_spectrail].y_rectified
ymiddle_line = \
self.list_spectrails[self.i_middle_spectrail].y_rectified
yupper_line = \
self.list_spectrails[self.i_upper_spectrail].y_rectified
ilower = int(ylower_line + 0.5) - self.bb_ns1_orig
imiddle = int(ymiddle_line + 0.5) - self.bb_ns1_orig
iupper = int(yupper_line + 0.5) - self.bb_ns1_orig
# median spectra using different image regions
sp0_ini = np.median(slitlet2d_rect[ilower:(iupper + 1), :], axis=0)
sp1_ini = np.median(slitlet2d_rect[ilower:(imiddle + 1), :], axis=0)
sp2_ini = np.median(slitlet2d_rect[imiddle:(iupper + 1), :], axis=0)
# gaussian filtering when requested (to avoid line saturation)
if sigma_gaussian_filtering > 0:
sp0 = ndimage.filters.gaussian_filter(
sp0_ini,
sigma=sigma_gaussian_filtering
)
sp1 = ndimage.filters.gaussian_filter(
sp1_ini,
sigma=sigma_gaussian_filtering
)
sp2 = ndimage.filters.gaussian_filter(
sp2_ini,
sigma=sigma_gaussian_filtering
)
else:
sp0 = np.copy(sp0_ini)
sp1 = np.copy(sp1_ini)
sp2 = np.copy(sp2_ini)
# compute threshold
q25, q50, q75 = np.percentile(sp0, q=[25.0, 50.0, 75.0])
sigma_g = 0.7413 * (q75 - q25) # robust standard deviation
threshold = q50 + times_sigma_threshold * sigma_g
if abs(self.debugplot) >= 10:
print("median...........:", q50)
print("robuts std.......:", sigma_g)
print("threshold........:", threshold)
if minimum_threshold is not None:
if minimum_threshold > threshold:
threshold = minimum_threshold
if abs(self.debugplot) >= 10:
print("minimum threshold:", minimum_threshold)
print("final threshold..:", threshold)
# initial location of the peaks (integer values)
ixpeaks0 = find_peaks_spectrum(sp0, nwinwidth=nwinwidth_initial,
threshold=threshold,
debugplot=self.debugplot)
# peaks in the lower and upper regions
ixpeaks1 = find_peaks_spectrum(sp1, nwinwidth=nwinwidth_initial,
threshold=threshold,
debugplot=self.debugplot)
ixpeaks2 = find_peaks_spectrum(sp2, nwinwidth=nwinwidth_initial,
threshold=threshold,
debugplot=self.debugplot)
# the peaks are valid if the are also found in the lower and
# upper regions (with a tolerance of +1 or -1 pixel)
ixpeaks = []
for ixpeak in ixpeaks0:
l1 = ixpeak in np.concatenate((ixpeaks1, ixpeaks1+1, ixpeaks1-1))
l2 = ixpeak in np.concatenate((ixpeaks2, ixpeaks2+1, ixpeaks2-1))
if l1 and l2:
ixpeaks.append(ixpeak)
ixpeaks = np.array(ixpeaks)
if abs(self.debugplot) >= 10:
print("Merged initial list of peaks:\n", ixpeaks)
# remove peaks too close to any of the borders of the spectrum
if npix_avoid_border > 0:
lok_ini = ixpeaks >= npix_avoid_border
lok_end = ixpeaks <= len(sp0) - 1 - npix_avoid_border
ixpeaks = ixpeaks[lok_ini * lok_end]
# select a maximum number of brightest lines in each region
if nbrightlines is None:
pass
elif len(nbrightlines) == 1 and nbrightlines[0] == 0:
pass
else:
if abs(self.debugplot) >= 10:
print('nbrightlines =', nbrightlines)
print('ixpeaks in whole spectrum:\n', ixpeaks)
region_size = (naxis1-1)/len(nbrightlines)
ixpeaks_filtered = np.array([], dtype=int)
for iregion, nlines_in_region in enumerate(nbrightlines):
if nlines_in_region > 0:
imin = int(iregion * region_size)
imax = int((iregion + 1) * region_size)
if iregion > 0:
imin += 1
ixpeaks_region = \
ixpeaks[np.logical_and(ixpeaks >= imin,
ixpeaks <= imax)]
if len(ixpeaks_region) > 0:
peak_fluxes = sp0[ixpeaks_region]
spos = peak_fluxes.argsort()
ixpeaks_tmp = ixpeaks_region[spos[-nlines_in_region:]]
ixpeaks_tmp.sort() # in-place sort
if abs(self.debugplot) >= 10:
print('ixpeaks in region........:\n', ixpeaks_tmp)
ixpeaks_filtered = np.concatenate((ixpeaks_filtered,
ixpeaks_tmp))
ixpeaks = ixpeaks_filtered
if abs(self.debugplot) >= 10:
print('ixpeaks filtered.........:\n', ixpeaks)
# refined location of the peaks (float values)
fxpeaks, sxpeaks = refine_peaks_spectrum(sp0, ixpeaks,
nwinwidth=nwinwidth_refined,
method="gaussian")
if abs(self.debugplot) % 10 != 0:
x = np.arange(self.bb_nc1_orig, self.bb_nc2_orig + 1)
title = "Slitlet#" + str(self.islitlet) + " (median spectrum)"
ax = ximplotxy(x, sp1, show=False, title=title,
xlabel='pixel coordinate (from 1 to NAXIS1)',
ylabel='number of counts',
**{'marker': ' ', 'label': 'lower region'})
ax.plot(x, sp2, label='upper region')
ax.plot(x, sp0, label='whole region')
# mark peak location
ax.plot(ixpeaks + self.bb_nc1_orig,
sp0[ixpeaks], 'o', label="initial location")
ax.plot(fxpeaks + self.bb_nc1_orig,
sp0[ixpeaks], 'o', label="refined location")
ax.legend()
pause_debugplot(self.debugplot, pltshow=True, tight_layout=False)
# return median spectrum and refined peak location
return sp0, fxpeaks | python | def median_spectrum_from_rectified_image(self, slitlet2d_rect,
sigma_gaussian_filtering=0,
nwinwidth_initial=5,
nwinwidth_refined=7,
times_sigma_threshold=5,
minimum_threshold=None,
npix_avoid_border=0,
nbrightlines=None):
"""Median spectrum and line peaks from rectified image.
In order to avoid the line ghosts, the line peaks are identified
independently in the upper and lower halves of the rectified
image. The final peaks correspond to lines that appear in both
spectra.
Parameters
----------
slitlet2d_rect : numpy array
Rectified slitlet image.
sigma_gaussian_filtering : float
Sigma of the gaussian filter to be applied to the spectrum
in order to avoid problems with saturated lines. This
filtering is skipped when this parameter is <= 0.
nwinwidth_initial : int
Width of the window where each peak must be found using
the initial method (approximate)
nwinwidth_refined : int
Width of the window where each peak location will be
refined.
times_sigma_threshold : float
Times (robust) sigma above the median of the image to set
the minimum threshold when searching for line peaks.
minimum_threshold : float or None
Minimum value of the threshold.
npix_avoid_border : int
Number of pixels at the borders of the spectrum where peaks
are not considered. If zero, the actual number will be
given by nwinwidth_initial.
nbrightlines : list
List with maximum number of brightest lines to be employed
in the wavelength calibration. The length of the list
indicates the number of equal-size subintervals in the
wavelength calibration direction to be considered.
If this value is [0] or None, all the detected lines will be
employed.
Returns
-------
sp0 : numpy array
Median spectrum.
fxpeaks : numpy array
Refined location of arc lines (in array index scale).
"""
# protections
naxis2, naxis1 = slitlet2d_rect.shape
if naxis1 != self.bb_nc2_orig - self.bb_nc1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis1")
if naxis2 != self.bb_ns2_orig - self.bb_ns1_orig + 1:
raise ValueError("Unexpected slitlet2d_rect naxis2")
# lower, middle and upper spectrum trails
ylower_line = \
self.list_spectrails[self.i_lower_spectrail].y_rectified
ymiddle_line = \
self.list_spectrails[self.i_middle_spectrail].y_rectified
yupper_line = \
self.list_spectrails[self.i_upper_spectrail].y_rectified
ilower = int(ylower_line + 0.5) - self.bb_ns1_orig
imiddle = int(ymiddle_line + 0.5) - self.bb_ns1_orig
iupper = int(yupper_line + 0.5) - self.bb_ns1_orig
# median spectra using different image regions
sp0_ini = np.median(slitlet2d_rect[ilower:(iupper + 1), :], axis=0)
sp1_ini = np.median(slitlet2d_rect[ilower:(imiddle + 1), :], axis=0)
sp2_ini = np.median(slitlet2d_rect[imiddle:(iupper + 1), :], axis=0)
# gaussian filtering when requested (to avoid line saturation)
if sigma_gaussian_filtering > 0:
sp0 = ndimage.filters.gaussian_filter(
sp0_ini,
sigma=sigma_gaussian_filtering
)
sp1 = ndimage.filters.gaussian_filter(
sp1_ini,
sigma=sigma_gaussian_filtering
)
sp2 = ndimage.filters.gaussian_filter(
sp2_ini,
sigma=sigma_gaussian_filtering
)
else:
sp0 = np.copy(sp0_ini)
sp1 = np.copy(sp1_ini)
sp2 = np.copy(sp2_ini)
# compute threshold
q25, q50, q75 = np.percentile(sp0, q=[25.0, 50.0, 75.0])
sigma_g = 0.7413 * (q75 - q25) # robust standard deviation
threshold = q50 + times_sigma_threshold * sigma_g
if abs(self.debugplot) >= 10:
print("median...........:", q50)
print("robuts std.......:", sigma_g)
print("threshold........:", threshold)
if minimum_threshold is not None:
if minimum_threshold > threshold:
threshold = minimum_threshold
if abs(self.debugplot) >= 10:
print("minimum threshold:", minimum_threshold)
print("final threshold..:", threshold)
# initial location of the peaks (integer values)
ixpeaks0 = find_peaks_spectrum(sp0, nwinwidth=nwinwidth_initial,
threshold=threshold,
debugplot=self.debugplot)
# peaks in the lower and upper regions
ixpeaks1 = find_peaks_spectrum(sp1, nwinwidth=nwinwidth_initial,
threshold=threshold,
debugplot=self.debugplot)
ixpeaks2 = find_peaks_spectrum(sp2, nwinwidth=nwinwidth_initial,
threshold=threshold,
debugplot=self.debugplot)
# the peaks are valid if the are also found in the lower and
# upper regions (with a tolerance of +1 or -1 pixel)
ixpeaks = []
for ixpeak in ixpeaks0:
l1 = ixpeak in np.concatenate((ixpeaks1, ixpeaks1+1, ixpeaks1-1))
l2 = ixpeak in np.concatenate((ixpeaks2, ixpeaks2+1, ixpeaks2-1))
if l1 and l2:
ixpeaks.append(ixpeak)
ixpeaks = np.array(ixpeaks)
if abs(self.debugplot) >= 10:
print("Merged initial list of peaks:\n", ixpeaks)
# remove peaks too close to any of the borders of the spectrum
if npix_avoid_border > 0:
lok_ini = ixpeaks >= npix_avoid_border
lok_end = ixpeaks <= len(sp0) - 1 - npix_avoid_border
ixpeaks = ixpeaks[lok_ini * lok_end]
# select a maximum number of brightest lines in each region
if nbrightlines is None:
pass
elif len(nbrightlines) == 1 and nbrightlines[0] == 0:
pass
else:
if abs(self.debugplot) >= 10:
print('nbrightlines =', nbrightlines)
print('ixpeaks in whole spectrum:\n', ixpeaks)
region_size = (naxis1-1)/len(nbrightlines)
ixpeaks_filtered = np.array([], dtype=int)
for iregion, nlines_in_region in enumerate(nbrightlines):
if nlines_in_region > 0:
imin = int(iregion * region_size)
imax = int((iregion + 1) * region_size)
if iregion > 0:
imin += 1
ixpeaks_region = \
ixpeaks[np.logical_and(ixpeaks >= imin,
ixpeaks <= imax)]
if len(ixpeaks_region) > 0:
peak_fluxes = sp0[ixpeaks_region]
spos = peak_fluxes.argsort()
ixpeaks_tmp = ixpeaks_region[spos[-nlines_in_region:]]
ixpeaks_tmp.sort() # in-place sort
if abs(self.debugplot) >= 10:
print('ixpeaks in region........:\n', ixpeaks_tmp)
ixpeaks_filtered = np.concatenate((ixpeaks_filtered,
ixpeaks_tmp))
ixpeaks = ixpeaks_filtered
if abs(self.debugplot) >= 10:
print('ixpeaks filtered.........:\n', ixpeaks)
# refined location of the peaks (float values)
fxpeaks, sxpeaks = refine_peaks_spectrum(sp0, ixpeaks,
nwinwidth=nwinwidth_refined,
method="gaussian")
if abs(self.debugplot) % 10 != 0:
x = np.arange(self.bb_nc1_orig, self.bb_nc2_orig + 1)
title = "Slitlet#" + str(self.islitlet) + " (median spectrum)"
ax = ximplotxy(x, sp1, show=False, title=title,
xlabel='pixel coordinate (from 1 to NAXIS1)',
ylabel='number of counts',
**{'marker': ' ', 'label': 'lower region'})
ax.plot(x, sp2, label='upper region')
ax.plot(x, sp0, label='whole region')
# mark peak location
ax.plot(ixpeaks + self.bb_nc1_orig,
sp0[ixpeaks], 'o', label="initial location")
ax.plot(fxpeaks + self.bb_nc1_orig,
sp0[ixpeaks], 'o', label="refined location")
ax.legend()
pause_debugplot(self.debugplot, pltshow=True, tight_layout=False)
# return median spectrum and refined peak location
return sp0, fxpeaks | [
"def",
"median_spectrum_from_rectified_image",
"(",
"self",
",",
"slitlet2d_rect",
",",
"sigma_gaussian_filtering",
"=",
"0",
",",
"nwinwidth_initial",
"=",
"5",
",",
"nwinwidth_refined",
"=",
"7",
",",
"times_sigma_threshold",
"=",
"5",
",",
"minimum_threshold",
"=",... | Median spectrum and line peaks from rectified image.
In order to avoid the line ghosts, the line peaks are identified
independently in the upper and lower halves of the rectified
image. The final peaks correspond to lines that appear in both
spectra.
Parameters
----------
slitlet2d_rect : numpy array
Rectified slitlet image.
sigma_gaussian_filtering : float
Sigma of the gaussian filter to be applied to the spectrum
in order to avoid problems with saturated lines. This
filtering is skipped when this parameter is <= 0.
nwinwidth_initial : int
Width of the window where each peak must be found using
the initial method (approximate)
nwinwidth_refined : int
Width of the window where each peak location will be
refined.
times_sigma_threshold : float
Times (robust) sigma above the median of the image to set
the minimum threshold when searching for line peaks.
minimum_threshold : float or None
Minimum value of the threshold.
npix_avoid_border : int
Number of pixels at the borders of the spectrum where peaks
are not considered. If zero, the actual number will be
given by nwinwidth_initial.
nbrightlines : list
List with maximum number of brightest lines to be employed
in the wavelength calibration. The length of the list
indicates the number of equal-size subintervals in the
wavelength calibration direction to be considered.
If this value is [0] or None, all the detected lines will be
employed.
Returns
-------
sp0 : numpy array
Median spectrum.
fxpeaks : numpy array
Refined location of arc lines (in array index scale). | [
"Median",
"spectrum",
"and",
"line",
"peaks",
"from",
"rectified",
"image",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L1147-L1347 |
guaix-ucm/pyemir | emirdrp/recipes/image/shared.py | intersection | def intersection(a, b, scale=1):
'''Intersection between two segments.'''
try:
a1, a2 = a
except TypeError:
a1 = a.start
a2 = a.stop
try:
b1, b2 = b
except TypeError:
b1 = b.start
b2 = b.stop
if a2 <= b1:
return None
if a1 >= b2:
return None
# a2 > b1 and a1 < b2
if a2 <= b2:
if a1 <= b1:
return slice(b1 * scale, a2 * scale)
else:
return slice(a1 * scale, a2 * scale)
else:
if a1 <= b1:
return slice(b1 * scale, b2 * scale)
else:
return slice(a1 * scale, b2 * scale) | python | def intersection(a, b, scale=1):
'''Intersection between two segments.'''
try:
a1, a2 = a
except TypeError:
a1 = a.start
a2 = a.stop
try:
b1, b2 = b
except TypeError:
b1 = b.start
b2 = b.stop
if a2 <= b1:
return None
if a1 >= b2:
return None
# a2 > b1 and a1 < b2
if a2 <= b2:
if a1 <= b1:
return slice(b1 * scale, a2 * scale)
else:
return slice(a1 * scale, a2 * scale)
else:
if a1 <= b1:
return slice(b1 * scale, b2 * scale)
else:
return slice(a1 * scale, b2 * scale) | [
"def",
"intersection",
"(",
"a",
",",
"b",
",",
"scale",
"=",
"1",
")",
":",
"try",
":",
"a1",
",",
"a2",
"=",
"a",
"except",
"TypeError",
":",
"a1",
"=",
"a",
".",
"start",
"a2",
"=",
"a",
".",
"stop",
"try",
":",
"b1",
",",
"b2",
"=",
"b"... | Intersection between two segments. | [
"Intersection",
"between",
"two",
"segments",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/image/shared.py#L67-L97 |
guaix-ucm/pyemir | emirdrp/recipes/image/shared.py | clip_slices | def clip_slices(r, region, scale=1):
'''Intersect slices with a region.'''
t = []
for ch in r:
a1 = intersection(ch[0], region[0], scale=scale)
if a1 is None:
continue
a2 = intersection(ch[1], region[1], scale=scale)
if a2 is None:
continue
t.append((a1, a2))
return t | python | def clip_slices(r, region, scale=1):
'''Intersect slices with a region.'''
t = []
for ch in r:
a1 = intersection(ch[0], region[0], scale=scale)
if a1 is None:
continue
a2 = intersection(ch[1], region[1], scale=scale)
if a2 is None:
continue
t.append((a1, a2))
return t | [
"def",
"clip_slices",
"(",
"r",
",",
"region",
",",
"scale",
"=",
"1",
")",
":",
"t",
"=",
"[",
"]",
"for",
"ch",
"in",
"r",
":",
"a1",
"=",
"intersection",
"(",
"ch",
"[",
"0",
"]",
",",
"region",
"[",
"0",
"]",
",",
"scale",
"=",
"scale",
... | Intersect slices with a region. | [
"Intersect",
"slices",
"with",
"a",
"region",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/image/shared.py#L100-L113 |
guaix-ucm/pyemir | emirdrp/recipes/image/join.py | JoinDitheredImagesRecipe.set_base_headers | def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr)
hdr['IMGOBBL'] = 0
hdr['OBSMODE'] = 'DITHERED_IMAGE'
return hdr | python | def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr)
hdr['IMGOBBL'] = 0
hdr['OBSMODE'] = 'DITHERED_IMAGE'
return hdr | [
"def",
"set_base_headers",
"(",
"self",
",",
"hdr",
")",
":",
"hdr",
"=",
"super",
"(",
"JoinDitheredImagesRecipe",
",",
"self",
")",
".",
"set_base_headers",
"(",
"hdr",
")",
"hdr",
"[",
"'IMGOBBL'",
"]",
"=",
"0",
"hdr",
"[",
"'OBSMODE'",
"]",
"=",
"... | Set metadata in FITS headers. | [
"Set",
"metadata",
"in",
"FITS",
"headers",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/image/join.py#L338-L343 |
BeyondTheClouds/enoslib | enoslib/api.py | _load_defaults | def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None,
basedir=False):
"""Load common defaults data structures.
For factorization purpose."""
extra_vars = extra_vars or {}
tags = tags or []
loader = DataLoader()
if basedir:
loader.set_basedir(basedir)
inventory = EnosInventory(loader=loader,
sources=inventory_path, roles=roles)
variable_manager = VariableManager(loader=loader,
inventory=inventory)
# seems mandatory to load group_vars variable
if basedir:
variable_manager.safe_basedir = True
if extra_vars:
variable_manager.extra_vars = extra_vars
# NOTE(msimonin): The ansible api is "low level" in the
# sense that we are redefining here all the default values
# that are usually enforce by ansible called from the cli
Options = namedtuple("Options", ["listtags", "listtasks",
"listhosts", "syntax",
"connection", "module_path",
"forks", "private_key_file",
"ssh_common_args",
"ssh_extra_args",
"sftp_extra_args",
"scp_extra_args", "become",
"become_method", "become_user",
"remote_user", "verbosity",
"check", "tags",
"diff", "basedir"])
options = Options(listtags=False, listtasks=False,
listhosts=False, syntax=False, connection="ssh",
module_path=None, forks=100,
private_key_file=None, ssh_common_args=None,
ssh_extra_args=None, sftp_extra_args=None,
scp_extra_args=None, become=None,
become_method="sudo", become_user="root",
remote_user=None, verbosity=2, check=False,
tags=tags, diff=None, basedir=basedir)
return inventory, variable_manager, loader, options | python | def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None,
basedir=False):
"""Load common defaults data structures.
For factorization purpose."""
extra_vars = extra_vars or {}
tags = tags or []
loader = DataLoader()
if basedir:
loader.set_basedir(basedir)
inventory = EnosInventory(loader=loader,
sources=inventory_path, roles=roles)
variable_manager = VariableManager(loader=loader,
inventory=inventory)
# seems mandatory to load group_vars variable
if basedir:
variable_manager.safe_basedir = True
if extra_vars:
variable_manager.extra_vars = extra_vars
# NOTE(msimonin): The ansible api is "low level" in the
# sense that we are redefining here all the default values
# that are usually enforce by ansible called from the cli
Options = namedtuple("Options", ["listtags", "listtasks",
"listhosts", "syntax",
"connection", "module_path",
"forks", "private_key_file",
"ssh_common_args",
"ssh_extra_args",
"sftp_extra_args",
"scp_extra_args", "become",
"become_method", "become_user",
"remote_user", "verbosity",
"check", "tags",
"diff", "basedir"])
options = Options(listtags=False, listtasks=False,
listhosts=False, syntax=False, connection="ssh",
module_path=None, forks=100,
private_key_file=None, ssh_common_args=None,
ssh_extra_args=None, sftp_extra_args=None,
scp_extra_args=None, become=None,
become_method="sudo", become_user="root",
remote_user=None, verbosity=2, check=False,
tags=tags, diff=None, basedir=basedir)
return inventory, variable_manager, loader, options | [
"def",
"_load_defaults",
"(",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"basedir",
"=",
"False",
")",
":",
"extra_vars",
"=",
"extra_vars",
"or",
"{",
"}",
"tags",
"=",
"tag... | Load common defaults data structures.
For factorization purpose. | [
"Load",
"common",
"defaults",
"data",
"structures",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L45-L96 |
BeyondTheClouds/enoslib | enoslib/api.py | run_play | def run_play(play_source, inventory_path=None, roles=None,
extra_vars=None, on_error_continue=False):
"""Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict): ansible task
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
Returns:
List of all the results
"""
# NOTE(msimonin): inventory could be infered from a host list (maybe)
results = []
inventory, variable_manager, loader, options = _load_defaults(
inventory_path=inventory_path,
roles=roles,
extra_vars=extra_vars)
callback = _MyCallback(results)
passwords = {}
tqm = task_queue_manager.TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=callback)
# create play
play_inst = play.Play().load(play_source,
variable_manager=variable_manager,
loader=loader)
# actually run it
try:
tqm.run(play_inst)
finally:
tqm.cleanup()
# Handling errors
failed_hosts = []
unreachable_hosts = []
for r in results:
if r.status == STATUS_UNREACHABLE:
unreachable_hosts.append(r)
if r.status == STATUS_FAILED:
failed_hosts.append(r)
if len(failed_hosts) > 0:
logger.error("Failed hosts: %s" % failed_hosts)
if not on_error_continue:
raise EnosFailedHostsError(failed_hosts)
if len(unreachable_hosts) > 0:
logger.error("Unreachable hosts: %s" % unreachable_hosts)
if not on_error_continue:
raise EnosUnreachableHostsError(unreachable_hosts)
return results | python | def run_play(play_source, inventory_path=None, roles=None,
extra_vars=None, on_error_continue=False):
"""Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict): ansible task
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
Returns:
List of all the results
"""
# NOTE(msimonin): inventory could be infered from a host list (maybe)
results = []
inventory, variable_manager, loader, options = _load_defaults(
inventory_path=inventory_path,
roles=roles,
extra_vars=extra_vars)
callback = _MyCallback(results)
passwords = {}
tqm = task_queue_manager.TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=callback)
# create play
play_inst = play.Play().load(play_source,
variable_manager=variable_manager,
loader=loader)
# actually run it
try:
tqm.run(play_inst)
finally:
tqm.cleanup()
# Handling errors
failed_hosts = []
unreachable_hosts = []
for r in results:
if r.status == STATUS_UNREACHABLE:
unreachable_hosts.append(r)
if r.status == STATUS_FAILED:
failed_hosts.append(r)
if len(failed_hosts) > 0:
logger.error("Failed hosts: %s" % failed_hosts)
if not on_error_continue:
raise EnosFailedHostsError(failed_hosts)
if len(unreachable_hosts) > 0:
logger.error("Unreachable hosts: %s" % unreachable_hosts)
if not on_error_continue:
raise EnosUnreachableHostsError(unreachable_hosts)
return results | [
"def",
"run_play",
"(",
"play_source",
",",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"on_error_continue",
"=",
"False",
")",
":",
"# NOTE(msimonin): inventory could be infered from a host list (maybe)",
"results",
... | Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict): ansible task
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
Returns:
List of all the results | [
"Run",
"a",
"play",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L135-L202 |
BeyondTheClouds/enoslib | enoslib/api.py | run_command | def run_command(pattern_hosts, command, inventory_path=None, roles=None,
extra_vars=None,
on_error_continue=False):
"""Run a shell command on some remote hosts.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
command (str): the command to run
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
Returns:
Dict combining the stdout and stderr of ok and failed hosts and every
results of tasks executed (this may include the fact gathering tasks)
Example:
.. code-block:: python
# Inventory
[control1]
enos-0
[control2]
enos-1
# Python
result = run_command("control*", "date", inventory)
# Result
{
'failed': {},
'ok':
{
u'enos-0':
{
'stderr': u'',
'stdout': u'Tue Oct 31 04:53:04 GMT 2017'
},
u'enos-1':
{
'stderr': u'',
'stdout': u'Tue Oct 31 04:53:05 GMT 2017'}
},
'results': [...]
}
If facts are gathers this is possible to use ansible templating
.. code-block:: python
result = run_command("control*", "ping -c 1
{{hostvars['enos-1']['ansible_' + n1].ipv4.address}}", inventory)
"""
def filter_results(results, status):
_r = [r for r in results
if r.status == status and r.task == COMMAND_NAME]
s = dict([[r.host, {"stdout": r.payload.get("stdout"),
"stderr": r.payload.get("stderr")}]
for r in _r])
return s
play_source = {
"hosts": pattern_hosts,
"tasks": [{
"name": COMMAND_NAME,
"shell": command,
}]
}
results = run_play(play_source,
inventory_path=inventory_path,
roles=roles,
extra_vars=extra_vars)
ok = filter_results(results, STATUS_OK)
failed = filter_results(results, STATUS_FAILED)
return {"ok": ok, "failed": failed, "results": results} | python | def run_command(pattern_hosts, command, inventory_path=None, roles=None,
extra_vars=None,
on_error_continue=False):
"""Run a shell command on some remote hosts.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
command (str): the command to run
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
Returns:
Dict combining the stdout and stderr of ok and failed hosts and every
results of tasks executed (this may include the fact gathering tasks)
Example:
.. code-block:: python
# Inventory
[control1]
enos-0
[control2]
enos-1
# Python
result = run_command("control*", "date", inventory)
# Result
{
'failed': {},
'ok':
{
u'enos-0':
{
'stderr': u'',
'stdout': u'Tue Oct 31 04:53:04 GMT 2017'
},
u'enos-1':
{
'stderr': u'',
'stdout': u'Tue Oct 31 04:53:05 GMT 2017'}
},
'results': [...]
}
If facts are gathers this is possible to use ansible templating
.. code-block:: python
result = run_command("control*", "ping -c 1
{{hostvars['enos-1']['ansible_' + n1].ipv4.address}}", inventory)
"""
def filter_results(results, status):
_r = [r for r in results
if r.status == status and r.task == COMMAND_NAME]
s = dict([[r.host, {"stdout": r.payload.get("stdout"),
"stderr": r.payload.get("stderr")}]
for r in _r])
return s
play_source = {
"hosts": pattern_hosts,
"tasks": [{
"name": COMMAND_NAME,
"shell": command,
}]
}
results = run_play(play_source,
inventory_path=inventory_path,
roles=roles,
extra_vars=extra_vars)
ok = filter_results(results, STATUS_OK)
failed = filter_results(results, STATUS_FAILED)
return {"ok": ok, "failed": failed, "results": results} | [
"def",
"run_command",
"(",
"pattern_hosts",
",",
"command",
",",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"on_error_continue",
"=",
"False",
")",
":",
"def",
"filter_results",
"(",
"results",
",",
"status... | Run a shell command on some remote hosts.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
command (str): the command to run
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
Returns:
Dict combining the stdout and stderr of ok and failed hosts and every
results of tasks executed (this may include the fact gathering tasks)
Example:
.. code-block:: python
# Inventory
[control1]
enos-0
[control2]
enos-1
# Python
result = run_command("control*", "date", inventory)
# Result
{
'failed': {},
'ok':
{
u'enos-0':
{
'stderr': u'',
'stdout': u'Tue Oct 31 04:53:04 GMT 2017'
},
u'enos-1':
{
'stderr': u'',
'stdout': u'Tue Oct 31 04:53:05 GMT 2017'}
},
'results': [...]
}
If facts are gathers this is possible to use ansible templating
.. code-block:: python
result = run_command("control*", "ping -c 1
{{hostvars['enos-1']['ansible_' + n1].ipv4.address}}", inventory) | [
"Run",
"a",
"shell",
"command",
"on",
"some",
"remote",
"hosts",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L306-L390 |
BeyondTheClouds/enoslib | enoslib/api.py | run_ansible | def run_ansible(playbooks, inventory_path=None, roles=None, extra_vars=None,
tags=None, on_error_continue=False, basedir='.'):
"""Run Ansible.
Args:
playbooks (list): list of paths to the playbooks to run
inventory_path (str): path to the hosts file (inventory)
extra_var (dict): extra vars to pass
tags (list): list of tags to run
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
"""
inventory, variable_manager, loader, options = _load_defaults(
inventory_path=inventory_path,
roles=roles,
extra_vars=extra_vars,
tags=tags,
basedir=basedir
)
passwords = {}
for path in playbooks:
logger.info("Running playbook %s with vars:\n%s" % (path, extra_vars))
pbex = PlaybookExecutor(
playbooks=[path],
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords
)
code = pbex.run()
stats = pbex._tqm._stats
hosts = stats.processed.keys()
result = [{h: stats.summarize(h)} for h in hosts]
results = {"code": code, "result": result, "playbook": path}
print(results)
failed_hosts = []
unreachable_hosts = []
for h in hosts:
t = stats.summarize(h)
if t["failures"] > 0:
failed_hosts.append(h)
if t["unreachable"] > 0:
unreachable_hosts.append(h)
if len(failed_hosts) > 0:
logger.error("Failed hosts: %s" % failed_hosts)
if not on_error_continue:
raise EnosFailedHostsError(failed_hosts)
if len(unreachable_hosts) > 0:
logger.error("Unreachable hosts: %s" % unreachable_hosts)
if not on_error_continue:
raise EnosUnreachableHostsError(unreachable_hosts) | python | def run_ansible(playbooks, inventory_path=None, roles=None, extra_vars=None,
tags=None, on_error_continue=False, basedir='.'):
"""Run Ansible.
Args:
playbooks (list): list of paths to the playbooks to run
inventory_path (str): path to the hosts file (inventory)
extra_var (dict): extra vars to pass
tags (list): list of tags to run
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False``
"""
inventory, variable_manager, loader, options = _load_defaults(
inventory_path=inventory_path,
roles=roles,
extra_vars=extra_vars,
tags=tags,
basedir=basedir
)
passwords = {}
for path in playbooks:
logger.info("Running playbook %s with vars:\n%s" % (path, extra_vars))
pbex = PlaybookExecutor(
playbooks=[path],
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords
)
code = pbex.run()
stats = pbex._tqm._stats
hosts = stats.processed.keys()
result = [{h: stats.summarize(h)} for h in hosts]
results = {"code": code, "result": result, "playbook": path}
print(results)
failed_hosts = []
unreachable_hosts = []
for h in hosts:
t = stats.summarize(h)
if t["failures"] > 0:
failed_hosts.append(h)
if t["unreachable"] > 0:
unreachable_hosts.append(h)
if len(failed_hosts) > 0:
logger.error("Failed hosts: %s" % failed_hosts)
if not on_error_continue:
raise EnosFailedHostsError(failed_hosts)
if len(unreachable_hosts) > 0:
logger.error("Unreachable hosts: %s" % unreachable_hosts)
if not on_error_continue:
raise EnosUnreachableHostsError(unreachable_hosts) | [
"def",
"run_ansible",
"(",
"playbooks",
",",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"on_error_continue",
"=",
"False",
",",
"basedir",
"=",
"'.'",
")",
":",
"inventory",
",... | Run Ansible.
Args:
playbooks (list): list of paths to the playbooks to run
inventory_path (str): path to the hosts file (inventory)
extra_var (dict): extra vars to pass
tags (list): list of tags to run
on_error_continue(bool): Don't throw any exception in case a host is
unreachable or the playbooks run with errors
Raises:
:py:class:`enoslib.errors.EnosFailedHostsError`: if a task returns an
error on a host and ``on_error_continue==False``
:py:class:`enoslib.errors.EnosUnreachableHostsError`: if a host is
unreachable (through ssh) and ``on_error_continue==False`` | [
"Run",
"Ansible",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L393-L456 |
BeyondTheClouds/enoslib | enoslib/api.py | discover_networks | def discover_networks(roles, networks, fake_interfaces=None,
fake_networks=None):
"""Checks the network interfaces on the nodes.
This enables to auto-discover the mapping interface name <-> network role.
Beware, this has a side effect on each Host in roles.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
networks (list): network list as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
fake_interfaces (list): names of optionnal dummy interfaces to create
fake_networks (list): names of the roles to associate with the fake
interfaces. Like reguilar network interfaces, the mapping will be
added to the host vars. Internally this will be zipped with the
fake_interfaces to produce the mapping.
If the command is successful each host will be added some variables.
Assuming that one network whose role is `mynetwork` has been declared, the
following variables will be available through the ansible hostvars:
- ``mynetwork=eth1``, `eth1` has been discovered has the interface in the
network `mynetwork`.
- ``mynetwork_dev=eth1``, same as above with a different accessor names
- ``mynetwork_ip=192.168.42.42``, this indicates the ip in the network
`mynetwork` for this node
All of this variable can then be accessed by the other nodes through the
hostvars: ``hostvars[remote_node]["mynetwork_ip"]``
"""
def get_devices(facts):
"""Extract the network devices information from the facts."""
devices = []
for interface in facts['ansible_interfaces']:
ansible_interface = 'ansible_' + interface
# filter here (active/ name...)
if 'ansible_' + interface in facts:
interface = facts[ansible_interface]
devices.append(interface)
return devices
wait_ssh(roles)
tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME)
_check_tmpdir(tmpdir)
fake_interfaces = fake_interfaces or []
fake_networks = fake_networks or []
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
facts_file = os.path.join(tmpdir, 'facts.json')
options = {
'enos_action': 'check_network',
'facts_file': facts_file,
'fake_interfaces': fake_interfaces
}
run_ansible([utils_playbook], roles=roles,
extra_vars=options,
on_error_continue=False)
# Read the file
# Match provider networks to interface names for each host
with open(facts_file) as f:
facts = json.load(f)
for _, host_facts in facts.items():
host_nets = _map_device_on_host_networks(networks,
get_devices(host_facts))
# Add the mapping : networks <-> nic name
host_facts['networks'] = host_nets
# Finally update the env with this information
# generate the extra_mapping for the fake interfaces
extra_mapping = dict(zip(fake_networks, fake_interfaces))
_update_hosts(roles, facts, extra_mapping=extra_mapping) | python | def discover_networks(roles, networks, fake_interfaces=None,
fake_networks=None):
"""Checks the network interfaces on the nodes.
This enables to auto-discover the mapping interface name <-> network role.
Beware, this has a side effect on each Host in roles.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
networks (list): network list as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
fake_interfaces (list): names of optionnal dummy interfaces to create
fake_networks (list): names of the roles to associate with the fake
interfaces. Like reguilar network interfaces, the mapping will be
added to the host vars. Internally this will be zipped with the
fake_interfaces to produce the mapping.
If the command is successful each host will be added some variables.
Assuming that one network whose role is `mynetwork` has been declared, the
following variables will be available through the ansible hostvars:
- ``mynetwork=eth1``, `eth1` has been discovered has the interface in the
network `mynetwork`.
- ``mynetwork_dev=eth1``, same as above with a different accessor names
- ``mynetwork_ip=192.168.42.42``, this indicates the ip in the network
`mynetwork` for this node
All of this variable can then be accessed by the other nodes through the
hostvars: ``hostvars[remote_node]["mynetwork_ip"]``
"""
def get_devices(facts):
"""Extract the network devices information from the facts."""
devices = []
for interface in facts['ansible_interfaces']:
ansible_interface = 'ansible_' + interface
# filter here (active/ name...)
if 'ansible_' + interface in facts:
interface = facts[ansible_interface]
devices.append(interface)
return devices
wait_ssh(roles)
tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME)
_check_tmpdir(tmpdir)
fake_interfaces = fake_interfaces or []
fake_networks = fake_networks or []
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
facts_file = os.path.join(tmpdir, 'facts.json')
options = {
'enos_action': 'check_network',
'facts_file': facts_file,
'fake_interfaces': fake_interfaces
}
run_ansible([utils_playbook], roles=roles,
extra_vars=options,
on_error_continue=False)
# Read the file
# Match provider networks to interface names for each host
with open(facts_file) as f:
facts = json.load(f)
for _, host_facts in facts.items():
host_nets = _map_device_on_host_networks(networks,
get_devices(host_facts))
# Add the mapping : networks <-> nic name
host_facts['networks'] = host_nets
# Finally update the env with this information
# generate the extra_mapping for the fake interfaces
extra_mapping = dict(zip(fake_networks, fake_interfaces))
_update_hosts(roles, facts, extra_mapping=extra_mapping) | [
"def",
"discover_networks",
"(",
"roles",
",",
"networks",
",",
"fake_interfaces",
"=",
"None",
",",
"fake_networks",
"=",
"None",
")",
":",
"def",
"get_devices",
"(",
"facts",
")",
":",
"\"\"\"Extract the network devices information from the facts.\"\"\"",
"devices",
... | Checks the network interfaces on the nodes.
This enables to auto-discover the mapping interface name <-> network role.
Beware, this has a side effect on each Host in roles.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
networks (list): network list as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
fake_interfaces (list): names of optionnal dummy interfaces to create
fake_networks (list): names of the roles to associate with the fake
interfaces. Like reguilar network interfaces, the mapping will be
added to the host vars. Internally this will be zipped with the
fake_interfaces to produce the mapping.
If the command is successful each host will be added some variables.
Assuming that one network whose role is `mynetwork` has been declared, the
following variables will be available through the ansible hostvars:
- ``mynetwork=eth1``, `eth1` has been discovered has the interface in the
network `mynetwork`.
- ``mynetwork_dev=eth1``, same as above with a different accessor names
- ``mynetwork_ip=192.168.42.42``, this indicates the ip in the network
`mynetwork` for this node
All of this variable can then be accessed by the other nodes through the
hostvars: ``hostvars[remote_node]["mynetwork_ip"]`` | [
"Checks",
"the",
"network",
"interfaces",
"on",
"the",
"nodes",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L459-L532 |
BeyondTheClouds/enoslib | enoslib/api.py | generate_inventory | def generate_inventory(roles, networks, inventory_path, check_networks=False,
fake_interfaces=None, fake_networks=None):
"""Generate an inventory file in the ini format.
The inventory is generated using the ``roles`` in the ``ini`` format. If
``check_network == True``, the function will try to discover which networks
interfaces are available and map them to one network of the ``networks``
parameters. Note that this auto-discovery feature requires the servers to
have their IP set.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
networks (list): network list as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path (str): path to the inventory to generate
check_networks (bool): True to enable the auto-discovery of the mapping
interface name <-> network role
fake_interfaces (list): names of optionnal dummy interfaces to create
on the nodes
fake_networks (list): names of the roles to associate with the fake
interfaces. Like reguilar network interfaces, the mapping will be
added to the host vars. Internally this will be zipped with the
fake_interfaces to produce the mapping. """
with open(inventory_path, "w") as f:
f.write(_generate_inventory(roles))
if check_networks:
discover_networks(
roles,
networks,
fake_interfaces=fake_interfaces,
fake_networks=fake_networks
)
with open(inventory_path, "w") as f:
f.write(_generate_inventory(roles)) | python | def generate_inventory(roles, networks, inventory_path, check_networks=False,
fake_interfaces=None, fake_networks=None):
"""Generate an inventory file in the ini format.
The inventory is generated using the ``roles`` in the ``ini`` format. If
``check_network == True``, the function will try to discover which networks
interfaces are available and map them to one network of the ``networks``
parameters. Note that this auto-discovery feature requires the servers to
have their IP set.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
networks (list): network list as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path (str): path to the inventory to generate
check_networks (bool): True to enable the auto-discovery of the mapping
interface name <-> network role
fake_interfaces (list): names of optionnal dummy interfaces to create
on the nodes
fake_networks (list): names of the roles to associate with the fake
interfaces. Like reguilar network interfaces, the mapping will be
added to the host vars. Internally this will be zipped with the
fake_interfaces to produce the mapping. """
with open(inventory_path, "w") as f:
f.write(_generate_inventory(roles))
if check_networks:
discover_networks(
roles,
networks,
fake_interfaces=fake_interfaces,
fake_networks=fake_networks
)
with open(inventory_path, "w") as f:
f.write(_generate_inventory(roles)) | [
"def",
"generate_inventory",
"(",
"roles",
",",
"networks",
",",
"inventory_path",
",",
"check_networks",
"=",
"False",
",",
"fake_interfaces",
"=",
"None",
",",
"fake_networks",
"=",
"None",
")",
":",
"with",
"open",
"(",
"inventory_path",
",",
"\"w\"",
")",
... | Generate an inventory file in the ini format.
The inventory is generated using the ``roles`` in the ``ini`` format. If
``check_network == True``, the function will try to discover which networks
interfaces are available and map them to one network of the ``networks``
parameters. Note that this auto-discovery feature requires the servers to
have their IP set.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
networks (list): network list as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path (str): path to the inventory to generate
check_networks (bool): True to enable the auto-discovery of the mapping
interface name <-> network role
fake_interfaces (list): names of optionnal dummy interfaces to create
on the nodes
fake_networks (list): names of the roles to associate with the fake
interfaces. Like reguilar network interfaces, the mapping will be
added to the host vars. Internally this will be zipped with the
fake_interfaces to produce the mapping. | [
"Generate",
"an",
"inventory",
"file",
"in",
"the",
"ini",
"format",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L535-L571 |
BeyondTheClouds/enoslib | enoslib/api.py | emulate_network | def emulate_network(network_constraints,
roles=None,
inventory_path=None,
extra_vars=None):
"""Emulate network links.
Read ``network_constraints`` and apply ``tc`` rules on all the nodes.
Constraints are applied between groups of machines. Theses groups are
described in the ``network_constraints`` variable and must be found in the
inventory file. The newtwork constraints support ``delay``, ``rate`` and
``loss``.
Args:
network_constraints (dict): network constraints to apply
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path(string): path to an inventory
extra_vars (dict): extra_vars to pass to ansible
Examples:
* Using defaults
The following will apply the network constraints between every groups.
For instance the constraints will be applied for the communication
between "n1" and "n3" but not between "n1" and "n2". Note that using
default leads to symetric constraints.
.. code-block:: python
roles = {
"grp1": ["n1", "n2"],
"grp2": ["n3", "n4"],
"grp3": ["n3", "n4"],
}
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
}
emulate_network(roles, tc)
If you want to control more precisely which groups need to be taken
into account, you can use ``except`` or ``groups`` key
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"except": "grp3"
}
emulate_network(roles, tc)
is equivalent to
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"groups": ["grp1", "grp2"]
}
emulate_network(roles, inventory, tc)
* Using ``src`` and ``dst``
The following will enforce a symetric constraint between ``grp1`` and
``grp2``.
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"constraints": [{
"src": "grp1"
"dst": "grp2"
"delay": "10ms"
"symetric": True
}]
}
emulate_network(roles, inventory, tc)
"""
# 1) Retrieve the list of ips for all nodes (Ansible)
# 2) Build all the constraints (Python)
# {source:src, target: ip_dest, device: if, rate:x, delay:y}
# 3) Enforce those constraints (Ansible)
if not network_constraints:
return
if roles is None and inventory is None:
raise ValueError("roles and inventory can't be None")
if not extra_vars:
extra_vars = {}
# 1. getting ips/devices information
logger.debug('Getting the ips of all nodes')
tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME)
_check_tmpdir(tmpdir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
ips_file = os.path.join(tmpdir, 'ips.txt')
options = {'enos_action': 'tc_ips',
'ips_file': ips_file}
run_ansible([utils_playbook], roles=roles, extra_vars=options)
# 2.a building the group constraints
logger.debug('Building all the constraints')
constraints = _build_grp_constraints(roles, network_constraints)
# 2.b Building the ip/device level constaints
with open(ips_file) as f:
ips = yaml.safe_load(f)
# will hold every single constraint
ips_with_constraints = _build_ip_constraints(roles,
ips,
constraints)
# dumping it for debugging purpose
ips_with_constraints_file = os.path.join(tmpdir,
'ips_with_constraints.yml')
with open(ips_with_constraints_file, 'w') as g:
yaml.dump(ips_with_constraints, g)
# 3. Enforcing those constraints
logger.info('Enforcing the constraints')
# enabling/disabling network constraints
enable = network_constraints.setdefault('enable', True)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {
'enos_action': 'tc_apply',
'ips_with_constraints': ips_with_constraints,
'tc_enable': enable,
}
options.update(extra_vars)
run_ansible([utils_playbook],
roles=roles,
inventory_path=inventory_path,
extra_vars=options) | python | def emulate_network(network_constraints,
roles=None,
inventory_path=None,
extra_vars=None):
"""Emulate network links.
Read ``network_constraints`` and apply ``tc`` rules on all the nodes.
Constraints are applied between groups of machines. Theses groups are
described in the ``network_constraints`` variable and must be found in the
inventory file. The newtwork constraints support ``delay``, ``rate`` and
``loss``.
Args:
network_constraints (dict): network constraints to apply
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path(string): path to an inventory
extra_vars (dict): extra_vars to pass to ansible
Examples:
* Using defaults
The following will apply the network constraints between every groups.
For instance the constraints will be applied for the communication
between "n1" and "n3" but not between "n1" and "n2". Note that using
default leads to symetric constraints.
.. code-block:: python
roles = {
"grp1": ["n1", "n2"],
"grp2": ["n3", "n4"],
"grp3": ["n3", "n4"],
}
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
}
emulate_network(roles, tc)
If you want to control more precisely which groups need to be taken
into account, you can use ``except`` or ``groups`` key
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"except": "grp3"
}
emulate_network(roles, tc)
is equivalent to
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"groups": ["grp1", "grp2"]
}
emulate_network(roles, inventory, tc)
* Using ``src`` and ``dst``
The following will enforce a symetric constraint between ``grp1`` and
``grp2``.
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"constraints": [{
"src": "grp1"
"dst": "grp2"
"delay": "10ms"
"symetric": True
}]
}
emulate_network(roles, inventory, tc)
"""
# 1) Retrieve the list of ips for all nodes (Ansible)
# 2) Build all the constraints (Python)
# {source:src, target: ip_dest, device: if, rate:x, delay:y}
# 3) Enforce those constraints (Ansible)
if not network_constraints:
return
if roles is None and inventory is None:
raise ValueError("roles and inventory can't be None")
if not extra_vars:
extra_vars = {}
# 1. getting ips/devices information
logger.debug('Getting the ips of all nodes')
tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME)
_check_tmpdir(tmpdir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
ips_file = os.path.join(tmpdir, 'ips.txt')
options = {'enos_action': 'tc_ips',
'ips_file': ips_file}
run_ansible([utils_playbook], roles=roles, extra_vars=options)
# 2.a building the group constraints
logger.debug('Building all the constraints')
constraints = _build_grp_constraints(roles, network_constraints)
# 2.b Building the ip/device level constaints
with open(ips_file) as f:
ips = yaml.safe_load(f)
# will hold every single constraint
ips_with_constraints = _build_ip_constraints(roles,
ips,
constraints)
# dumping it for debugging purpose
ips_with_constraints_file = os.path.join(tmpdir,
'ips_with_constraints.yml')
with open(ips_with_constraints_file, 'w') as g:
yaml.dump(ips_with_constraints, g)
# 3. Enforcing those constraints
logger.info('Enforcing the constraints')
# enabling/disabling network constraints
enable = network_constraints.setdefault('enable', True)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {
'enos_action': 'tc_apply',
'ips_with_constraints': ips_with_constraints,
'tc_enable': enable,
}
options.update(extra_vars)
run_ansible([utils_playbook],
roles=roles,
inventory_path=inventory_path,
extra_vars=options) | [
"def",
"emulate_network",
"(",
"network_constraints",
",",
"roles",
"=",
"None",
",",
"inventory_path",
"=",
"None",
",",
"extra_vars",
"=",
"None",
")",
":",
"# 1) Retrieve the list of ips for all nodes (Ansible)",
"# 2) Build all the constraints (Python)",
"# {source:src... | Emulate network links.
Read ``network_constraints`` and apply ``tc`` rules on all the nodes.
Constraints are applied between groups of machines. Theses groups are
described in the ``network_constraints`` variable and must be found in the
inventory file. The newtwork constraints support ``delay``, ``rate`` and
``loss``.
Args:
network_constraints (dict): network constraints to apply
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path(string): path to an inventory
extra_vars (dict): extra_vars to pass to ansible
Examples:
* Using defaults
The following will apply the network constraints between every groups.
For instance the constraints will be applied for the communication
between "n1" and "n3" but not between "n1" and "n2". Note that using
default leads to symetric constraints.
.. code-block:: python
roles = {
"grp1": ["n1", "n2"],
"grp2": ["n3", "n4"],
"grp3": ["n3", "n4"],
}
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
}
emulate_network(roles, tc)
If you want to control more precisely which groups need to be taken
into account, you can use ``except`` or ``groups`` key
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"except": "grp3"
}
emulate_network(roles, tc)
is equivalent to
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"groups": ["grp1", "grp2"]
}
emulate_network(roles, inventory, tc)
* Using ``src`` and ``dst``
The following will enforce a symetric constraint between ``grp1`` and
``grp2``.
.. code-block:: python
tc = {
"enable": True,
"default_delay": "20ms",
"default_rate": "1gbit",
"constraints": [{
"src": "grp1"
"dst": "grp2"
"delay": "10ms"
"symetric": True
}]
}
emulate_network(roles, inventory, tc) | [
"Emulate",
"network",
"links",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L574-L717 |
BeyondTheClouds/enoslib | enoslib/api.py | validate_network | def validate_network(roles=None,
inventory_path=None,
output_dir=None,
extra_vars=None):
"""Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Reports are available in the tmp directory used
by enos.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path (str): path to an inventory
output_dir (str): directory where validation files will be stored.
Default to :py:const:`enoslib.constants.TMP_DIRNAME`.
"""
logger.debug('Checking the constraints')
if not output_dir:
output_dir = os.path.join(os.getcwd(), TMP_DIRNAME)
if not extra_vars:
extra_vars = {}
output_dir = os.path.abspath(output_dir)
_check_tmpdir(output_dir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'tc_validate',
'tc_output_dir': output_dir}
options.update(extra_vars)
run_ansible([utils_playbook],
roles=roles,
inventory_path=inventory_path,
extra_vars=options) | python | def validate_network(roles=None,
inventory_path=None,
output_dir=None,
extra_vars=None):
"""Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Reports are available in the tmp directory used
by enos.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path (str): path to an inventory
output_dir (str): directory where validation files will be stored.
Default to :py:const:`enoslib.constants.TMP_DIRNAME`.
"""
logger.debug('Checking the constraints')
if not output_dir:
output_dir = os.path.join(os.getcwd(), TMP_DIRNAME)
if not extra_vars:
extra_vars = {}
output_dir = os.path.abspath(output_dir)
_check_tmpdir(output_dir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'tc_validate',
'tc_output_dir': output_dir}
options.update(extra_vars)
run_ansible([utils_playbook],
roles=roles,
inventory_path=inventory_path,
extra_vars=options) | [
"def",
"validate_network",
"(",
"roles",
"=",
"None",
",",
"inventory_path",
"=",
"None",
",",
"output_dir",
"=",
"None",
",",
"extra_vars",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Checking the constraints'",
")",
"if",
"not",
"output_dir",
":"... | Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Reports are available in the tmp directory used
by enos.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory_path (str): path to an inventory
output_dir (str): directory where validation files will be stored.
Default to :py:const:`enoslib.constants.TMP_DIRNAME`. | [
"Validate",
"the",
"network",
"parameters",
"(",
"latency",
"bandwidth",
"...",
")"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L720-L754 |
BeyondTheClouds/enoslib | enoslib/api.py | reset_network | def reset_network(roles, extra_vars=None):
"""Reset the network constraints (latency, bandwidth ...)
Remove any filter that have been applied to shape the traffic.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory (str): path to the inventory
"""
logger.debug('Reset the constraints')
if not extra_vars:
extra_vars = {}
tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME)
_check_tmpdir(tmpdir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'tc_reset',
'tc_output_dir': tmpdir}
options.update(extra_vars)
run_ansible([utils_playbook], roles=roles, extra_vars=options) | python | def reset_network(roles, extra_vars=None):
"""Reset the network constraints (latency, bandwidth ...)
Remove any filter that have been applied to shape the traffic.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory (str): path to the inventory
"""
logger.debug('Reset the constraints')
if not extra_vars:
extra_vars = {}
tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME)
_check_tmpdir(tmpdir)
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'tc_reset',
'tc_output_dir': tmpdir}
options.update(extra_vars)
run_ansible([utils_playbook], roles=roles, extra_vars=options) | [
"def",
"reset_network",
"(",
"roles",
",",
"extra_vars",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Reset the constraints'",
")",
"if",
"not",
"extra_vars",
":",
"extra_vars",
"=",
"{",
"}",
"tmpdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | Reset the network constraints (latency, bandwidth ...)
Remove any filter that have been applied to shape the traffic.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory (str): path to the inventory | [
"Reset",
"the",
"network",
"constraints",
"(",
"latency",
"bandwidth",
"...",
")"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L757-L779 |
BeyondTheClouds/enoslib | enoslib/api.py | wait_ssh | def wait_ssh(roles, retries=100, interval=30):
"""Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
interval (int): Interval to wait in seconds between two retries
"""
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'ping'}
for i in range(0, retries):
try:
run_ansible([utils_playbook],
roles=roles,
extra_vars=options,
on_error_continue=False)
break
except EnosUnreachableHostsError as e:
logger.info("Hosts unreachable: %s " % e.hosts)
logger.info("Retrying... %s/%s" % (i + 1, retries))
time.sleep(interval)
else:
raise EnosSSHNotReady('Maximum retries reached') | python | def wait_ssh(roles, retries=100, interval=30):
"""Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
interval (int): Interval to wait in seconds between two retries
"""
utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml')
options = {'enos_action': 'ping'}
for i in range(0, retries):
try:
run_ansible([utils_playbook],
roles=roles,
extra_vars=options,
on_error_continue=False)
break
except EnosUnreachableHostsError as e:
logger.info("Hosts unreachable: %s " % e.hosts)
logger.info("Retrying... %s/%s" % (i + 1, retries))
time.sleep(interval)
else:
raise EnosSSHNotReady('Maximum retries reached') | [
"def",
"wait_ssh",
"(",
"roles",
",",
"retries",
"=",
"100",
",",
"interval",
"=",
"30",
")",
":",
"utils_playbook",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ANSIBLE_DIR",
",",
"'utils.yml'",
")",
"options",
"=",
"{",
"'enos_action'",
":",
"'ping'",
... | Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
interval (int): Interval to wait in seconds between two retries | [
"Wait",
"for",
"all",
"the",
"machines",
"to",
"be",
"ssh",
"-",
"reachable"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L782-L807 |
BeyondTheClouds/enoslib | enoslib/api.py | expand_groups | def expand_groups(grp):
"""Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1]
"""
p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P<end>\d+)\]")
m = p.match(grp)
if m is not None:
s = int(m.group('start'))
e = int(m.group('end'))
n = m.group('name')
return list(map(lambda x: n + str(x), range(s, e + 1)))
else:
return [grp] | python | def expand_groups(grp):
"""Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1]
"""
p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P<end>\d+)\]")
m = p.match(grp)
if m is not None:
s = int(m.group('start'))
e = int(m.group('end'))
n = m.group('name')
return list(map(lambda x: n + str(x), range(s, e + 1)))
else:
return [grp] | [
"def",
"expand_groups",
"(",
"grp",
")",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<name>.+)\\[(?P<start>\\d+)-(?P<end>\\d+)\\]\"",
")",
"m",
"=",
"p",
".",
"match",
"(",
"grp",
")",
"if",
"m",
"is",
"not",
"None",
":",
"s",
"=",
"int",
"(",
"m"... | Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1] | [
"Expand",
"group",
"names",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L810-L832 |
BeyondTheClouds/enoslib | enoslib/api.py | _expand_description | def _expand_description(desc):
"""Expand the description given the group names/patterns
e.g:
{src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions
"""
srcs = expand_groups(desc['src'])
dsts = expand_groups(desc['dst'])
descs = []
for src in srcs:
for dst in dsts:
local_desc = desc.copy()
local_desc['src'] = src
local_desc['dst'] = dst
descs.append(local_desc)
return descs | python | def _expand_description(desc):
"""Expand the description given the group names/patterns
e.g:
{src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions
"""
srcs = expand_groups(desc['src'])
dsts = expand_groups(desc['dst'])
descs = []
for src in srcs:
for dst in dsts:
local_desc = desc.copy()
local_desc['src'] = src
local_desc['dst'] = dst
descs.append(local_desc)
return descs | [
"def",
"_expand_description",
"(",
"desc",
")",
":",
"srcs",
"=",
"expand_groups",
"(",
"desc",
"[",
"'src'",
"]",
")",
"dsts",
"=",
"expand_groups",
"(",
"desc",
"[",
"'dst'",
"]",
")",
"descs",
"=",
"[",
"]",
"for",
"src",
"in",
"srcs",
":",
"for",... | Expand the description given the group names/patterns
e.g:
{src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions | [
"Expand",
"the",
"description",
"given",
"the",
"group",
"names",
"/",
"patterns",
"e",
".",
"g",
":",
"{",
"src",
":",
"grp",
"[",
"1",
"-",
"3",
"]",
"dst",
":",
"grp",
"[",
"4",
"-",
"6",
"]",
"...",
"}",
"will",
"generate",
"9",
"descriptions... | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L886-L901 |
BeyondTheClouds/enoslib | enoslib/api.py | _generate_default_grp_constraints | def _generate_default_grp_constraints(roles, network_constraints):
"""Generate default symetric grp constraints.
"""
default_delay = network_constraints.get('default_delay')
default_rate = network_constraints.get('default_rate')
default_loss = network_constraints.get('default_loss', 0)
except_groups = network_constraints.get('except', [])
grps = network_constraints.get('groups', roles.keys())
# expand each groups
grps = [expand_groups(g) for g in grps]
# flatten
grps = [x for expanded_group in grps for x in expanded_group]
# building the default group constraints
return [{'src': grp1,
'dst': grp2,
'delay': default_delay,
'rate': default_rate,
'loss': default_loss}
for grp1 in grps for grp2 in grps
if ((grp1 != grp2
or _src_equals_dst_in_constraints(network_constraints, grp1))
and grp1 not in except_groups and grp2 not in except_groups)] | python | def _generate_default_grp_constraints(roles, network_constraints):
"""Generate default symetric grp constraints.
"""
default_delay = network_constraints.get('default_delay')
default_rate = network_constraints.get('default_rate')
default_loss = network_constraints.get('default_loss', 0)
except_groups = network_constraints.get('except', [])
grps = network_constraints.get('groups', roles.keys())
# expand each groups
grps = [expand_groups(g) for g in grps]
# flatten
grps = [x for expanded_group in grps for x in expanded_group]
# building the default group constraints
return [{'src': grp1,
'dst': grp2,
'delay': default_delay,
'rate': default_rate,
'loss': default_loss}
for grp1 in grps for grp2 in grps
if ((grp1 != grp2
or _src_equals_dst_in_constraints(network_constraints, grp1))
and grp1 not in except_groups and grp2 not in except_groups)] | [
"def",
"_generate_default_grp_constraints",
"(",
"roles",
",",
"network_constraints",
")",
":",
"default_delay",
"=",
"network_constraints",
".",
"get",
"(",
"'default_delay'",
")",
"default_rate",
"=",
"network_constraints",
".",
"get",
"(",
"'default_rate'",
")",
"d... | Generate default symetric grp constraints. | [
"Generate",
"default",
"symetric",
"grp",
"constraints",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L922-L943 |
BeyondTheClouds/enoslib | enoslib/api.py | _generate_actual_grp_constraints | def _generate_actual_grp_constraints(network_constraints):
"""Generate the user specified constraints
"""
if 'constraints' not in network_constraints:
return []
constraints = network_constraints['constraints']
actual = []
for desc in constraints:
descs = _expand_description(desc)
for desc in descs:
actual.append(desc)
if 'symetric' in desc:
sym = desc.copy()
sym['src'] = desc['dst']
sym['dst'] = desc['src']
actual.append(sym)
return actual | python | def _generate_actual_grp_constraints(network_constraints):
"""Generate the user specified constraints
"""
if 'constraints' not in network_constraints:
return []
constraints = network_constraints['constraints']
actual = []
for desc in constraints:
descs = _expand_description(desc)
for desc in descs:
actual.append(desc)
if 'symetric' in desc:
sym = desc.copy()
sym['src'] = desc['dst']
sym['dst'] = desc['src']
actual.append(sym)
return actual | [
"def",
"_generate_actual_grp_constraints",
"(",
"network_constraints",
")",
":",
"if",
"'constraints'",
"not",
"in",
"network_constraints",
":",
"return",
"[",
"]",
"constraints",
"=",
"network_constraints",
"[",
"'constraints'",
"]",
"actual",
"=",
"[",
"]",
"for",... | Generate the user specified constraints | [
"Generate",
"the",
"user",
"specified",
"constraints"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L946-L963 |
BeyondTheClouds/enoslib | enoslib/api.py | _merge_constraints | def _merge_constraints(constraints, overrides):
"""Merge the constraints avoiding duplicates
Change constraints in place.
"""
for o in overrides:
i = 0
while i < len(constraints):
c = constraints[i]
if _same(o, c):
constraints[i].update(o)
break
i = i + 1 | python | def _merge_constraints(constraints, overrides):
"""Merge the constraints avoiding duplicates
Change constraints in place.
"""
for o in overrides:
i = 0
while i < len(constraints):
c = constraints[i]
if _same(o, c):
constraints[i].update(o)
break
i = i + 1 | [
"def",
"_merge_constraints",
"(",
"constraints",
",",
"overrides",
")",
":",
"for",
"o",
"in",
"overrides",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"constraints",
")",
":",
"c",
"=",
"constraints",
"[",
"i",
"]",
"if",
"_same",
"(",
"o",
... | Merge the constraints avoiding duplicates
Change constraints in place. | [
"Merge",
"the",
"constraints",
"avoiding",
"duplicates",
"Change",
"constraints",
"in",
"place",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L966-L977 |
BeyondTheClouds/enoslib | enoslib/api.py | _build_grp_constraints | def _build_grp_constraints(roles, network_constraints):
"""Generate constraints at the group level,
It expands the group names and deal with symetric constraints.
"""
# generate defaults constraints
constraints = _generate_default_grp_constraints(roles,
network_constraints)
# Updating the constraints if necessary
if 'constraints' in network_constraints:
actual = _generate_actual_grp_constraints(network_constraints)
_merge_constraints(constraints, actual)
return constraints | python | def _build_grp_constraints(roles, network_constraints):
"""Generate constraints at the group level,
It expands the group names and deal with symetric constraints.
"""
# generate defaults constraints
constraints = _generate_default_grp_constraints(roles,
network_constraints)
# Updating the constraints if necessary
if 'constraints' in network_constraints:
actual = _generate_actual_grp_constraints(network_constraints)
_merge_constraints(constraints, actual)
return constraints | [
"def",
"_build_grp_constraints",
"(",
"roles",
",",
"network_constraints",
")",
":",
"# generate defaults constraints",
"constraints",
"=",
"_generate_default_grp_constraints",
"(",
"roles",
",",
"network_constraints",
")",
"# Updating the constraints if necessary",
"if",
"'con... | Generate constraints at the group level,
It expands the group names and deal with symetric constraints. | [
"Generate",
"constraints",
"at",
"the",
"group",
"level",
"It",
"expands",
"the",
"group",
"names",
"and",
"deal",
"with",
"symetric",
"constraints",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L980-L992 |
BeyondTheClouds/enoslib | enoslib/api.py | _build_ip_constraints | def _build_ip_constraints(roles, ips, constraints):
"""Generate the constraints at the ip/device level.
Those constraints are those used by ansible to enforce tc/netem rules.
"""
local_ips = copy.deepcopy(ips)
for constraint in constraints:
gsrc = constraint['src']
gdst = constraint['dst']
gdelay = constraint['delay']
grate = constraint['rate']
gloss = constraint['loss']
for s in roles[gsrc]:
# one possible source
# Get all the active devices for this source
active_devices = filter(lambda x: x["active"],
local_ips[s.alias]['devices'])
# Get only the devices specified in the network constraint
if 'network' in constraint:
active_devices = filter(
lambda x:
x['device'] == s.extra[constraint['network']],
active_devices)
# Get only the name of the active devices
sdevices = map(lambda x: x['device'], active_devices)
for sdevice in sdevices:
# one possible device
for d in roles[gdst]:
# one possible destination
dallips = local_ips[d.alias]['all_ipv4_addresses']
# Let's keep docker bridge out of this
dallips = filter(lambda x: x != '172.17.0.1', dallips)
for dip in dallips:
local_ips[s.alias].setdefault('tc', []).append({
'source': s.alias,
'target': dip,
'device': sdevice,
'delay': gdelay,
'rate': grate,
'loss': gloss
})
return local_ips | python | def _build_ip_constraints(roles, ips, constraints):
"""Generate the constraints at the ip/device level.
Those constraints are those used by ansible to enforce tc/netem rules.
"""
local_ips = copy.deepcopy(ips)
for constraint in constraints:
gsrc = constraint['src']
gdst = constraint['dst']
gdelay = constraint['delay']
grate = constraint['rate']
gloss = constraint['loss']
for s in roles[gsrc]:
# one possible source
# Get all the active devices for this source
active_devices = filter(lambda x: x["active"],
local_ips[s.alias]['devices'])
# Get only the devices specified in the network constraint
if 'network' in constraint:
active_devices = filter(
lambda x:
x['device'] == s.extra[constraint['network']],
active_devices)
# Get only the name of the active devices
sdevices = map(lambda x: x['device'], active_devices)
for sdevice in sdevices:
# one possible device
for d in roles[gdst]:
# one possible destination
dallips = local_ips[d.alias]['all_ipv4_addresses']
# Let's keep docker bridge out of this
dallips = filter(lambda x: x != '172.17.0.1', dallips)
for dip in dallips:
local_ips[s.alias].setdefault('tc', []).append({
'source': s.alias,
'target': dip,
'device': sdevice,
'delay': gdelay,
'rate': grate,
'loss': gloss
})
return local_ips | [
"def",
"_build_ip_constraints",
"(",
"roles",
",",
"ips",
",",
"constraints",
")",
":",
"local_ips",
"=",
"copy",
".",
"deepcopy",
"(",
"ips",
")",
"for",
"constraint",
"in",
"constraints",
":",
"gsrc",
"=",
"constraint",
"[",
"'src'",
"]",
"gdst",
"=",
... | Generate the constraints at the ip/device level.
Those constraints are those used by ansible to enforce tc/netem rules. | [
"Generate",
"the",
"constraints",
"at",
"the",
"ip",
"/",
"device",
"level",
".",
"Those",
"constraints",
"are",
"those",
"used",
"by",
"ansible",
"to",
"enforce",
"tc",
"/",
"netem",
"rules",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L995-L1035 |
BeyondTheClouds/enoslib | enoslib/api.py | _map_device_on_host_networks | def _map_device_on_host_networks(provider_nets, devices):
"""Decorate each networks with the corresponding nic name."""
networks = copy.deepcopy(provider_nets)
for network in networks:
for device in devices:
network.setdefault('device', None)
ip_set = IPSet([network['cidr']])
if 'ipv4' not in device:
continue
ips = device['ipv4']
if not isinstance(ips, list):
ips = [ips]
if len(ips) < 1:
continue
ip = IPAddress(ips[0]['address'])
if ip in ip_set:
network['device'] = device['device']
continue
return networks | python | def _map_device_on_host_networks(provider_nets, devices):
"""Decorate each networks with the corresponding nic name."""
networks = copy.deepcopy(provider_nets)
for network in networks:
for device in devices:
network.setdefault('device', None)
ip_set = IPSet([network['cidr']])
if 'ipv4' not in device:
continue
ips = device['ipv4']
if not isinstance(ips, list):
ips = [ips]
if len(ips) < 1:
continue
ip = IPAddress(ips[0]['address'])
if ip in ip_set:
network['device'] = device['device']
continue
return networks | [
"def",
"_map_device_on_host_networks",
"(",
"provider_nets",
",",
"devices",
")",
":",
"networks",
"=",
"copy",
".",
"deepcopy",
"(",
"provider_nets",
")",
"for",
"network",
"in",
"networks",
":",
"for",
"device",
"in",
"devices",
":",
"network",
".",
"setdefa... | Decorate each networks with the corresponding nic name. | [
"Decorate",
"each",
"networks",
"with",
"the",
"corresponding",
"nic",
"name",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L1038-L1056 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | f_daterange | def f_daterange(freq, tz='UTC', *args, **kwargs):
"""
Use ``dateutil.rrule`` to create a range of dates. The frequency must be a
string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
MINUTELY or SECONDLY.
See `dateutil rrule`_ documentation for more detail.
.. _dateutil rrule: https://dateutil.readthedocs.org/en/latest/rrule.html
:param freq: One of the ``dateutil.rrule`` frequencies
:type freq: str
:param tz: One of the ``pytz`` timezones, defaults to UTC
:type tz: str
:param args: start date <datetime>, interval between each frequency <int>,
max number of recurrences <int>, end date <datetime>
:param kwargs: ``dtstart``, ``interval``, ``count``, ``until``
:return: range of dates
:rtype: list
"""
tz = pytz.timezone(tz)
freq = getattr(rrule, freq.upper()) # get frequency enumeration from rrule
return [tz.localize(dt) for dt in rrule.rrule(freq, *args, **kwargs)] | python | def f_daterange(freq, tz='UTC', *args, **kwargs):
"""
Use ``dateutil.rrule`` to create a range of dates. The frequency must be a
string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
MINUTELY or SECONDLY.
See `dateutil rrule`_ documentation for more detail.
.. _dateutil rrule: https://dateutil.readthedocs.org/en/latest/rrule.html
:param freq: One of the ``dateutil.rrule`` frequencies
:type freq: str
:param tz: One of the ``pytz`` timezones, defaults to UTC
:type tz: str
:param args: start date <datetime>, interval between each frequency <int>,
max number of recurrences <int>, end date <datetime>
:param kwargs: ``dtstart``, ``interval``, ``count``, ``until``
:return: range of dates
:rtype: list
"""
tz = pytz.timezone(tz)
freq = getattr(rrule, freq.upper()) # get frequency enumeration from rrule
return [tz.localize(dt) for dt in rrule.rrule(freq, *args, **kwargs)] | [
"def",
"f_daterange",
"(",
"freq",
",",
"tz",
"=",
"'UTC'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"tz",
")",
"freq",
"=",
"getattr",
"(",
"rrule",
",",
"freq",
".",
"upper",
"(",
")",
")",... | Use ``dateutil.rrule`` to create a range of dates. The frequency must be a
string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
MINUTELY or SECONDLY.
See `dateutil rrule`_ documentation for more detail.
.. _dateutil rrule: https://dateutil.readthedocs.org/en/latest/rrule.html
:param freq: One of the ``dateutil.rrule`` frequencies
:type freq: str
:param tz: One of the ``pytz`` timezones, defaults to UTC
:type tz: str
:param args: start date <datetime>, interval between each frequency <int>,
max number of recurrences <int>, end date <datetime>
:param kwargs: ``dtstart``, ``interval``, ``count``, ``until``
:return: range of dates
:rtype: list | [
"Use",
"dateutil",
".",
"rrule",
"to",
"create",
"a",
"range",
"of",
"dates",
".",
"The",
"frequency",
"must",
"be",
"a",
"string",
"in",
"the",
"following",
"list",
":",
"YEARLY",
"MONTHLY",
"WEEKLY",
"DAILY",
"HOURLY",
"MINUTELY",
"or",
"SECONDLY",
"."
] | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L14-L36 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | f_energy | def f_energy(ac_power, times):
"""
Calculate the total energy accumulated from AC power at the end of each
timestep between the given times.
:param ac_power: AC Power [W]
:param times: times
:type times: np.datetime64[s]
:return: energy [W*h] and energy times
"""
dt = np.diff(times) # calculate timesteps
# convert timedeltas to quantities
dt = dt.astype('timedelta64[s]').astype('float') / sc_const.hour
# energy accumulate during timestep
energy = dt * (ac_power[:-1] + ac_power[1:]) / 2
return energy, times[1:] | python | def f_energy(ac_power, times):
"""
Calculate the total energy accumulated from AC power at the end of each
timestep between the given times.
:param ac_power: AC Power [W]
:param times: times
:type times: np.datetime64[s]
:return: energy [W*h] and energy times
"""
dt = np.diff(times) # calculate timesteps
# convert timedeltas to quantities
dt = dt.astype('timedelta64[s]').astype('float') / sc_const.hour
# energy accumulate during timestep
energy = dt * (ac_power[:-1] + ac_power[1:]) / 2
return energy, times[1:] | [
"def",
"f_energy",
"(",
"ac_power",
",",
"times",
")",
":",
"dt",
"=",
"np",
".",
"diff",
"(",
"times",
")",
"# calculate timesteps",
"# convert timedeltas to quantities",
"dt",
"=",
"dt",
".",
"astype",
"(",
"'timedelta64[s]'",
")",
".",
"astype",
"(",
"'fl... | Calculate the total energy accumulated from AC power at the end of each
timestep between the given times.
:param ac_power: AC Power [W]
:param times: times
:type times: np.datetime64[s]
:return: energy [W*h] and energy times | [
"Calculate",
"the",
"total",
"energy",
"accumulated",
"from",
"AC",
"power",
"at",
"the",
"end",
"of",
"each",
"timestep",
"between",
"the",
"given",
"times",
"."
] | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L39-L54 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | groupby_freq | def groupby_freq(items, times, freq, wkst='SU'):
"""
Group timeseries by frequency. The frequency must be a string in the
following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or
SECONDLY. The optional weekstart must be a string in the following list:
MO, TU, WE, TH, FR, SA and SU.
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
:param wkst: One of the ``dateutil.rrule`` weekday constants
:type wkst: str
:return: generator
"""
timeseries = zip(times, items) # timeseries map of items
# create a key lambda to group timeseries by
if freq.upper() == 'DAILY':
def key(ts_): return ts_[0].day
elif freq.upper() == 'WEEKLY':
weekday = getattr(rrule, wkst.upper()) # weekday start
# generator that searches times for weekday start
days = (day for day in times if day.weekday() == weekday.weekday)
day0 = days.next() # first weekday start of all times
def key(ts_): return (ts_[0] - day0).days // 7
else:
def key(ts_): return getattr(ts_[0], freq.lower()[:-2])
for k, ts in itertools.groupby(timeseries, key):
yield k, ts | python | def groupby_freq(items, times, freq, wkst='SU'):
"""
Group timeseries by frequency. The frequency must be a string in the
following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or
SECONDLY. The optional weekstart must be a string in the following list:
MO, TU, WE, TH, FR, SA and SU.
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
:param wkst: One of the ``dateutil.rrule`` weekday constants
:type wkst: str
:return: generator
"""
timeseries = zip(times, items) # timeseries map of items
# create a key lambda to group timeseries by
if freq.upper() == 'DAILY':
def key(ts_): return ts_[0].day
elif freq.upper() == 'WEEKLY':
weekday = getattr(rrule, wkst.upper()) # weekday start
# generator that searches times for weekday start
days = (day for day in times if day.weekday() == weekday.weekday)
day0 = days.next() # first weekday start of all times
def key(ts_): return (ts_[0] - day0).days // 7
else:
def key(ts_): return getattr(ts_[0], freq.lower()[:-2])
for k, ts in itertools.groupby(timeseries, key):
yield k, ts | [
"def",
"groupby_freq",
"(",
"items",
",",
"times",
",",
"freq",
",",
"wkst",
"=",
"'SU'",
")",
":",
"timeseries",
"=",
"zip",
"(",
"times",
",",
"items",
")",
"# timeseries map of items",
"# create a key lambda to group timeseries by",
"if",
"freq",
".",
"upper"... | Group timeseries by frequency. The frequency must be a string in the
following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or
SECONDLY. The optional weekstart must be a string in the following list:
MO, TU, WE, TH, FR, SA and SU.
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
:param wkst: One of the ``dateutil.rrule`` weekday constants
:type wkst: str
:return: generator | [
"Group",
"timeseries",
"by",
"frequency",
".",
"The",
"frequency",
"must",
"be",
"a",
"string",
"in",
"the",
"following",
"list",
":",
"YEARLY",
"MONTHLY",
"WEEKLY",
"DAILY",
"HOURLY",
"MINUTELY",
"or",
"SECONDLY",
".",
"The",
"optional",
"weekstart",
"must",
... | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L57-L86 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | f_rollup | def f_rollup(items, times, freq):
"""
Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
"""
rollup = [np.sum(item for __, item in ts)
for _, ts in groupby_freq(items, times, freq)]
return np.array(rollup) | python | def f_rollup(items, times, freq):
"""
Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
"""
rollup = [np.sum(item for __, item in ts)
for _, ts in groupby_freq(items, times, freq)]
return np.array(rollup) | [
"def",
"f_rollup",
"(",
"items",
",",
"times",
",",
"freq",
")",
":",
"rollup",
"=",
"[",
"np",
".",
"sum",
"(",
"item",
"for",
"__",
",",
"item",
"in",
"ts",
")",
"for",
"_",
",",
"ts",
"in",
"groupby_freq",
"(",
"items",
",",
"times",
",",
"f... | Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str | [
"Use",
":",
"func",
":",
"groupby_freq",
"to",
"rollup",
"items"
] | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L89-L100 |
volafiled/python-volapi | volapi/file.py | File.fileupdate | def fileupdate(self, data):
"""Method to update extra metadata fields with dict obtained
through `fileinfo`"""
self.name = data["name"]
add = self.__additional
add["filetype"] = "other"
for filetype in ("book", "image", "video", "audio", "archive"):
if filetype in data:
add["filetype"] = filetype
break
if add["filetype"] in ("image", "video", "audio"):
add["thumb"] = data.get("thumb", dict())
# checksum is md5
add["checksum"] = data["checksum"]
add["expire_time"] = data["expires"] / 1000
add["size"] = data["size"]
add["info"] = data.get(add["filetype"], dict())
add["uploader"] = data["user"]
if self.room.admin:
add["info"].update({"room": data.get("room")})
add["info"].update({"uploader_ip": data.get("uploader_ip")})
self.updated = True | python | def fileupdate(self, data):
"""Method to update extra metadata fields with dict obtained
through `fileinfo`"""
self.name = data["name"]
add = self.__additional
add["filetype"] = "other"
for filetype in ("book", "image", "video", "audio", "archive"):
if filetype in data:
add["filetype"] = filetype
break
if add["filetype"] in ("image", "video", "audio"):
add["thumb"] = data.get("thumb", dict())
# checksum is md5
add["checksum"] = data["checksum"]
add["expire_time"] = data["expires"] / 1000
add["size"] = data["size"]
add["info"] = data.get(add["filetype"], dict())
add["uploader"] = data["user"]
if self.room.admin:
add["info"].update({"room": data.get("room")})
add["info"].update({"uploader_ip": data.get("uploader_ip")})
self.updated = True | [
"def",
"fileupdate",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"name",
"=",
"data",
"[",
"\"name\"",
"]",
"add",
"=",
"self",
".",
"__additional",
"add",
"[",
"\"filetype\"",
"]",
"=",
"\"other\"",
"for",
"filetype",
"in",
"(",
"\"book\"",
",",
... | Method to update extra metadata fields with dict obtained
through `fileinfo` | [
"Method",
"to",
"update",
"extra",
"metadata",
"fields",
"with",
"dict",
"obtained",
"through",
"fileinfo"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L38-L60 |
volafiled/python-volapi | volapi/file.py | File.thumbnail | def thumbnail(self):
"""Returns the thumbnail's url for this image, audio, or video file.
Returns empty string if the file has no thumbnail"""
if self.filetype not in ("video", "image", "audio"):
raise RuntimeError("Only video, audio and image files can have thumbnails")
thumb_srv = self.thumb.get("server")
url = f"https://{thumb_srv}" if thumb_srv else None
return f"{url}/asset/{self.fid}/thumb" if url else "" | python | def thumbnail(self):
"""Returns the thumbnail's url for this image, audio, or video file.
Returns empty string if the file has no thumbnail"""
if self.filetype not in ("video", "image", "audio"):
raise RuntimeError("Only video, audio and image files can have thumbnails")
thumb_srv = self.thumb.get("server")
url = f"https://{thumb_srv}" if thumb_srv else None
return f"{url}/asset/{self.fid}/thumb" if url else "" | [
"def",
"thumbnail",
"(",
"self",
")",
":",
"if",
"self",
".",
"filetype",
"not",
"in",
"(",
"\"video\"",
",",
"\"image\"",
",",
"\"audio\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Only video, audio and image files can have thumbnails\"",
")",
"thumb_srv",
"=",... | Returns the thumbnail's url for this image, audio, or video file.
Returns empty string if the file has no thumbnail | [
"Returns",
"the",
"thumbnail",
"s",
"url",
"for",
"this",
"image",
"audio",
"or",
"video",
"file",
".",
"Returns",
"empty",
"string",
"if",
"the",
"file",
"has",
"no",
"thumbnail"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L81-L89 |
volafiled/python-volapi | volapi/file.py | File.duration | def duration(self):
"""Returns the duration in seconds of this audio or video file"""
if self.filetype not in ("video", "audio"):
raise RuntimeError("Only videos and audio have durations")
return self.info.get("length") or self.info.get("duration") | python | def duration(self):
"""Returns the duration in seconds of this audio or video file"""
if self.filetype not in ("video", "audio"):
raise RuntimeError("Only videos and audio have durations")
return self.info.get("length") or self.info.get("duration") | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"filetype",
"not",
"in",
"(",
"\"video\"",
",",
"\"audio\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Only videos and audio have durations\"",
")",
"return",
"self",
".",
"info",
".",
"get",
"(",... | Returns the duration in seconds of this audio or video file | [
"Returns",
"the",
"duration",
"in",
"seconds",
"of",
"this",
"audio",
"or",
"video",
"file"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L100-L105 |
volafiled/python-volapi | volapi/file.py | File.delete | def delete(self):
""" Remove this file """
self.room.check_owner()
self.conn.make_call("deleteFiles", [self.fid]) | python | def delete(self):
""" Remove this file """
self.room.check_owner()
self.conn.make_call("deleteFiles", [self.fid]) | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"room",
".",
"check_owner",
"(",
")",
"self",
".",
"conn",
".",
"make_call",
"(",
"\"deleteFiles\"",
",",
"[",
"self",
".",
"fid",
"]",
")"
] | Remove this file | [
"Remove",
"this",
"file"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L151-L154 |
volafiled/python-volapi | volapi/file.py | File.timeout | def timeout(self, duration=3600):
""" Timeout the uploader of this file """
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) | python | def timeout(self, duration=3600):
""" Timeout the uploader of this file """
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) | [
"def",
"timeout",
"(",
"self",
",",
"duration",
"=",
"3600",
")",
":",
"self",
".",
"room",
".",
"check_owner",
"(",
")",
"self",
".",
"conn",
".",
"make_call",
"(",
"\"timeoutFile\"",
",",
"self",
".",
"fid",
",",
"duration",
")"
] | Timeout the uploader of this file | [
"Timeout",
"the",
"uploader",
"of",
"this",
"file"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L156-L159 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.set_gid | def set_gid(self):
"""Change the group of the running process"""
if self.group:
gid = getgrnam(self.group).gr_gid
try:
os.setgid(gid)
except Exception:
message = ("Unable to switch ownership to {0}:{1}. " +
"Did you start the daemon as root?")
print(message.format(self.user, self.group))
sys.exit(1) | python | def set_gid(self):
"""Change the group of the running process"""
if self.group:
gid = getgrnam(self.group).gr_gid
try:
os.setgid(gid)
except Exception:
message = ("Unable to switch ownership to {0}:{1}. " +
"Did you start the daemon as root?")
print(message.format(self.user, self.group))
sys.exit(1) | [
"def",
"set_gid",
"(",
"self",
")",
":",
"if",
"self",
".",
"group",
":",
"gid",
"=",
"getgrnam",
"(",
"self",
".",
"group",
")",
".",
"gr_gid",
"try",
":",
"os",
".",
"setgid",
"(",
"gid",
")",
"except",
"Exception",
":",
"message",
"=",
"(",
"\... | Change the group of the running process | [
"Change",
"the",
"group",
"of",
"the",
"running",
"process"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L46-L56 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.set_uid | def set_uid(self):
"""Change the user of the running process"""
if self.user:
uid = getpwnam(self.user).pw_uid
try:
os.setuid(uid)
except Exception:
message = ('Unable to switch ownership to {0}:{1}. ' +
'Did you start the daemon as root?')
print(message.format(self.user, self.group))
sys.exit(1) | python | def set_uid(self):
"""Change the user of the running process"""
if self.user:
uid = getpwnam(self.user).pw_uid
try:
os.setuid(uid)
except Exception:
message = ('Unable to switch ownership to {0}:{1}. ' +
'Did you start the daemon as root?')
print(message.format(self.user, self.group))
sys.exit(1) | [
"def",
"set_uid",
"(",
"self",
")",
":",
"if",
"self",
".",
"user",
":",
"uid",
"=",
"getpwnam",
"(",
"self",
".",
"user",
")",
".",
"pw_uid",
"try",
":",
"os",
".",
"setuid",
"(",
"uid",
")",
"except",
"Exception",
":",
"message",
"=",
"(",
"'Un... | Change the user of the running process | [
"Change",
"the",
"user",
"of",
"the",
"running",
"process"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L58-L68 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.setup_logging | def setup_logging(self):
"""Set up self.logger
This function is called after load_configuration() and after changing
to new user/group IDs (if configured). Logging to syslog using the
root logger is configured by default, you can override this method if
you want something else.
"""
self.logger = logging.getLogger()
if os.path.exists('/dev/log'):
handler = SysLogHandler('/dev/log')
else:
handler = SysLogHandler()
self.logger.addHandler(handler) | python | def setup_logging(self):
"""Set up self.logger
This function is called after load_configuration() and after changing
to new user/group IDs (if configured). Logging to syslog using the
root logger is configured by default, you can override this method if
you want something else.
"""
self.logger = logging.getLogger()
if os.path.exists('/dev/log'):
handler = SysLogHandler('/dev/log')
else:
handler = SysLogHandler()
self.logger.addHandler(handler) | [
"def",
"setup_logging",
"(",
"self",
")",
":",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'/dev/log'",
")",
":",
"handler",
"=",
"SysLogHandler",
"(",
"'/dev/log'",
")",
"else",
":",... | Set up self.logger
This function is called after load_configuration() and after changing
to new user/group IDs (if configured). Logging to syslog using the
root logger is configured by default, you can override this method if
you want something else. | [
"Set",
"up",
"self",
".",
"logger"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L91-L105 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.daemonize | def daemonize(self):
"""
Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as e:
sys.stderr.write('fork #1 failed: %d (%s)\n' %
(e.errno, e.strerror))
sys.exit(1)
os.chdir('/')
os.setsid()
os.umask(0)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as e:
sys.stderr.write('fork #2 failed: %d (%s)\n' %
(e.errno, e.strerror))
sys.exit(1)
# to properly close the fd's, we need to use sys and os:
# http://chromano.me/2011/05/23/starting-python-daemons-via-ssh.html
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
os.closerange(0, 3)
pid = os.getpid()
with open(self.pid_file, 'w+') as fp:
fp.write("%s\n" % pid)
def handler(*args):
raise BaseException("SIGTERM was caught")
signal.signal(signal.SIGTERM, handler)
# atexit functions are "not called when the program is killed by a
# signal not handled by Python". But since SIGTERM is now handled, the
# atexit functions do get called.
atexit.register(self._shutdown) | python | def daemonize(self):
"""
Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as e:
sys.stderr.write('fork #1 failed: %d (%s)\n' %
(e.errno, e.strerror))
sys.exit(1)
os.chdir('/')
os.setsid()
os.umask(0)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as e:
sys.stderr.write('fork #2 failed: %d (%s)\n' %
(e.errno, e.strerror))
sys.exit(1)
# to properly close the fd's, we need to use sys and os:
# http://chromano.me/2011/05/23/starting-python-daemons-via-ssh.html
sys.stdin.close()
sys.stdout.close()
sys.stderr.close()
os.closerange(0, 3)
pid = os.getpid()
with open(self.pid_file, 'w+') as fp:
fp.write("%s\n" % pid)
def handler(*args):
raise BaseException("SIGTERM was caught")
signal.signal(signal.SIGTERM, handler)
# atexit functions are "not called when the program is killed by a
# signal not handled by Python". But since SIGTERM is now handled, the
# atexit functions do get called.
atexit.register(self._shutdown) | [
"def",
"daemonize",
"(",
"self",
")",
":",
"try",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
">",
"0",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"OSError",
"as",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'for... | Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 | [
"Do",
"the",
"UNIX",
"double",
"-",
"fork",
"magic",
"see",
"Stevens",
"Advanced",
"Programming",
"in",
"the",
"UNIX",
"Environment",
"for",
"details",
"(",
"ISBN",
"0201563177",
")",
"http",
":",
"//",
"www",
".",
"erlenstar",
".",
"demon",
".",
"co",
"... | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L123-L165 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.start | def start(self):
"""Start the daemon"""
if self._already_running():
message = 'pid file %s already exists. Daemon already running?\n'
sys.stderr.write(message % self.pid_file)
return 0
self.set_gid()
self.set_uid()
# Create log files (if configured) with the new user/group. Creating
# them as root would allow symlink exploits.
self.setup_logging()
# Create pid file with new user/group. This ensures we will be able
# to delete the file when shutting down.
self.daemonize()
try:
self.run()
except Exception:
self.logger.exception('Exception while running the daemon:')
return 1
return 0 | python | def start(self):
"""Start the daemon"""
if self._already_running():
message = 'pid file %s already exists. Daemon already running?\n'
sys.stderr.write(message % self.pid_file)
return 0
self.set_gid()
self.set_uid()
# Create log files (if configured) with the new user/group. Creating
# them as root would allow symlink exploits.
self.setup_logging()
# Create pid file with new user/group. This ensures we will be able
# to delete the file when shutting down.
self.daemonize()
try:
self.run()
except Exception:
self.logger.exception('Exception while running the daemon:')
return 1
return 0 | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_already_running",
"(",
")",
":",
"message",
"=",
"'pid file %s already exists. Daemon already running?\\n'",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
"%",
"self",
".",
"pid_file",
")",
"ret... | Start the daemon | [
"Start",
"the",
"daemon"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L181-L200 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.stop | def stop(self):
"""Stop the daemon"""
if self._already_running():
return self.reliable_kill()
else:
# FIXME: misleading error message
message = 'Daemon not running, nothing to do.\n'
sys.stderr.write(message)
return 0 | python | def stop(self):
"""Stop the daemon"""
if self._already_running():
return self.reliable_kill()
else:
# FIXME: misleading error message
message = 'Daemon not running, nothing to do.\n'
sys.stderr.write(message)
return 0 | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_already_running",
"(",
")",
":",
"return",
"self",
".",
"reliable_kill",
"(",
")",
"else",
":",
"# FIXME: misleading error message",
"message",
"=",
"'Daemon not running, nothing to do.\\n'",
"sys",
".",
... | Stop the daemon | [
"Stop",
"the",
"daemon"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L223-L231 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.status | def status(self):
"""Determine the status of the daemon"""
my_name = os.path.basename(sys.argv[0])
if self._already_running():
message = "{0} (pid {1}) is running...\n".format(my_name, self.pid)
sys.stdout.write(message)
return 0
sys.stdout.write("{0} is stopped\n".format(my_name))
return 3 | python | def status(self):
"""Determine the status of the daemon"""
my_name = os.path.basename(sys.argv[0])
if self._already_running():
message = "{0} (pid {1}) is running...\n".format(my_name, self.pid)
sys.stdout.write(message)
return 0
sys.stdout.write("{0} is stopped\n".format(my_name))
return 3 | [
"def",
"status",
"(",
"self",
")",
":",
"my_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"if",
"self",
".",
"_already_running",
"(",
")",
":",
"message",
"=",
"\"{0} (pid {1}) is running...\\n\"",
".",
"... | Determine the status of the daemon | [
"Determine",
"the",
"status",
"of",
"the",
"daemon"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L242-L250 |
nigma/django-easy-pdf | easy_pdf/rendering.py | fetch_resources | def fetch_resources(uri, rel):
"""
Retrieves embeddable resource from given ``uri``.
For now only local resources (images, fonts) are supported.
:param str uri: path or url to image or font resource
:returns: path to local resource file.
:rtype: str
:raises: :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException`
"""
if settings.STATIC_URL and uri.startswith(settings.STATIC_URL):
path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ""))
elif settings.MEDIA_URL and uri.startswith(settings.MEDIA_URL):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
else:
path = os.path.join(settings.STATIC_ROOT, uri)
if not os.path.isfile(path):
raise UnsupportedMediaPathException(
"media urls must start with {} or {}".format(
settings.MEDIA_ROOT, settings.STATIC_ROOT
)
)
return path.replace("\\", "/") | python | def fetch_resources(uri, rel):
"""
Retrieves embeddable resource from given ``uri``.
For now only local resources (images, fonts) are supported.
:param str uri: path or url to image or font resource
:returns: path to local resource file.
:rtype: str
:raises: :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException`
"""
if settings.STATIC_URL and uri.startswith(settings.STATIC_URL):
path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, ""))
elif settings.MEDIA_URL and uri.startswith(settings.MEDIA_URL):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
else:
path = os.path.join(settings.STATIC_ROOT, uri)
if not os.path.isfile(path):
raise UnsupportedMediaPathException(
"media urls must start with {} or {}".format(
settings.MEDIA_ROOT, settings.STATIC_ROOT
)
)
return path.replace("\\", "/") | [
"def",
"fetch_resources",
"(",
"uri",
",",
"rel",
")",
":",
"if",
"settings",
".",
"STATIC_URL",
"and",
"uri",
".",
"startswith",
"(",
"settings",
".",
"STATIC_URL",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"STATIC_R... | Retrieves embeddable resource from given ``uri``.
For now only local resources (images, fonts) are supported.
:param str uri: path or url to image or font resource
:returns: path to local resource file.
:rtype: str
:raises: :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException` | [
"Retrieves",
"embeddable",
"resource",
"from",
"given",
"uri",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L23-L48 |
nigma/django-easy-pdf | easy_pdf/rendering.py | html_to_pdf | def html_to_pdf(content, encoding="utf-8",
link_callback=fetch_resources, **kwargs):
"""
Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`
"""
src = BytesIO(content.encode(encoding))
dest = BytesIO()
pdf = pisa.pisaDocument(src, dest, encoding=encoding,
link_callback=link_callback, **kwargs)
if pdf.err:
logger.error("Error rendering PDF document")
for entry in pdf.log:
if entry[0] == xhtml2pdf.default.PML_ERROR:
logger_x2p.error("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])
raise PDFRenderingError("Errors rendering PDF", content=content, log=pdf.log)
if pdf.warn:
for entry in pdf.log:
if entry[0] == xhtml2pdf.default.PML_WARNING:
logger_x2p.warning("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])
return dest.getvalue() | python | def html_to_pdf(content, encoding="utf-8",
link_callback=fetch_resources, **kwargs):
"""
Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`
"""
src = BytesIO(content.encode(encoding))
dest = BytesIO()
pdf = pisa.pisaDocument(src, dest, encoding=encoding,
link_callback=link_callback, **kwargs)
if pdf.err:
logger.error("Error rendering PDF document")
for entry in pdf.log:
if entry[0] == xhtml2pdf.default.PML_ERROR:
logger_x2p.error("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])
raise PDFRenderingError("Errors rendering PDF", content=content, log=pdf.log)
if pdf.warn:
for entry in pdf.log:
if entry[0] == xhtml2pdf.default.PML_WARNING:
logger_x2p.warning("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])
return dest.getvalue() | [
"def",
"html_to_pdf",
"(",
"content",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"link_callback",
"=",
"fetch_resources",
",",
"*",
"*",
"kwargs",
")",
":",
"src",
"=",
"BytesIO",
"(",
"content",
".",
"encode",
"(",
"encoding",
")",
")",
"dest",
"=",
"Bytes... | Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError` | [
"Converts",
"html",
"content",
"into",
"PDF",
"document",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L51-L78 |
nigma/django-easy-pdf | easy_pdf/rendering.py | make_response | def make_response(content, filename=None, content_type="application/pdf"):
"""
Wraps content into HTTP response.
If ``filename`` is specified then ``Content-Disposition: attachment``
header is added to the response.
Default ``Content-Type`` is ``application/pdf``.
:param bytes content: response content
:param str filename: optional filename for file download
:param str content_type: response content type
:rtype: :class:`django.http.HttpResponse`
"""
response = HttpResponse(content, content_type=content_type)
if filename is not None:
response["Content-Disposition"] = "attachment; %s" % encode_filename(filename)
return response | python | def make_response(content, filename=None, content_type="application/pdf"):
"""
Wraps content into HTTP response.
If ``filename`` is specified then ``Content-Disposition: attachment``
header is added to the response.
Default ``Content-Type`` is ``application/pdf``.
:param bytes content: response content
:param str filename: optional filename for file download
:param str content_type: response content type
:rtype: :class:`django.http.HttpResponse`
"""
response = HttpResponse(content, content_type=content_type)
if filename is not None:
response["Content-Disposition"] = "attachment; %s" % encode_filename(filename)
return response | [
"def",
"make_response",
"(",
"content",
",",
"filename",
"=",
"None",
",",
"content_type",
"=",
"\"application/pdf\"",
")",
":",
"response",
"=",
"HttpResponse",
"(",
"content",
",",
"content_type",
"=",
"content_type",
")",
"if",
"filename",
"is",
"not",
"Non... | Wraps content into HTTP response.
If ``filename`` is specified then ``Content-Disposition: attachment``
header is added to the response.
Default ``Content-Type`` is ``application/pdf``.
:param bytes content: response content
:param str filename: optional filename for file download
:param str content_type: response content type
:rtype: :class:`django.http.HttpResponse` | [
"Wraps",
"content",
"into",
"HTTP",
"response",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L102-L119 |
nigma/django-easy-pdf | easy_pdf/rendering.py | render_to_pdf | def render_to_pdf(template, context, using=None, request=None, encoding="utf-8", **kwargs):
"""
Create PDF document from Django html template.
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:returns: rendered PDF
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`, :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException`
"""
content = loader.render_to_string(template, context, request=request, using=using)
return html_to_pdf(content, encoding, **kwargs) | python | def render_to_pdf(template, context, using=None, request=None, encoding="utf-8", **kwargs):
"""
Create PDF document from Django html template.
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:returns: rendered PDF
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`, :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException`
"""
content = loader.render_to_string(template, context, request=request, using=using)
return html_to_pdf(content, encoding, **kwargs) | [
"def",
"render_to_pdf",
"(",
"template",
",",
"context",
",",
"using",
"=",
"None",
",",
"request",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"loader",
".",
"render_to_string",
"(",
"template",
","... | Create PDF document from Django html template.
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:returns: rendered PDF
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`, :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException` | [
"Create",
"PDF",
"document",
"from",
"Django",
"html",
"template",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L122-L138 |
nigma/django-easy-pdf | easy_pdf/rendering.py | render_to_pdf_response | def render_to_pdf_response(request, template, context, using=None, filename=None,
encoding="utf-8", **kwargs):
"""
Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header will be set to ``attachment`` making the browser display
a "Save as.." dialog.
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:rtype: :class:`django.http.HttpResponse`
"""
try:
pdf = render_to_pdf(template, context, using=using, encoding=encoding, **kwargs)
return make_response(pdf, filename)
except PDFRenderingError as e:
logger.exception(e.message)
return HttpResponse(e.message) | python | def render_to_pdf_response(request, template, context, using=None, filename=None,
encoding="utf-8", **kwargs):
"""
Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header will be set to ``attachment`` making the browser display
a "Save as.." dialog.
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:rtype: :class:`django.http.HttpResponse`
"""
try:
pdf = render_to_pdf(template, context, using=using, encoding=encoding, **kwargs)
return make_response(pdf, filename)
except PDFRenderingError as e:
logger.exception(e.message)
return HttpResponse(e.message) | [
"def",
"render_to_pdf_response",
"(",
"request",
",",
"template",
",",
"context",
",",
"using",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pdf",
"=",
"render_to_pdf",
"(",... | Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header will be set to ``attachment`` making the browser display
a "Save as.." dialog.
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:rtype: :class:`django.http.HttpResponse` | [
"Renders",
"a",
"PDF",
"response",
"using",
"given",
"request",
"template",
"and",
"context",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L141-L162 |
nigma/django-easy-pdf | easy_pdf/views.py | PDFTemplateResponseMixin.get_pdf_response | def get_pdf_response(self, context, **response_kwargs):
"""
Renders PDF document and prepares response.
:returns: Django HTTP response
:rtype: :class:`django.http.HttpResponse`
"""
return render_to_pdf_response(
request=self.request,
template=self.get_template_names(),
context=context,
using=self.template_engine,
filename=self.get_pdf_filename(),
**self.get_pdf_kwargs()
) | python | def get_pdf_response(self, context, **response_kwargs):
"""
Renders PDF document and prepares response.
:returns: Django HTTP response
:rtype: :class:`django.http.HttpResponse`
"""
return render_to_pdf_response(
request=self.request,
template=self.get_template_names(),
context=context,
using=self.template_engine,
filename=self.get_pdf_filename(),
**self.get_pdf_kwargs()
) | [
"def",
"get_pdf_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"return",
"render_to_pdf_response",
"(",
"request",
"=",
"self",
".",
"request",
",",
"template",
"=",
"self",
".",
"get_template_names",
"(",
")",
",",
"cont... | Renders PDF document and prepares response.
:returns: Django HTTP response
:rtype: :class:`django.http.HttpResponse` | [
"Renders",
"PDF",
"document",
"and",
"prepares",
"response",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/views.py#L47-L61 |
lk-geimfari/expynent | expynent/compiled.py | compile_patterns_in_dictionary | def compile_patterns_in_dictionary(dictionary):
"""
Replace all strings in dictionary with compiled
version of themselves and return dictionary.
"""
for key, value in dictionary.items():
if isinstance(value, str):
dictionary[key] = re.compile(value)
elif isinstance(value, dict):
compile_patterns_in_dictionary(value)
return dictionary | python | def compile_patterns_in_dictionary(dictionary):
"""
Replace all strings in dictionary with compiled
version of themselves and return dictionary.
"""
for key, value in dictionary.items():
if isinstance(value, str):
dictionary[key] = re.compile(value)
elif isinstance(value, dict):
compile_patterns_in_dictionary(value)
return dictionary | [
"def",
"compile_patterns_in_dictionary",
"(",
"dictionary",
")",
":",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"dictionary",
"[",
"key",
"]",
"=",
"re",
".",
"c... | Replace all strings in dictionary with compiled
version of themselves and return dictionary. | [
"Replace",
"all",
"strings",
"in",
"dictionary",
"with",
"compiled",
"version",
"of",
"themselves",
"and",
"return",
"dictionary",
"."
] | train | https://github.com/lk-geimfari/expynent/blob/85a1f6e681f669238202becb934381dd9a2313f4/expynent/compiled.py#L10-L20 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.validate_options | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'delimiters':
for d in v:
if not isinstance(d, (dict, OrderedDict)):
raise ValueError("{}: 'delimters' entries must be of dict type.".format(self.__class__.__name__))
for key, value in d.items():
if key not in ('open', 'close', 'content'):
raise KeyError(
"{}: '{}' is not a valid key for a 'delimeters' entry.".format(self.__class__.__name__, key)
)
if not isinstance(value, str):
raise ValueError(
"{}: 'delimeters' '{}' key should have str values.".format(self.__class__.__name__, value)
) | python | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'delimiters':
for d in v:
if not isinstance(d, (dict, OrderedDict)):
raise ValueError("{}: 'delimters' entries must be of dict type.".format(self.__class__.__name__))
for key, value in d.items():
if key not in ('open', 'close', 'content'):
raise KeyError(
"{}: '{}' is not a valid key for a 'delimeters' entry.".format(self.__class__.__name__, key)
)
if not isinstance(value, str):
raise ValueError(
"{}: 'delimeters' '{}' key should have str values.".format(self.__class__.__name__, value)
) | [
"def",
"validate_options",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"super",
"(",
")",
".",
"validate_options",
"(",
"k",
",",
"v",
")",
"if",
"k",
"==",
"'delimiters'",
":",
"for",
"d",
"in",
"v",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",... | Validate options. | [
"Validate",
"options",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L30-L46 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.setup | def setup(self):
"""Setup."""
self.context_visible_first = self.config['context_visible_first']
self.delimiters = []
self.escapes = None
self.line_endings = self.config['normalize_line_endings']
escapes = []
for delimiter in self.config['delimiters']:
if not isinstance(delimiter, dict):
continue
group = util.random_name_gen()
while (
group in delimiter['open'] or
group in delimiter['close'] or
group in delimiter.get('content', DEFAULT_CONTENT)
):
group = util.random_name_gen()
pattern = r'%s(?P<%s>%s)(?:%s|\Z)' % (
delimiter['open'],
group,
delimiter.get('content', DEFAULT_CONTENT),
delimiter['close']
)
self.delimiters.append((re.compile(pattern, re.M), group))
escapes = self.config['escapes']
if escapes:
self.escapes = re.compile(escapes) | python | def setup(self):
"""Setup."""
self.context_visible_first = self.config['context_visible_first']
self.delimiters = []
self.escapes = None
self.line_endings = self.config['normalize_line_endings']
escapes = []
for delimiter in self.config['delimiters']:
if not isinstance(delimiter, dict):
continue
group = util.random_name_gen()
while (
group in delimiter['open'] or
group in delimiter['close'] or
group in delimiter.get('content', DEFAULT_CONTENT)
):
group = util.random_name_gen()
pattern = r'%s(?P<%s>%s)(?:%s|\Z)' % (
delimiter['open'],
group,
delimiter.get('content', DEFAULT_CONTENT),
delimiter['close']
)
self.delimiters.append((re.compile(pattern, re.M), group))
escapes = self.config['escapes']
if escapes:
self.escapes = re.compile(escapes) | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"context_visible_first",
"=",
"self",
".",
"config",
"[",
"'context_visible_first'",
"]",
"self",
".",
"delimiters",
"=",
"[",
"]",
"self",
".",
"escapes",
"=",
"None",
"self",
".",
"line_endings",
"=",
... | Setup. | [
"Setup",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L48-L76 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.filter | def filter(self, source_file, encoding): # noqa A001
"""Parse file."""
with codecs.open(source_file, 'r', encoding=encoding) as f:
text = f.read()
return [filters.SourceText(self._filter(text), source_file, encoding, 'context')] | python | def filter(self, source_file, encoding): # noqa A001
"""Parse file."""
with codecs.open(source_file, 'r', encoding=encoding) as f:
text = f.read()
return [filters.SourceText(self._filter(text), source_file, encoding, 'context')] | [
"def",
"filter",
"(",
"self",
",",
"source_file",
",",
"encoding",
")",
":",
"# noqa A001",
"with",
"codecs",
".",
"open",
"(",
"source_file",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",... | Parse file. | [
"Parse",
"file",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L78-L84 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.sfilter | def sfilter(self, source):
"""Filter."""
return [filters.SourceText(self._filter(source.text), source.context, source.encoding, 'context')] | python | def sfilter(self, source):
"""Filter."""
return [filters.SourceText(self._filter(source.text), source.context, source.encoding, 'context')] | [
"def",
"sfilter",
"(",
"self",
",",
"source",
")",
":",
"return",
"[",
"filters",
".",
"SourceText",
"(",
"self",
".",
"_filter",
"(",
"source",
".",
"text",
")",
",",
"source",
".",
"context",
",",
"source",
".",
"encoding",
",",
"'context'",
")",
"... | Filter. | [
"Filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L86-L89 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter._filter | def _filter(self, text):
"""Context delimiter filter."""
if self.line_endings:
text = self.norm_nl(text)
new_text = []
index = 0
last = 0
end = len(text)
while index < end:
m = self.escapes.match(text, pos=index) if self.escapes else None
if m:
index = m.end(0)
continue
handled = False
for delimiter in self.delimiters:
m = delimiter[0].match(text, pos=index)
if m:
if self.context_visible_first is True:
new_text.append(text[last:m.start(0)])
else:
new_text.append(m.group(delimiter[1]))
index = m.end(0)
last = index
handled = True
break
if handled:
continue
index += 1
if last < end and self.context_visible_first is True:
new_text.append(text[last:end])
return ' '.join(new_text) | python | def _filter(self, text):
"""Context delimiter filter."""
if self.line_endings:
text = self.norm_nl(text)
new_text = []
index = 0
last = 0
end = len(text)
while index < end:
m = self.escapes.match(text, pos=index) if self.escapes else None
if m:
index = m.end(0)
continue
handled = False
for delimiter in self.delimiters:
m = delimiter[0].match(text, pos=index)
if m:
if self.context_visible_first is True:
new_text.append(text[last:m.start(0)])
else:
new_text.append(m.group(delimiter[1]))
index = m.end(0)
last = index
handled = True
break
if handled:
continue
index += 1
if last < end and self.context_visible_first is True:
new_text.append(text[last:end])
return ' '.join(new_text) | [
"def",
"_filter",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"line_endings",
":",
"text",
"=",
"self",
".",
"norm_nl",
"(",
"text",
")",
"new_text",
"=",
"[",
"]",
"index",
"=",
"0",
"last",
"=",
"0",
"end",
"=",
"len",
"(",
"text",
... | Context delimiter filter. | [
"Context",
"delimiter",
"filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L91-L124 |
horazont/aioopenssl | aioopenssl/__init__.py | create_starttls_connection | def create_starttls_connection(
loop,
protocol_factory,
host=None,
port=None,
*,
sock=None,
ssl_context_factory=None,
use_starttls=False,
local_addr=None,
**kwargs):
"""
Create a connection which can later be upgraded to use TLS.
.. versionchanged:: 0.4
The `local_addr` argument was added.
:param loop: The event loop to use.
:type loop: :class:`asyncio.BaseEventLoop`
:param protocol_factory: Factory for the protocol for the connection
:param host: The host name or address to connect to
:type host: :class:`str` or :data:`None`
:param port: The port to connect to
:type port: :class:`int` or :data:`None`
:param sock: A socket to wrap (conflicts with `host` and `port`)
:type sock: :class:`socket.socket`
:param ssl_context_factory: Function which returns a
:class:`OpenSSL.SSL.Context` to use for TLS operations
:param use_starttls: Flag to control whether TLS is negotiated right away
or deferredly.
:type use_starttls: :class:`bool`
:param local_addr: Address to bind to
This is roughly a copy of the asyncio implementation of
:meth:`asyncio.BaseEventLoop.create_connection`. It returns a pair
``(transport, protocol)``, where `transport` is a newly created
:class:`STARTTLSTransport` instance. Further keyword arguments are
forwarded to the constructor of :class:`STARTTLSTransport`.
`loop` must be a :class:`asyncio.BaseEventLoop`, with support for
:meth:`asyncio.BaseEventLoop.add_reader` and the corresponding writer and
removal functions for sockets. This is typically a selector type event
loop.
`protocol_factory` must be a callable which (without any arguments) returns
a :class:`asyncio.Protocol` which will be connected to the STARTTLS
transport.
`host` and `port` must be a hostname and a port number, or both
:data:`None`. Both must be :data:`None`, if and only if `sock` is not
:data:`None`. In that case, `sock` is used instead of a newly created
socket. `sock` is put into non-blocking mode and must be a stream socket.
If `use_starttls` is :data:`True`, no TLS handshake will be performed
initially. Instead, the connection is established without any
transport-layer security. It is expected that the
:meth:`STARTTLSTransport.starttls` method is used when the application
protocol requires TLS. If `use_starttls` is :data:`False`, the TLS
handshake is initiated right away.
`local_addr` may be an address to bind this side of the socket to. If
omitted or :data:`None`, the local address is assigned by the operating
system.
This coroutine returns when the stream is established. If `use_starttls` is
:data:`False`, this means that the full TLS handshake has to be finished
for this coroutine to return. Otherwise, no TLS handshake takes place. It
must be invoked using the :meth:`STARTTLSTransport.starttls` coroutine.
"""
if host is not None and port is not None:
host_addrs = yield from loop.getaddrinfo(
host, port,
type=socket.SOCK_STREAM)
exceptions = []
for family, type, proto, cname, address in host_addrs:
sock = None
try:
sock = socket.socket(family=family, type=type, proto=proto)
sock.setblocking(False)
if local_addr is not None:
sock.bind(local_addr)
yield from loop.sock_connect(sock, address)
except OSError as exc:
if sock is not None:
sock.close()
exceptions.append(exc)
else:
break
else:
if len(exceptions) == 1:
raise exceptions[0]
model = str(exceptions[0])
if all(str(exc) == model for exc in exceptions):
raise exceptions[0]
try:
from aioxmpp.errors import MultiOSError
except ImportError:
MultiOSError = OSError
exc = MultiOSError(
"could not connect to [{}]:{}".format(host, port),
exceptions)
raise exc
elif sock is None:
raise ValueError("sock must not be None if host and/or port are None")
else:
sock.setblocking(False)
protocol = protocol_factory()
waiter = asyncio.Future(loop=loop)
transport = STARTTLSTransport(loop, sock, protocol,
ssl_context_factory=ssl_context_factory,
waiter=waiter,
use_starttls=use_starttls,
**kwargs)
yield from waiter
return transport, protocol | python | def create_starttls_connection(
loop,
protocol_factory,
host=None,
port=None,
*,
sock=None,
ssl_context_factory=None,
use_starttls=False,
local_addr=None,
**kwargs):
"""
Create a connection which can later be upgraded to use TLS.
.. versionchanged:: 0.4
The `local_addr` argument was added.
:param loop: The event loop to use.
:type loop: :class:`asyncio.BaseEventLoop`
:param protocol_factory: Factory for the protocol for the connection
:param host: The host name or address to connect to
:type host: :class:`str` or :data:`None`
:param port: The port to connect to
:type port: :class:`int` or :data:`None`
:param sock: A socket to wrap (conflicts with `host` and `port`)
:type sock: :class:`socket.socket`
:param ssl_context_factory: Function which returns a
:class:`OpenSSL.SSL.Context` to use for TLS operations
:param use_starttls: Flag to control whether TLS is negotiated right away
or deferredly.
:type use_starttls: :class:`bool`
:param local_addr: Address to bind to
This is roughly a copy of the asyncio implementation of
:meth:`asyncio.BaseEventLoop.create_connection`. It returns a pair
``(transport, protocol)``, where `transport` is a newly created
:class:`STARTTLSTransport` instance. Further keyword arguments are
forwarded to the constructor of :class:`STARTTLSTransport`.
`loop` must be a :class:`asyncio.BaseEventLoop`, with support for
:meth:`asyncio.BaseEventLoop.add_reader` and the corresponding writer and
removal functions for sockets. This is typically a selector type event
loop.
`protocol_factory` must be a callable which (without any arguments) returns
a :class:`asyncio.Protocol` which will be connected to the STARTTLS
transport.
`host` and `port` must be a hostname and a port number, or both
:data:`None`. Both must be :data:`None`, if and only if `sock` is not
:data:`None`. In that case, `sock` is used instead of a newly created
socket. `sock` is put into non-blocking mode and must be a stream socket.
If `use_starttls` is :data:`True`, no TLS handshake will be performed
initially. Instead, the connection is established without any
transport-layer security. It is expected that the
:meth:`STARTTLSTransport.starttls` method is used when the application
protocol requires TLS. If `use_starttls` is :data:`False`, the TLS
handshake is initiated right away.
`local_addr` may be an address to bind this side of the socket to. If
omitted or :data:`None`, the local address is assigned by the operating
system.
This coroutine returns when the stream is established. If `use_starttls` is
:data:`False`, this means that the full TLS handshake has to be finished
for this coroutine to return. Otherwise, no TLS handshake takes place. It
must be invoked using the :meth:`STARTTLSTransport.starttls` coroutine.
"""
if host is not None and port is not None:
host_addrs = yield from loop.getaddrinfo(
host, port,
type=socket.SOCK_STREAM)
exceptions = []
for family, type, proto, cname, address in host_addrs:
sock = None
try:
sock = socket.socket(family=family, type=type, proto=proto)
sock.setblocking(False)
if local_addr is not None:
sock.bind(local_addr)
yield from loop.sock_connect(sock, address)
except OSError as exc:
if sock is not None:
sock.close()
exceptions.append(exc)
else:
break
else:
if len(exceptions) == 1:
raise exceptions[0]
model = str(exceptions[0])
if all(str(exc) == model for exc in exceptions):
raise exceptions[0]
try:
from aioxmpp.errors import MultiOSError
except ImportError:
MultiOSError = OSError
exc = MultiOSError(
"could not connect to [{}]:{}".format(host, port),
exceptions)
raise exc
elif sock is None:
raise ValueError("sock must not be None if host and/or port are None")
else:
sock.setblocking(False)
protocol = protocol_factory()
waiter = asyncio.Future(loop=loop)
transport = STARTTLSTransport(loop, sock, protocol,
ssl_context_factory=ssl_context_factory,
waiter=waiter,
use_starttls=use_starttls,
**kwargs)
yield from waiter
return transport, protocol | [
"def",
"create_starttls_connection",
"(",
"loop",
",",
"protocol_factory",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"*",
",",
"sock",
"=",
"None",
",",
"ssl_context_factory",
"=",
"None",
",",
"use_starttls",
"=",
"False",
",",
"local_addr",
... | Create a connection which can later be upgraded to use TLS.
.. versionchanged:: 0.4
The `local_addr` argument was added.
:param loop: The event loop to use.
:type loop: :class:`asyncio.BaseEventLoop`
:param protocol_factory: Factory for the protocol for the connection
:param host: The host name or address to connect to
:type host: :class:`str` or :data:`None`
:param port: The port to connect to
:type port: :class:`int` or :data:`None`
:param sock: A socket to wrap (conflicts with `host` and `port`)
:type sock: :class:`socket.socket`
:param ssl_context_factory: Function which returns a
:class:`OpenSSL.SSL.Context` to use for TLS operations
:param use_starttls: Flag to control whether TLS is negotiated right away
or deferredly.
:type use_starttls: :class:`bool`
:param local_addr: Address to bind to
This is roughly a copy of the asyncio implementation of
:meth:`asyncio.BaseEventLoop.create_connection`. It returns a pair
``(transport, protocol)``, where `transport` is a newly created
:class:`STARTTLSTransport` instance. Further keyword arguments are
forwarded to the constructor of :class:`STARTTLSTransport`.
`loop` must be a :class:`asyncio.BaseEventLoop`, with support for
:meth:`asyncio.BaseEventLoop.add_reader` and the corresponding writer and
removal functions for sockets. This is typically a selector type event
loop.
`protocol_factory` must be a callable which (without any arguments) returns
a :class:`asyncio.Protocol` which will be connected to the STARTTLS
transport.
`host` and `port` must be a hostname and a port number, or both
:data:`None`. Both must be :data:`None`, if and only if `sock` is not
:data:`None`. In that case, `sock` is used instead of a newly created
socket. `sock` is put into non-blocking mode and must be a stream socket.
If `use_starttls` is :data:`True`, no TLS handshake will be performed
initially. Instead, the connection is established without any
transport-layer security. It is expected that the
:meth:`STARTTLSTransport.starttls` method is used when the application
protocol requires TLS. If `use_starttls` is :data:`False`, the TLS
handshake is initiated right away.
`local_addr` may be an address to bind this side of the socket to. If
omitted or :data:`None`, the local address is assigned by the operating
system.
This coroutine returns when the stream is established. If `use_starttls` is
:data:`False`, this means that the full TLS handshake has to be finished
for this coroutine to return. Otherwise, no TLS handshake takes place. It
must be invoked using the :meth:`STARTTLSTransport.starttls` coroutine. | [
"Create",
"a",
"connection",
"which",
"can",
"later",
"be",
"upgraded",
"to",
"use",
"TLS",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L726-L849 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport._call_connection_lost_and_clean_up | def _call_connection_lost_and_clean_up(self, exc):
"""
Clean up all resources and call the protocols connection lost method.
"""
self._state = _State.CLOSED
try:
self._protocol.connection_lost(exc)
finally:
self._rawsock.close()
if self._tls_conn is not None:
self._tls_conn.set_app_data(None)
self._tls_conn = None
self._rawsock = None
self._protocol = None
self._loop = None | python | def _call_connection_lost_and_clean_up(self, exc):
"""
Clean up all resources and call the protocols connection lost method.
"""
self._state = _State.CLOSED
try:
self._protocol.connection_lost(exc)
finally:
self._rawsock.close()
if self._tls_conn is not None:
self._tls_conn.set_app_data(None)
self._tls_conn = None
self._rawsock = None
self._protocol = None
self._loop = None | [
"def",
"_call_connection_lost_and_clean_up",
"(",
"self",
",",
"exc",
")",
":",
"self",
".",
"_state",
"=",
"_State",
".",
"CLOSED",
"try",
":",
"self",
".",
"_protocol",
".",
"connection_lost",
"(",
"exc",
")",
"finally",
":",
"self",
".",
"_rawsock",
"."... | Clean up all resources and call the protocols connection lost method. | [
"Clean",
"up",
"all",
"resources",
"and",
"call",
"the",
"protocols",
"connection",
"lost",
"method",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L271-L286 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.abort | def abort(self):
"""
Immediately close the stream, without sending remaining buffers or
performing a proper shutdown.
"""
if self._state == _State.CLOSED:
self._invalid_state("abort() called")
return
self._force_close(None) | python | def abort(self):
"""
Immediately close the stream, without sending remaining buffers or
performing a proper shutdown.
"""
if self._state == _State.CLOSED:
self._invalid_state("abort() called")
return
self._force_close(None) | [
"def",
"abort",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"CLOSED",
":",
"self",
".",
"_invalid_state",
"(",
"\"abort() called\"",
")",
"return",
"self",
".",
"_force_close",
"(",
"None",
")"
] | Immediately close the stream, without sending remaining buffers or
performing a proper shutdown. | [
"Immediately",
"close",
"the",
"stream",
"without",
"sending",
"remaining",
"buffers",
"or",
"performing",
"a",
"proper",
"shutdown",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L576-L585 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.close | def close(self):
"""
Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitted.
"""
if self._state == _State.CLOSED:
self._invalid_state("close() called")
return
if self._state == _State.TLS_HANDSHAKING:
# hard-close
self._force_close(None)
elif self._state == _State.TLS_SHUTTING_DOWN:
# shut down in progress, nothing to do
pass
elif self._buffer:
# there is data to be send left, first wait for it to transmit ...
self._closing = True
elif self._state.tls_started:
# normal TLS state, nothing left to transmit, shut down
self._tls_shutdown()
else:
# normal non-TLS state, nothing left to transmit, close
self._raw_shutdown() | python | def close(self):
"""
Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitted.
"""
if self._state == _State.CLOSED:
self._invalid_state("close() called")
return
if self._state == _State.TLS_HANDSHAKING:
# hard-close
self._force_close(None)
elif self._state == _State.TLS_SHUTTING_DOWN:
# shut down in progress, nothing to do
pass
elif self._buffer:
# there is data to be send left, first wait for it to transmit ...
self._closing = True
elif self._state.tls_started:
# normal TLS state, nothing left to transmit, shut down
self._tls_shutdown()
else:
# normal non-TLS state, nothing left to transmit, close
self._raw_shutdown() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"CLOSED",
":",
"self",
".",
"_invalid_state",
"(",
"\"close() called\"",
")",
"return",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"TLS_HANDSHAKING",
":",
"# ... | Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitted. | [
"Close",
"the",
"stream",
".",
"This",
"performs",
"a",
"proper",
"stream",
"shutdown",
"except",
"if",
"the",
"stream",
"is",
"currently",
"performing",
"a",
"TLS",
"handshake",
".",
"In",
"that",
"case",
"calling",
":",
"meth",
":",
"close",
"is",
"equiv... | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L601-L628 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.starttls | def starttls(self, ssl_context=None,
post_handshake_callback=None):
"""
Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructor. If `post_handshake_callback` is set, it overrides the
`post_handshake_callback` passed to the constructor.
.. versionchanged:: 0.4
This method is now a barrier with respect to reads and writes:
before the handshake is completed (including the post handshake
callback, if any), no data is received or sent.
"""
if self._state != _State.RAW_OPEN or self._closing:
raise self._invalid_state("starttls() called")
if ssl_context is not None:
self._ssl_context = ssl_context
self._extra.update(
sslcontext=ssl_context
)
else:
self._ssl_context = self._ssl_context_factory(self)
if post_handshake_callback is not None:
self._tls_post_handshake_callback = post_handshake_callback
self._waiter = asyncio.Future()
self._waiter.add_done_callback(self._waiter_done)
self._initiate_tls()
try:
yield from self._waiter
finally:
self._waiter = None | python | def starttls(self, ssl_context=None,
post_handshake_callback=None):
"""
Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructor. If `post_handshake_callback` is set, it overrides the
`post_handshake_callback` passed to the constructor.
.. versionchanged:: 0.4
This method is now a barrier with respect to reads and writes:
before the handshake is completed (including the post handshake
callback, if any), no data is received or sent.
"""
if self._state != _State.RAW_OPEN or self._closing:
raise self._invalid_state("starttls() called")
if ssl_context is not None:
self._ssl_context = ssl_context
self._extra.update(
sslcontext=ssl_context
)
else:
self._ssl_context = self._ssl_context_factory(self)
if post_handshake_callback is not None:
self._tls_post_handshake_callback = post_handshake_callback
self._waiter = asyncio.Future()
self._waiter.add_done_callback(self._waiter_done)
self._initiate_tls()
try:
yield from self._waiter
finally:
self._waiter = None | [
"def",
"starttls",
"(",
"self",
",",
"ssl_context",
"=",
"None",
",",
"post_handshake_callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_state",
"!=",
"_State",
".",
"RAW_OPEN",
"or",
"self",
".",
"_closing",
":",
"raise",
"self",
".",
"_invalid_state"... | Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructor. If `post_handshake_callback` is set, it overrides the
`post_handshake_callback` passed to the constructor.
.. versionchanged:: 0.4
This method is now a barrier with respect to reads and writes:
before the handshake is completed (including the post handshake
callback, if any), no data is received or sent. | [
"Start",
"a",
"TLS",
"stream",
"on",
"top",
"of",
"the",
"socket",
".",
"This",
"is",
"an",
"invalid",
"operation",
"if",
"the",
"stream",
"is",
"not",
"in",
"RAW_OPEN",
"state",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L649-L685 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.write | def write(self, data):
"""
Write data to the transport. This is an invalid operation if the stream
is not writable, that is, if it is closed. During TLS negotiation, the
data is buffered.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError('data argument must be byte-ish (%r)',
type(data))
if not self._state.is_writable or self._closing:
raise self._invalid_state("write() called")
if not data:
return
if not self._buffer:
self._loop.add_writer(self._raw_fd, self._write_ready)
self._buffer.extend(data) | python | def write(self, data):
"""
Write data to the transport. This is an invalid operation if the stream
is not writable, that is, if it is closed. During TLS negotiation, the
data is buffered.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError('data argument must be byte-ish (%r)',
type(data))
if not self._state.is_writable or self._closing:
raise self._invalid_state("write() called")
if not data:
return
if not self._buffer:
self._loop.add_writer(self._raw_fd, self._write_ready)
self._buffer.extend(data) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
",",
"memoryview",
")",
")",
":",
"raise",
"TypeError",
"(",
"'data argument must be byte-ish (%r)'",
",",
"type",
"(",
"data",... | Write data to the transport. This is an invalid operation if the stream
is not writable, that is, if it is closed. During TLS negotiation, the
data is buffered. | [
"Write",
"data",
"to",
"the",
"transport",
".",
"This",
"is",
"an",
"invalid",
"operation",
"if",
"the",
"stream",
"is",
"not",
"writable",
"that",
"is",
"if",
"it",
"is",
"closed",
".",
"During",
"TLS",
"negotiation",
"the",
"data",
"is",
"buffered",
".... | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L687-L706 |
BBVA/data-refinery | datarefinery/FieldOperations.py | explode | def explode(prefix: str):
"""
given an array of objects de-normalized into fields
"""
def _app(i, e=None):
if i is not None:
return {k: v for (k, v) in iter_fields(i)}, None
return i, e
def iter_fields(event_field: Union[dict, list]):
if type(event_field) is dict:
for key, val in event_field.items():
yield (key, val)
elif type(event_field) is list:
for i, value in enumerate(event_field):
for key, val in value.items():
if not i == 0:
yield ("{}_{}".format(key, i), val)
else:
yield (key, val)
return compose(_app, add_column_prefix(prefix)) | python | def explode(prefix: str):
"""
given an array of objects de-normalized into fields
"""
def _app(i, e=None):
if i is not None:
return {k: v for (k, v) in iter_fields(i)}, None
return i, e
def iter_fields(event_field: Union[dict, list]):
if type(event_field) is dict:
for key, val in event_field.items():
yield (key, val)
elif type(event_field) is list:
for i, value in enumerate(event_field):
for key, val in value.items():
if not i == 0:
yield ("{}_{}".format(key, i), val)
else:
yield (key, val)
return compose(_app, add_column_prefix(prefix)) | [
"def",
"explode",
"(",
"prefix",
":",
"str",
")",
":",
"def",
"_app",
"(",
"i",
",",
"e",
"=",
"None",
")",
":",
"if",
"i",
"is",
"not",
"None",
":",
"return",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"iter_fields",
"(",
"i... | given an array of objects de-normalized into fields | [
"given",
"an",
"array",
"of",
"objects",
"de",
"-",
"normalized",
"into",
"fields"
] | train | https://github.com/BBVA/data-refinery/blob/4ff19186ac570269f64a245ad6297cf882c70aa4/datarefinery/FieldOperations.py#L186-L207 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter._has_xml_encode | def _has_xml_encode(self, content):
"""Check XML encoding."""
encode = None
m = RE_XML_START.match(content)
if m:
if m.group(1):
m2 = RE_XML_ENCODE.match(m.group(1))
if m2:
enc = m2.group(2).decode('ascii')
try:
codecs.getencoder(enc)
encode = enc
except LookupError:
pass
else:
if m.group(2):
enc = 'utf-32-be'
text = m.group(2)
elif m.group(3):
enc = 'utf-32-le'
text = m.group(3)
elif m.group(4):
enc = 'utf-16-be'
text = m.group(4)
elif m.group(5):
enc = 'utf-16-le'
text = m.group(5)
try:
m2 = RE_XML_ENCODE_U.match(text.decode(enc))
except Exception: # pragma: no cover
m2 = None
if m2:
enc = m2.group(2)
try:
codecs.getencoder(enc)
encode = enc
except Exception:
pass
return encode | python | def _has_xml_encode(self, content):
"""Check XML encoding."""
encode = None
m = RE_XML_START.match(content)
if m:
if m.group(1):
m2 = RE_XML_ENCODE.match(m.group(1))
if m2:
enc = m2.group(2).decode('ascii')
try:
codecs.getencoder(enc)
encode = enc
except LookupError:
pass
else:
if m.group(2):
enc = 'utf-32-be'
text = m.group(2)
elif m.group(3):
enc = 'utf-32-le'
text = m.group(3)
elif m.group(4):
enc = 'utf-16-be'
text = m.group(4)
elif m.group(5):
enc = 'utf-16-le'
text = m.group(5)
try:
m2 = RE_XML_ENCODE_U.match(text.decode(enc))
except Exception: # pragma: no cover
m2 = None
if m2:
enc = m2.group(2)
try:
codecs.getencoder(enc)
encode = enc
except Exception:
pass
return encode | [
"def",
"_has_xml_encode",
"(",
"self",
",",
"content",
")",
":",
"encode",
"=",
"None",
"m",
"=",
"RE_XML_START",
".",
"match",
"(",
"content",
")",
"if",
"m",
":",
"if",
"m",
".",
"group",
"(",
"1",
")",
":",
"m2",
"=",
"RE_XML_ENCODE",
".",
"matc... | Check XML encoding. | [
"Check",
"XML",
"encoding",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L71-L116 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.is_break_tag | def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = el.name
return name in self.break_tags or name in self.user_break_tags | python | def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = el.name
return name in self.break_tags or name in self.user_break_tags | [
"def",
"is_break_tag",
"(",
"self",
",",
"el",
")",
":",
"name",
"=",
"el",
".",
"name",
"return",
"name",
"in",
"self",
".",
"break_tags",
"or",
"name",
"in",
"self",
".",
"user_break_tags"
] | Check if tag is an element we should break on. | [
"Check",
"if",
"tag",
"is",
"an",
"element",
"we",
"should",
"break",
"on",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L123-L127 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.store_blocks | def store_blocks(self, el, blocks, text, force_root):
"""Store the text as desired."""
if force_root or el.parent is None or self.is_break_tag(el):
content = ''.join(text)
if content:
blocks.append((content, self.construct_selector(el)))
text = []
return text | python | def store_blocks(self, el, blocks, text, force_root):
"""Store the text as desired."""
if force_root or el.parent is None or self.is_break_tag(el):
content = ''.join(text)
if content:
blocks.append((content, self.construct_selector(el)))
text = []
return text | [
"def",
"store_blocks",
"(",
"self",
",",
"el",
",",
"blocks",
",",
"text",
",",
"force_root",
")",
":",
"if",
"force_root",
"or",
"el",
".",
"parent",
"is",
"None",
"or",
"self",
".",
"is_break_tag",
"(",
"el",
")",
":",
"content",
"=",
"''",
".",
... | Store the text as desired. | [
"Store",
"the",
"text",
"as",
"desired",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L129-L137 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.construct_selector | def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancestor.name
prefix = ancestor.prefix
sel = ''
if prefix:
sel += prefix + '|'
sel = tag
if attr:
sel += '[%s]' % attr
selector.appendleft(sel)
ancestor = ancestor.parent
return '>'.join(selector) | python | def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancestor.name
prefix = ancestor.prefix
sel = ''
if prefix:
sel += prefix + '|'
sel = tag
if attr:
sel += '[%s]' % attr
selector.appendleft(sel)
ancestor = ancestor.parent
return '>'.join(selector) | [
"def",
"construct_selector",
"(",
"self",
",",
"el",
",",
"attr",
"=",
"''",
")",
":",
"selector",
"=",
"deque",
"(",
")",
"ancestor",
"=",
"el",
"while",
"ancestor",
"and",
"ancestor",
".",
"parent",
":",
"if",
"ancestor",
"is",
"not",
"el",
":",
"s... | Construct an selector for context. | [
"Construct",
"an",
"selector",
"for",
"context",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L139-L159 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.to_text | def to_text(self, tree, force_root=False):
"""
Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either.
"""
self.extract_tag_metadata(tree)
text = []
attributes = []
comments = []
blocks = []
if not (self.ignores.match(tree) if self.ignores else None):
# The root of the document is the BeautifulSoup object
capture = self.captures.match(tree) if self.captures is not None else None
# Check attributes for normal tags
if capture:
for attr in self.attributes:
value = tree.attrs.get(attr, '').strip()
if value:
sel = self.construct_selector(tree, attr=attr)
attributes.append((value, sel))
# Walk children
for child in tree.children:
string = str(child).strip()
is_comment = isinstance(child, bs4.Comment)
if isinstance(child, bs4.element.Tag):
t, b, a, c = self.to_text(child)
text.extend(t)
attributes.extend(a)
comments.extend(c)
blocks.extend(b)
# Get content if not the root and not a comment (unless we want comments).
elif not isinstance(child, NON_CONTENT) and (not is_comment or self.comments):
string = str(child).strip()
if string:
if is_comment:
sel = self.construct_selector(tree) + '<!--comment-->'
comments.append((string, sel))
elif capture:
text.append(string)
text.append(' ')
elif self.comments:
for child in tree.descendants:
if isinstance(child, bs4.Comment):
string = str(child).strip()
if string:
sel = self.construct_selector(tree) + '<!--comment-->'
comments.append((string, sel))
text = self.store_blocks(tree, blocks, text, force_root)
if tree.parent is None or force_root:
return blocks, attributes, comments
else:
return text, blocks, attributes, comments | python | def to_text(self, tree, force_root=False):
"""
Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either.
"""
self.extract_tag_metadata(tree)
text = []
attributes = []
comments = []
blocks = []
if not (self.ignores.match(tree) if self.ignores else None):
# The root of the document is the BeautifulSoup object
capture = self.captures.match(tree) if self.captures is not None else None
# Check attributes for normal tags
if capture:
for attr in self.attributes:
value = tree.attrs.get(attr, '').strip()
if value:
sel = self.construct_selector(tree, attr=attr)
attributes.append((value, sel))
# Walk children
for child in tree.children:
string = str(child).strip()
is_comment = isinstance(child, bs4.Comment)
if isinstance(child, bs4.element.Tag):
t, b, a, c = self.to_text(child)
text.extend(t)
attributes.extend(a)
comments.extend(c)
blocks.extend(b)
# Get content if not the root and not a comment (unless we want comments).
elif not isinstance(child, NON_CONTENT) and (not is_comment or self.comments):
string = str(child).strip()
if string:
if is_comment:
sel = self.construct_selector(tree) + '<!--comment-->'
comments.append((string, sel))
elif capture:
text.append(string)
text.append(' ')
elif self.comments:
for child in tree.descendants:
if isinstance(child, bs4.Comment):
string = str(child).strip()
if string:
sel = self.construct_selector(tree) + '<!--comment-->'
comments.append((string, sel))
text = self.store_blocks(tree, blocks, text, force_root)
if tree.parent is None or force_root:
return blocks, attributes, comments
else:
return text, blocks, attributes, comments | [
"def",
"to_text",
"(",
"self",
",",
"tree",
",",
"force_root",
"=",
"False",
")",
":",
"self",
".",
"extract_tag_metadata",
"(",
"tree",
")",
"text",
"=",
"[",
"]",
"attributes",
"=",
"[",
"]",
"comments",
"=",
"[",
"]",
"blocks",
"=",
"[",
"]",
"i... | Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either. | [
"Extract",
"text",
"from",
"tags",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L167-L226 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter._filter | def _filter(self, text, context, encoding):
"""Filter the source text."""
content = []
blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser))
if self.comments:
for c, desc in comments:
content.append(filters.SourceText(c, context + ': ' + desc, encoding, self.type + 'comment'))
if self.attributes:
for a, desc in attributes:
content.append(filters.SourceText(a, context + ': ' + desc, encoding, self.type + 'attribute'))
for b, desc in blocks:
content.append(filters.SourceText(b, context + ': ' + desc, encoding, self.type + 'content'))
return content | python | def _filter(self, text, context, encoding):
"""Filter the source text."""
content = []
blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser))
if self.comments:
for c, desc in comments:
content.append(filters.SourceText(c, context + ': ' + desc, encoding, self.type + 'comment'))
if self.attributes:
for a, desc in attributes:
content.append(filters.SourceText(a, context + ': ' + desc, encoding, self.type + 'attribute'))
for b, desc in blocks:
content.append(filters.SourceText(b, context + ': ' + desc, encoding, self.type + 'content'))
return content | [
"def",
"_filter",
"(",
"self",
",",
"text",
",",
"context",
",",
"encoding",
")",
":",
"content",
"=",
"[",
"]",
"blocks",
",",
"attributes",
",",
"comments",
"=",
"self",
".",
"to_text",
"(",
"bs4",
".",
"BeautifulSoup",
"(",
"text",
",",
"self",
".... | Filter the source text. | [
"Filter",
"the",
"source",
"text",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L228-L241 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.sfilter | def sfilter(self, source):
"""Filter."""
return self._filter(source.text, source.context, source.encoding) | python | def sfilter(self, source):
"""Filter."""
return self._filter(source.text, source.context, source.encoding) | [
"def",
"sfilter",
"(",
"self",
",",
"source",
")",
":",
"return",
"self",
".",
"_filter",
"(",
"source",
".",
"text",
",",
"source",
".",
"context",
",",
"source",
".",
"encoding",
")"
] | Filter. | [
"Filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L250-L253 |
JMSwag/dsdev-utils | dsdev_utils/helpers.py | lazy_import | def lazy_import(func):
"""Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports like this:
@lazy_import
def socket():
import socket
return socket
The name "socket" will then be bound to a transparent object proxy which
will import the socket module upon first use.
The syntax here is slightly more verbose than other lazy import recipes,
but it's designed not to hide the actual "import" statements from tools
like pyinstaller or grep.
"""
try:
f = sys._getframe(1)
except Exception: # pragma: no cover
namespace = None
else:
namespace = f.f_locals
return _LazyImport(func.__name__, func, namespace) | python | def lazy_import(func):
"""Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports like this:
@lazy_import
def socket():
import socket
return socket
The name "socket" will then be bound to a transparent object proxy which
will import the socket module upon first use.
The syntax here is slightly more verbose than other lazy import recipes,
but it's designed not to hide the actual "import" statements from tools
like pyinstaller or grep.
"""
try:
f = sys._getframe(1)
except Exception: # pragma: no cover
namespace = None
else:
namespace = f.f_locals
return _LazyImport(func.__name__, func, namespace) | [
"def",
"lazy_import",
"(",
"func",
")",
":",
"try",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
"except",
"Exception",
":",
"# pragma: no cover",
"namespace",
"=",
"None",
"else",
":",
"namespace",
"=",
"f",
".",
"f_locals",
"return",
"_LazyIm... | Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports like this:
@lazy_import
def socket():
import socket
return socket
The name "socket" will then be bound to a transparent object proxy which
will import the socket module upon first use.
The syntax here is slightly more verbose than other lazy import recipes,
but it's designed not to hide the actual "import" statements from tools
like pyinstaller or grep. | [
"Decorator",
"for",
"declaring",
"a",
"lazy",
"import",
"."
] | train | https://github.com/JMSwag/dsdev-utils/blob/5adbf9b3fd9fff92d1dd714423b08e26a5038e14/dsdev_utils/helpers.py#L64-L90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.