sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _get_binary_from_ipv4(self, ip_addr):
"""Converts IPv4 address to binary form."""
return struct.unpack("!L", socket.inet_pton(socket.AF_INET,
ip_addr))[0] | Converts IPv4 address to binary form. | entailment |
def _get_binary_from_ipv6(self, ip_addr):
"""Converts IPv6 address to binary form."""
hi, lo = struct.unpack("!QQ", socket.inet_pton(socket.AF_INET6,
ip_addr))
return (hi << 64) | lo | Converts IPv6 address to binary form. | entailment |
def _get_ipv4_from_binary(self, bin_addr):
"""Converts binary address to Ipv4 format."""
return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr)) | Converts binary address to Ipv4 format. | entailment |
def _get_ipv6_from_binary(self, bin_addr):
"""Converts binary address to Ipv6 format."""
hi = bin_addr >> 64
lo = bin_addr & 0xFFFFFFFF
return socket.inet_ntop(socket.AF_INET6, struct.pack("!QQ", hi, lo)) | Converts binary address to Ipv6 format. | entailment |
def _get_router_ip(self, cidr, ip_count, ip_ver):
"""For a given IP subnet and IP version type, generate IP for router.
This method takes the network address (cidr) and selects an
IP address that should be assigned to virtual router running
on multiple switches. It uses upper addresses ... | For a given IP subnet and IP version type, generate IP for router.
This method takes the network address (cidr) and selects an
IP address that should be assigned to virtual router running
on multiple switches. It uses upper addresses in a subnet address
as IP for the router. Each instac... | entailment |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL or an Engine.
Calls to context.execute() here emit the given string to the
script output.
"""
set_mysql_engine()
kwargs = dict()
if neutron_config.database.connection:
... | Run migrations in 'offline' mode.
This configures the context with just a URL or an Engine.
Calls to context.execute() here emit the given string to the
script output. | entailment |
def create_tenant(self, tenant_id):
"""Enqueue tenant create"""
t_res = MechResource(tenant_id, a_const.TENANT_RESOURCE,
a_const.CREATE)
self.provision_queue.put(t_res) | Enqueue tenant create | entailment |
def delete_tenant_if_removed(self, tenant_id):
"""Enqueue tenant delete if it's no longer in the db"""
if not db_lib.tenant_provisioned(tenant_id):
t_res = MechResource(tenant_id, a_const.TENANT_RESOURCE,
a_const.DELETE)
self.provision_queue.put(t... | Enqueue tenant delete if it's no longer in the db | entailment |
def create_network(self, network):
"""Enqueue network create"""
n_res = MechResource(network['id'], a_const.NETWORK_RESOURCE,
a_const.CREATE)
self.provision_queue.put(n_res) | Enqueue network create | entailment |
def delete_network(self, network):
"""Enqueue network delete"""
n_res = MechResource(network['id'], a_const.NETWORK_RESOURCE,
a_const.DELETE)
self.provision_queue.put(n_res) | Enqueue network delete | entailment |
def create_segments(self, segments):
"""Enqueue segment creates"""
for segment in segments:
s_res = MechResource(segment['id'], a_const.SEGMENT_RESOURCE,
a_const.CREATE)
self.provision_queue.put(s_res) | Enqueue segment creates | entailment |
def delete_segments(self, segments):
"""Enqueue segment deletes"""
for segment in segments:
s_res = MechResource(segment['id'], a_const.SEGMENT_RESOURCE,
a_const.DELETE)
self.provision_queue.put(s_res) | Enqueue segment deletes | entailment |
def get_instance_type(self, port):
"""Determine the port type based on device owner and vnic type"""
if port[portbindings.VNIC_TYPE] == portbindings.VNIC_BAREMETAL:
return a_const.BAREMETAL_RESOURCE
owner_to_type = {
n_const.DEVICE_OWNER_DHCP: a_const.DHCP_RESOURCE,
... | Determine the port type based on device owner and vnic type | entailment |
def create_instance(self, port):
"""Enqueue instance create"""
instance_type = self.get_instance_type(port)
if not instance_type:
return
i_res = MechResource(port['device_id'], instance_type, a_const.CREATE)
self.provision_queue.put(i_res) | Enqueue instance create | entailment |
def delete_instance_if_removed(self, port):
"""Enqueue instance delete if it's no longer in the db"""
instance_type = self.get_instance_type(port)
if not instance_type:
return
if not db_lib.instance_provisioned(port['device_id']):
i_res = MechResource(port['device... | Enqueue instance delete if it's no longer in the db | entailment |
def create_port(self, port):
"""Enqueue port create"""
instance_type = self.get_instance_type(port)
if not instance_type:
return
port_type = instance_type + a_const.PORT_SUFFIX
p_res = MechResource(port['id'], port_type, a_const.CREATE)
self.provision_queue.pu... | Enqueue port create | entailment |
def delete_port_if_removed(self, port):
"""Enqueue port delete"""
instance_type = self.get_instance_type(port)
if not instance_type:
return
port_type = instance_type + a_const.PORT_SUFFIX
if not db_lib.port_provisioned(port['id']):
p_res = MechResource(por... | Enqueue port delete | entailment |
def _get_binding_keys(self, port, host):
"""Get binding keys from the port binding"""
binding_keys = list()
switch_binding = port[portbindings.PROFILE].get(
'local_link_information', None)
if switch_binding:
for binding in switch_binding:
switch_id... | Get binding keys from the port binding | entailment |
def create_port_binding(self, port, host):
"""Enqueue port binding create"""
if not self.get_instance_type(port):
return
for pb_key in self._get_binding_keys(port, host):
pb_res = MechResource(pb_key, a_const.PORT_BINDING_RESOURCE,
a_cons... | Enqueue port binding create | entailment |
def delete_port_binding(self, port, host):
"""Enqueue port binding delete"""
if not self.get_instance_type(port):
return
for pb_key in self._get_binding_keys(port, host):
pb_res = MechResource(pb_key, a_const.PORT_BINDING_RESOURCE,
a_cons... | Enqueue port binding delete | entailment |
def create_network_postcommit(self, context):
"""Provision the network on CVX"""
network = context.current
log_context("create_network_postcommit: network", network)
segments = context.network_segments
tenant_id = network['project_id']
self.create_tenant(tenant_id)
... | Provision the network on CVX | entailment |
def update_network_postcommit(self, context):
"""Send network updates to CVX:
- Update the network name
- Add new segments
- Delete stale segments
"""
network = context.current
orig_network = context.original
log_context("update_network_postcommit: netwo... | Send network updates to CVX:
- Update the network name
- Add new segments
- Delete stale segments | entailment |
def delete_network_postcommit(self, context):
"""Delete the network from CVX"""
network = context.current
log_context("delete_network_postcommit: network", network)
segments = context.network_segments
tenant_id = network['project_id']
self.delete_segments(segments)
... | Delete the network from CVX | entailment |
def update_port_postcommit(self, context):
"""Send port updates to CVX
This method is also responsible for the initial creation of ports
as we wait until after a port is bound to send the port data to CVX
"""
port = context.current
orig_port = context.original
ne... | Send port updates to CVX
This method is also responsible for the initial creation of ports
as we wait until after a port is bound to send the port data to CVX | entailment |
def delete_port_postcommit(self, context):
"""Delete the port from CVX"""
port = context.current
log_context("delete_port_postcommit: port", port)
self._delete_port_resources(port, context.host)
self._try_to_release_dynamic_segment(context) | Delete the port from CVX | entailment |
def _bind_baremetal_port(self, context, segment):
"""Bind the baremetal port to the segment"""
port = context.current
vif_details = {
portbindings.VIF_DETAILS_VLAN: str(
segment[driver_api.SEGMENTATION_ID])
}
context.set_binding(segment[driver_api.ID],... | Bind the baremetal port to the segment | entailment |
def _get_physnet(self, context):
"""Find the appropriate physnet for the host
- Baremetal ports' physnet is determined by looking at the
local_link_information contained in the binding profile
- Other ports' physnet is determined by looking for the host in the
topology
... | Find the appropriate physnet for the host
- Baremetal ports' physnet is determined by looking at the
local_link_information contained in the binding profile
- Other ports' physnet is determined by looking for the host in the
topology | entailment |
def _bind_fabric(self, context, segment):
"""Allocate dynamic segments for the port
Segment physnets are based on the switch to which the host is
connected.
"""
port_id = context.current['id']
physnet = self._get_physnet(context)
if not physnet:
LOG.d... | Allocate dynamic segments for the port
Segment physnets are based on the switch to which the host is
connected. | entailment |
def bind_port(self, context):
"""Bind port to a network segment.
Provisioning request to Arista Hardware to plug a host
into appropriate network is done when the port is created
this simply tells the ML2 Plugin that we are binding the port
"""
port = context.current
... | Bind port to a network segment.
Provisioning request to Arista Hardware to plug a host
into appropriate network is done when the port is created
this simply tells the ML2 Plugin that we are binding the port | entailment |
def _try_to_release_dynamic_segment(self, context, migration=False):
"""Release dynamic segment if necessary
If this port was the last port using a segment and the segment was
allocated by this driver, it should be released
"""
if migration:
binding_levels = context.... | Release dynamic segment if necessary
If this port was the last port using a segment and the segment was
allocated by this driver, it should be released | entailment |
def bdom_roll_date(sd, ed, bdom, months, holidays=[]):
"""
Convenience function for getting business day data associated with
contracts. Usefully for generating business day derived 'contract_dates'
which can be used as input to roller(). Returns dates for a business day of
the month for months in m... | Convenience function for getting business day data associated with
contracts. Usefully for generating business day derived 'contract_dates'
which can be used as input to roller(). Returns dates for a business day of
the month for months in months.keys() between the start date and end date.
Parameters
... | entailment |
def roller(timestamps, contract_dates, get_weights, **kwargs):
"""
Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timestamps to calculate wei... | Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timestamps to calculate weights for
contract_dates: pandas.Series
Series with index of tra... | entailment |
def aggregate_weights(weights, drop_date=False):
"""
Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contra... | Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contract as a
float and the date as a pandas.Timestamp.
... | entailment |
def static_transition(timestamp, contract_dates, transition, holidays=None,
validate_inputs=True):
"""
An implementation of *get_weights* parameter in roller().
Return weights to tradeable instruments for a given date based on a
transition DataFrame which indicates how to roll thro... | An implementation of *get_weights* parameter in roller().
Return weights to tradeable instruments for a given date based on a
transition DataFrame which indicates how to roll through the roll period.
Parameters
----------
timestamp: pandas.Timestamp
The timestamp to return instrument weight... | entailment |
def to_generics(instruments, weights):
"""
Map tradeable instruments to generics given weights and tradeable
instrument holdings. This is solving the equation Ax = b where A is the
weights, and b is the instrument holdings. When Ax = b has no solution we
solve for x' such that Ax' is closest to b in... | Map tradeable instruments to generics given weights and tradeable
instrument holdings. This is solving the equation Ax = b where A is the
weights, and b is the instrument holdings. When Ax = b has no solution we
solve for x' such that Ax' is closest to b in the least squares sense with
the additional co... | entailment |
def synchronize_switch(self, switch_ip, expected_acls, expected_bindings):
"""Update ACL config on a switch to match expected config
This is done as follows:
1. Get switch ACL config using show commands
2. Update expected bindings based on switch LAGs
3. Get commands to synchron... | Update ACL config on a switch to match expected config
This is done as follows:
1. Get switch ACL config using show commands
2. Update expected bindings based on switch LAGs
3. Get commands to synchronize switch ACLs
4. Get commands to synchronize switch ACL bindings
5. ... | entailment |
def synchronize(self):
"""Perform sync of the security groups between ML2 and EOS."""
# Get expected ACLs and rules
expected_acls = self.get_expected_acls()
# Get expected interface to ACL mappings
all_expected_bindings = self.get_expected_bindings()
# Check that confi... | Perform sync of the security groups between ML2 and EOS. | entailment |
def check_vlan_type_driver_commands(self):
"""Checks the validity of CLI commands for Arista's VLAN type driver.
This method tries to execute the commands used exclusively by the
arista_vlan type driver and stores the commands if they succeed.
"""
cmd = ['show openstack re... | Checks the validity of CLI commands for Arista's VLAN type driver.
This method tries to execute the commands used exclusively by the
arista_vlan type driver and stores the commands if they succeed. | entailment |
def get_vlan_assignment_uuid(self):
"""Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID
"""
vlan_uuid_cmd = self.cli_commands['resource-pool']
if vlan_uuid_cmd:
return self._run_eos_cmds(commands=v... | Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID | entailment |
def get_vlan_allocation(self):
"""Returns the status of the region's VLAN pool in CVX
:returns: dictionary containg the assigned, allocated and available
VLANs for the region
"""
if not self.cli_commands['resource-pool']:
LOG.warning(_('The version of CVX y... | Returns the status of the region's VLAN pool in CVX
:returns: dictionary containg the assigned, allocated and available
VLANs for the region | entailment |
def _run_eos_cmds(self, commands, commands_to_log=None):
"""Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be executed on EOS.
... | Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be executed on EOS.
:param commands_to_log : This should be set to the command that i... | entailment |
def _build_command(self, cmds, sync=False):
"""Build full EOS's openstack CLI command.
Helper method to add commands to enter and exit from openstack
CLI modes.
:param cmds: The openstack CLI commands that need to be executed
in the openstack config mode.
:... | Build full EOS's openstack CLI command.
Helper method to add commands to enter and exit from openstack
CLI modes.
:param cmds: The openstack CLI commands that need to be executed
in the openstack config mode.
:param sync: This flags indicates that the region is bei... | entailment |
def _run_openstack_cmds(self, commands, commands_to_log=None, sync=False):
"""Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be exec... | Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be executed on EOS.
:param commands_to_logs : This should be set to the command that ... | entailment |
def get_baremetal_physnet(self, context):
"""Returns dictionary which contains mac to hostname mapping"""
port = context.current
host_id = context.host
cmd = ['show network physical-topology hosts']
try:
response = self._run_eos_cmds(cmd)
binding_profile =... | Returns dictionary which contains mac to hostname mapping | entailment |
def get_host_physnet(self, context):
"""Returns dictionary which contains physical topology information
for a given host_id
"""
host_id = utils.hostname(context.host)
cmd = ['show network physical-topology neighbors']
try:
response = self._run_eos_cmds(cmd)
... | Returns dictionary which contains physical topology information
for a given host_id | entailment |
def filter_unnecessary_segments(query):
"""Filter segments are not needed on CVX"""
segment_model = segment_models.NetworkSegment
network_model = models_v2.Network
query = (query
.join_if_necessary(network_model)
.join_if_necessary(segment_model)
.filter(network_mo... | Filter segments are not needed on CVX | entailment |
def filter_network_type(query):
"""Filter unsupported segment types"""
segment_model = segment_models.NetworkSegment
query = (query
.filter(
segment_model.network_type.in_(
utils.SUPPORTED_NETWORK_TYPES)))
return query | Filter unsupported segment types | entailment |
def filter_unbound_ports(query):
"""Filter ports not bound to a host or network"""
# hack for pep8 E711: comparison to None should be
# 'if cond is not None'
none = None
port_model = models_v2.Port
binding_level_model = ml2_models.PortBindingLevel
query = (query
.join_if_necessa... | Filter ports not bound to a host or network | entailment |
def filter_by_device_owner(query, device_owners=None):
"""Filter ports by device_owner
Either filter using specified device_owner or using the list of all
device_owners supported and unsupported by the arista ML2 plugin
"""
port_model = models_v2.Port
if not device_owners:
device_owners... | Filter ports by device_owner
Either filter using specified device_owner or using the list of all
device_owners supported and unsupported by the arista ML2 plugin | entailment |
def filter_by_device_id(query):
"""Filter ports attached to devices we don't care about
Currently used to filter DHCP_RESERVED ports
"""
port_model = models_v2.Port
unsupported_device_id_filter = [
port_model.device_id.notilike('%s%%' % id)
for id in utils.UNSUPPORTED_DEVICE_IDS]
... | Filter ports attached to devices we don't care about
Currently used to filter DHCP_RESERVED ports | entailment |
def filter_by_vnic_type(query, vnic_type):
"""Filter ports by vnic_type (currently only used for baremetals)"""
port_model = models_v2.Port
binding_model = ml2_models.PortBinding
dst_binding_model = ml2_models.DistributedPortBinding
query = (query
.outerjoin_if_necessary(
... | Filter ports by vnic_type (currently only used for baremetals) | entailment |
def filter_unmanaged_physnets(query):
"""Filter ports managed by other ML2 plugins """
config = cfg.CONF.ml2_arista
managed_physnets = config['managed_physnets']
# Filter out ports bound to segments on physnets that we're not
# managing
segment_model = segment_models.NetworkSegment
if manag... | Filter ports managed by other ML2 plugins | entailment |
def filter_inactive_ports(query):
"""Filter ports that aren't in active status """
port_model = models_v2.Port
query = (query
.filter(port_model.status == n_const.PORT_STATUS_ACTIVE))
return query | Filter ports that aren't in active status | entailment |
def filter_unnecessary_ports(query, device_owners=None, vnic_type=None,
active=True):
"""Filter out all ports are not needed on CVX """
query = (query
.filter_unbound_ports()
.filter_by_device_owner(device_owners)
.filter_by_device_id()
... | Filter out all ports are not needed on CVX | entailment |
def get_tenants(tenant_id=None):
"""Returns list of all project/tenant ids that may be relevant on CVX"""
if tenant_id == '':
return []
session = db.get_reader_session()
project_ids = set()
with session.begin():
for m in [models_v2.Network, models_v2.Port]:
q = session.qu... | Returns list of all project/tenant ids that may be relevant on CVX | entailment |
def get_networks(network_id=None):
"""Returns list of all networks that may be relevant on CVX"""
session = db.get_reader_session()
with session.begin():
model = models_v2.Network
networks = session.query(model).filter(model.project_id != '')
if network_id:
networks = net... | Returns list of all networks that may be relevant on CVX | entailment |
def get_segments(segment_id=None):
"""Returns list of all network segments that may be relevant on CVX"""
session = db.get_reader_session()
with session.begin():
model = segment_models.NetworkSegment
segments = session.query(model).filter_unnecessary_segments()
if segment_id:
... | Returns list of all network segments that may be relevant on CVX | entailment |
def get_instances(device_owners=None, vnic_type=None, instance_id=None):
"""Returns filtered list of all instances in the neutron db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
binding_model = ml2_models.PortBinding
instances = (session
... | Returns filtered list of all instances in the neutron db | entailment |
def get_vm_instances(instance_id=None):
"""Returns filtered list of vms that may be relevant on CVX"""
return get_instances(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX],
vnic_type=portbindings.VNIC_NORMAL,
instance_id=instance_id) | Returns filtered list of vms that may be relevant on CVX | entailment |
def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True):
"""Returns list of all ports in neutron the db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
ports = (session
.query(port_model)
.filter_un... | Returns list of all ports in neutron the db | entailment |
def get_vm_ports(port_id=None):
"""Returns filtered list of vms that may be relevant on CVX"""
return get_ports(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX,
t_const.TRUNK_SUBPORT_OWNER],
vnic_type=portbindings.VNIC_NORMAL, port_id=port_id) | Returns filtered list of vms that may be relevant on CVX | entailment |
def get_port_bindings(binding_key=None):
"""Returns filtered list of port bindings that may be relevant on CVX
This query is a little complex as we need all binding levels for any
binding that has a single managed physnet, but we need to filter bindings
that have no managed physnets. In order to achiev... | Returns filtered list of port bindings that may be relevant on CVX
This query is a little complex as we need all binding levels for any
binding that has a single managed physnet, but we need to filter bindings
that have no managed physnets. In order to achieve this, we join to the
binding_level_model o... | entailment |
def tenant_provisioned(tenant_id):
"""Returns true if any networks or ports exist for a tenant."""
session = db.get_reader_session()
with session.begin():
res = any(
session.query(m).filter(m.tenant_id == tenant_id).count()
for m in [models_v2.Network, models_v2.Port]
... | Returns true if any networks or ports exist for a tenant. | entailment |
def instance_provisioned(device_id):
"""Returns true if any ports exist for an instance."""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
res = bool(session.query(port_model)
.filter(port_model.device_id == device_id).count())
retu... | Returns true if any ports exist for an instance. | entailment |
def port_provisioned(port_id):
"""Returns true if port still exists."""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
res = bool(session.query(port_model)
.filter(port_model.id == port_id).count())
return res | Returns true if port still exists. | entailment |
def get_parent(port_id):
"""Get trunk subport's parent port"""
session = db.get_reader_session()
res = dict()
with session.begin():
subport_model = trunk_models.SubPort
trunk_model = trunk_models.Trunk
subport = (session.query(subport_model).
filter(subport_mod... | Get trunk subport's parent port | entailment |
def get_port_binding_level(filters):
"""Returns entries from PortBindingLevel based on the specified filters."""
session = db.get_reader_session()
with session.begin():
return (session.query(ml2_models.PortBindingLevel).
filter_by(**filters).
order_by(ml2_models.PortB... | Returns entries from PortBindingLevel based on the specified filters. | entailment |
def read(file, frames=-1, start=0, stop=None, dtype='float64', always_2d=False,
fill_value=None, out=None, samplerate=None, channels=None,
format=None, subtype=None, endian=None, closefd=True):
"""Provide audio data from a sound file as NumPy array.
By default, the whole file is read from the... | Provide audio data from a sound file as NumPy array.
By default, the whole file is read from the beginning, but the
position to start reading can be specified with `start` and the
number of frames to read can be specified with `frames`.
Alternatively, a range can be specified with `start` and `stop`.
... | entailment |
def write(file, data, samplerate, subtype=None, endian=None, format=None,
closefd=True):
"""Write data to a sound file.
.. note:: If `file` exists, it will be truncated and overwritten!
Parameters
----------
file : str or int or file-like object
The file to write to. See :class:... | Write data to a sound file.
.. note:: If `file` exists, it will be truncated and overwritten!
Parameters
----------
file : str or int or file-like object
The file to write to. See :class:`SoundFile` for details.
data : array_like
The data to write. Usually two-dimensional (frames... | entailment |
def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None,
dtype='float64', always_2d=False, fill_value=None, out=None,
samplerate=None, channels=None,
format=None, subtype=None, endian=None, closefd=True):
"""Return a generator for block-wise reading.
By defaul... | Return a generator for block-wise reading.
By default, iteration starts at the beginning and stops at the end
of the file. Use `start` to start at a later position and `frames`
or `stop` to stop earlier.
If you stop iterating over the generator before it's exhausted,
the sound file is not closed.... | entailment |
def available_subtypes(format=None):
"""Return a dictionary of available subtypes.
Parameters
----------
format : str
If given, only compatible subtypes are returned.
Examples
--------
>>> import soundfile as sf
>>> sf.available_subtypes('FLAC')
{'PCM_24': 'Signed 24 bit PC... | Return a dictionary of available subtypes.
Parameters
----------
format : str
If given, only compatible subtypes are returned.
Examples
--------
>>> import soundfile as sf
>>> sf.available_subtypes('FLAC')
{'PCM_24': 'Signed 24 bit PCM',
'PCM_16': 'Signed 16 bit PCM',
... | entailment |
def check_format(format, subtype=None, endian=None):
"""Check if the combination of format/subtype/endian is valid.
Examples
--------
>>> import soundfile as sf
>>> sf.check_format('WAV', 'PCM_24')
True
>>> sf.check_format('FLAC', 'VORBIS')
False
"""
try:
return bool(_f... | Check if the combination of format/subtype/endian is valid.
Examples
--------
>>> import soundfile as sf
>>> sf.check_format('WAV', 'PCM_24')
True
>>> sf.check_format('FLAC', 'VORBIS')
False | entailment |
def _error_check(err, prefix=""):
"""Pretty-print a numerical error code if there is an error."""
if err != 0:
err_str = _snd.sf_error_number(err)
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace')) | Pretty-print a numerical error code if there is an error. | entailment |
def _format_int(format, subtype, endian):
"""Return numeric ID for given format|subtype|endian combo."""
result = _check_format(format)
if subtype is None:
subtype = default_subtype(format)
if subtype is None:
raise TypeError(
"No default subtype for major format ... | Return numeric ID for given format|subtype|endian combo. | entailment |
def _check_mode(mode):
"""Check if mode is valid and return its integer representation."""
if not isinstance(mode, (_unicode, str)):
raise TypeError("Invalid mode: {0!r}".format(mode))
mode_set = set(mode)
if mode_set.difference('xrwb+') or len(mode) > len(mode_set):
raise ValueError("In... | Check if mode is valid and return its integer representation. | entailment |
def _create_info_struct(file, mode, samplerate, channels,
format, subtype, endian):
"""Check arguments and create SF_INFO struct."""
original_format = format
if format is None:
format = _get_format_from_filename(file, mode)
assert isinstance(format, (_unicode, str))
... | Check arguments and create SF_INFO struct. | entailment |
def _get_format_from_filename(file, mode):
"""Return a format string obtained from file (or file.name).
If file already exists (= read mode), an empty string is returned on
error. If not, an exception is raised.
The return type will always be str or unicode (even if
file/file.name is a bytes objec... | Return a format string obtained from file (or file.name).
If file already exists (= read mode), an empty string is returned on
error. If not, an exception is raised.
The return type will always be str or unicode (even if
file/file.name is a bytes object). | entailment |
def _format_str(format_int):
"""Return the string representation of a given numeric format."""
for dictionary in _formats, _subtypes, _endians:
for k, v in dictionary.items():
if v == format_int:
return k
else:
return 'n/a' | Return the string representation of a given numeric format. | entailment |
def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO):
"""Return the ID and short description of a given format."""
format_info = _ffi.new("SF_FORMAT_INFO*")
format_info.format = format_int
_snd.sf_command(_ffi.NULL, format_flag, format_info,
_ffi.sizeof("SF_FORMAT_INFO"... | Return the ID and short description of a given format. | entailment |
def _available_formats_helper(count_flag, format_flag):
"""Helper for available_formats() and available_subtypes()."""
count = _ffi.new("int*")
_snd.sf_command(_ffi.NULL, count_flag, count, _ffi.sizeof("int"))
for format_int in range(count[0]):
yield _format_info(format_int, format_flag) | Helper for available_formats() and available_subtypes(). | entailment |
def _check_format(format_str):
"""Check if `format_str` is valid and return format ID."""
if not isinstance(format_str, (_unicode, str)):
raise TypeError("Invalid format: {0!r}".format(format_str))
try:
format_int = _formats[format_str.upper()]
except KeyError:
raise ValueError("... | Check if `format_str` is valid and return format ID. | entailment |
def _has_virtual_io_attrs(file, mode_int):
"""Check if file has all the necessary attributes for virtual IO."""
readonly = mode_int == _snd.SFM_READ
writeonly = mode_int == _snd.SFM_WRITE
return all([
hasattr(file, 'seek'),
hasattr(file, 'tell'),
hasattr(file, 'write') or readonl... | Check if file has all the necessary attributes for virtual IO. | entailment |
def extra_info(self):
"""Retrieve the log string generated when opening the file."""
info = _ffi.new("char[]", 2**14)
_snd.sf_command(self._file, _snd.SFC_GET_LOG_INFO,
info, _ffi.sizeof(info))
return _ffi.string(info).decode('utf-8', 'replace') | Retrieve the log string generated when opening the file. | entailment |
def seek(self, frames, whence=SEEK_SET):
"""Set the read/write position.
Parameters
----------
frames : int
The frame index or offset to seek.
whence : {SEEK_SET, SEEK_CUR, SEEK_END}, optional
By default (``whence=SEEK_SET``), `frames` are counted from
... | Set the read/write position.
Parameters
----------
frames : int
The frame index or offset to seek.
whence : {SEEK_SET, SEEK_CUR, SEEK_END}, optional
By default (``whence=SEEK_SET``), `frames` are counted from
the beginning of the file.
``w... | entailment |
def read(self, frames=-1, dtype='float64', always_2d=False,
fill_value=None, out=None):
"""Read from the file and return data as NumPy array.
Reads the given number of frames in the given data format
starting at the current read/write position. This advances the
read/write... | Read from the file and return data as NumPy array.
Reads the given number of frames in the given data format
starting at the current read/write position. This advances the
read/write position by the same number of frames.
By default, all frames from the current read/write position to
... | entailment |
def buffer_read(self, frames=-1, dtype=None):
"""Read from the file and return data as buffer object.
Reads the given number of `frames` in the given data format
starting at the current read/write position. This advances the
read/write position by the same number of frames.
By ... | Read from the file and return data as buffer object.
Reads the given number of `frames` in the given data format
starting at the current read/write position. This advances the
read/write position by the same number of frames.
By default, all frames from the current read/write position ... | entailment |
def buffer_read_into(self, buffer, dtype):
"""Read from the file into a given buffer object.
Fills the given `buffer` with frames in the given data format
starting at the current read/write position (which can be
changed with :meth:`.seek`) until the buffer is full or the end
of... | Read from the file into a given buffer object.
Fills the given `buffer` with frames in the given data format
starting at the current read/write position (which can be
changed with :meth:`.seek`) until the buffer is full or the end
of the file is reached. This advances the read/write po... | entailment |
def write(self, data):
"""Write audio data from a NumPy array to the file.
Writes a number of frames at the read/write position to the
file. This also advances the read/write position by the same
number of frames and enlarges the file if necessary.
Note that writing int values ... | Write audio data from a NumPy array to the file.
Writes a number of frames at the read/write position to the
file. This also advances the read/write position by the same
number of frames and enlarges the file if necessary.
Note that writing int values to a float file will *not* scale
... | entailment |
def buffer_write(self, data, dtype):
"""Write audio data from a buffer/bytes object to the file.
Writes the contents of `data` to the file at the current
read/write position.
This also advances the read/write position by the number of
frames that were written and enlarges the fi... | Write audio data from a buffer/bytes object to the file.
Writes the contents of `data` to the file at the current
read/write position.
This also advances the read/write position by the number of
frames that were written and enlarges the file if necessary.
Parameters
---... | entailment |
def blocks(self, blocksize=None, overlap=0, frames=-1, dtype='float64',
always_2d=False, fill_value=None, out=None):
"""Return a generator for block-wise reading.
By default, the generator yields blocks of the given
`blocksize` (using a given `overlap`) until the end of the file
... | Return a generator for block-wise reading.
By default, the generator yields blocks of the given
`blocksize` (using a given `overlap`) until the end of the file
is reached; `frames` can be used to stop earlier.
Parameters
----------
blocksize : int
The number... | entailment |
def truncate(self, frames=None):
"""Truncate the file to a given number of frames.
After this command, the read/write position will be at the new
end of the file.
Parameters
----------
frames : int, optional
Only the data before `frames` is kept, the rest is... | Truncate the file to a given number of frames.
After this command, the read/write position will be at the new
end of the file.
Parameters
----------
frames : int, optional
Only the data before `frames` is kept, the rest is deleted.
If not specified, the ... | entailment |
def close(self):
"""Close the file. Can be called multiple times."""
if not self.closed:
# be sure to flush data to disk before closing the file
self.flush()
err = _snd.sf_close(self._file)
self._file = None
_error_check(err) | Close the file. Can be called multiple times. | entailment |
def _open(self, file, mode_int, closefd):
"""Call the appropriate sf_open*() function from libsndfile."""
if isinstance(file, (_unicode, bytes)):
if _os.path.isfile(file):
if 'x' in self.mode:
raise OSError("File exists: {0!r}".format(self.name))
... | Call the appropriate sf_open*() function from libsndfile. | entailment |
def _init_virtual_io(self, file):
"""Initialize callback functions for sf_open_virtual()."""
@_ffi.callback("sf_vio_get_filelen")
def vio_get_filelen(user_data):
curr = file.tell()
file.seek(0, SEEK_END)
size = file.tell()
file.seek(curr, SEEK_SET)... | Initialize callback functions for sf_open_virtual(). | entailment |
def _check_frames(self, frames, fill_value):
"""Reduce frames to no more than are available in the file."""
if self.seekable():
remaining_frames = self.frames - self.tell()
if frames < 0 or (frames > remaining_frames and
fill_value is None):
... | Reduce frames to no more than are available in the file. | entailment |
def _check_buffer(self, data, ctype):
"""Convert buffer to cdata and check for valid size."""
assert ctype in _ffi_types.values()
if not isinstance(data, bytes):
data = _ffi.from_buffer(data)
frames, remainder = divmod(len(data),
self.channe... | Convert buffer to cdata and check for valid size. | entailment |
def _create_empty_array(self, frames, always_2d, dtype):
"""Create an empty array with appropriate shape."""
import numpy as np
if always_2d or self.channels > 1:
shape = frames, self.channels
else:
shape = frames,
return np.empty(shape, dtype, order='C') | Create an empty array with appropriate shape. | entailment |
def _check_dtype(self, dtype):
"""Check if dtype string is valid and return ctype string."""
try:
return _ffi_types[dtype]
except KeyError:
raise ValueError("dtype must be one of {0!r} and not {1!r}".format(
sorted(_ffi_types.keys()), dtype)) | Check if dtype string is valid and return ctype string. | entailment |
def _array_io(self, action, array, frames):
"""Check array and call low-level IO function."""
if (array.ndim not in (1, 2) or
array.ndim == 1 and self.channels != 1 or
array.ndim == 2 and array.shape[1] != self.channels):
raise ValueError("Invalid shape: {0!r}... | Check array and call low-level IO function. | entailment |
def _cdata_io(self, action, data, ctype, frames):
"""Call one of libsndfile's read/write functions."""
assert ctype in _ffi_types.values()
self._check_if_closed()
if self.seekable():
curr = self.tell()
func = getattr(_snd, 'sf_' + action + 'f_' + ctype)
frames... | Call one of libsndfile's read/write functions. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.