body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
|---|---|---|---|---|---|---|---|---|---|
d50b92b29aacbe18a8c52bf2b631f637cce2f7800e9be940c810b8d94b223b86
|
@staticmethod
def find(credit_card_token):
'\n Find a credit card, given a credit_card_id. This does not return\n a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided\n credit_card_id is not found. ::\n\n credit_card = braintree.CreditCard.find("my_credit_card_token")\n '
return Configuration.gateway().credit_card.find(credit_card_token)
|
Find a credit card, given a credit_card_id. This does not return
a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided
credit_card_id is not found. ::
credit_card = braintree.CreditCard.find("my_credit_card_token")
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
find
|
Fa67/saleor-shop
| 0
|
python
|
@staticmethod
def find(credit_card_token):
'\n Find a credit card, given a credit_card_id. This does not return\n a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided\n credit_card_id is not found. ::\n\n credit_card = braintree.CreditCard.find("my_credit_card_token")\n '
return Configuration.gateway().credit_card.find(credit_card_token)
|
@staticmethod
def find(credit_card_token):
'\n Find a credit card, given a credit_card_id. This does not return\n a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided\n credit_card_id is not found. ::\n\n credit_card = braintree.CreditCard.find("my_credit_card_token")\n '
return Configuration.gateway().credit_card.find(credit_card_token)<|docstring|>Find a credit card, given a credit_card_id. This does not return
a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided
credit_card_id is not found. ::
credit_card = braintree.CreditCard.find("my_credit_card_token")<|endoftext|>
|
f58df2a74a2fdd8fa02d18723bfb189f85737941b7e235bf1955c6a3c00acda1
|
@staticmethod
def forward(credit_card_token, receiving_merchant_id):
'\n Create a nonce for a credit card in your Braintree vault that can be used by another Braintree merchant.\n\n A credit card token and a receiving merchant ID are required:\n\n result = braintree.CreditCard.forward(\n credit_card.token,\n "another_merchant_public_id"\n })\n '
return Configuration.gateway().credit_card.forward(credit_card_token, receiving_merchant_id)
|
Create a nonce for a credit card in your Braintree vault that can be used by another Braintree merchant.
A credit card token and a receiving merchant ID are required:
result = braintree.CreditCard.forward(
credit_card.token,
"another_merchant_public_id"
})
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
forward
|
Fa67/saleor-shop
| 0
|
python
|
@staticmethod
def forward(credit_card_token, receiving_merchant_id):
'\n Create a nonce for a credit card in your Braintree vault that can be used by another Braintree merchant.\n\n A credit card token and a receiving merchant ID are required:\n\n result = braintree.CreditCard.forward(\n credit_card.token,\n "another_merchant_public_id"\n })\n '
return Configuration.gateway().credit_card.forward(credit_card_token, receiving_merchant_id)
|
@staticmethod
def forward(credit_card_token, receiving_merchant_id):
'\n Create a nonce for a credit card in your Braintree vault that can be used by another Braintree merchant.\n\n A credit card token and a receiving merchant ID are required:\n\n result = braintree.CreditCard.forward(\n credit_card.token,\n "another_merchant_public_id"\n })\n '
return Configuration.gateway().credit_card.forward(credit_card_token, receiving_merchant_id)<|docstring|>Create a nonce for a credit card in your Braintree vault that can be used by another Braintree merchant.
A credit card token and a receiving merchant ID are required:
result = braintree.CreditCard.forward(
credit_card.token,
"another_merchant_public_id"
})<|endoftext|>
|
4a6f2b7ee2b89b014001e28e6cf014877526c50af754727422f2de687a676d37
|
@staticmethod
def from_nonce(nonce):
'\n Convert a payment method nonce into a CreditCard. This does not return\n a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided\n credit_card_id is not found. ::\n\n credit_card = braintree.CreditCard.from_nonce("my_payment_method_nonce")\n '
return Configuration.gateway().credit_card.from_nonce(nonce)
|
Convert a payment method nonce into a CreditCard. This does not return
a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided
credit_card_id is not found. ::
credit_card = braintree.CreditCard.from_nonce("my_payment_method_nonce")
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
from_nonce
|
Fa67/saleor-shop
| 0
|
python
|
@staticmethod
def from_nonce(nonce):
'\n Convert a payment method nonce into a CreditCard. This does not return\n a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided\n credit_card_id is not found. ::\n\n credit_card = braintree.CreditCard.from_nonce("my_payment_method_nonce")\n '
return Configuration.gateway().credit_card.from_nonce(nonce)
|
@staticmethod
def from_nonce(nonce):
'\n Convert a payment method nonce into a CreditCard. This does not return\n a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided\n credit_card_id is not found. ::\n\n credit_card = braintree.CreditCard.from_nonce("my_payment_method_nonce")\n '
return Configuration.gateway().credit_card.from_nonce(nonce)<|docstring|>Convert a payment method nonce into a CreditCard. This does not return
a result object. This will raise a :class:`NotFoundError <braintree.exceptions.not_found_error.NotFoundError>` if the provided
credit_card_id is not found. ::
credit_card = braintree.CreditCard.from_nonce("my_payment_method_nonce")<|endoftext|>
|
329b3b019f78dfaac644e8e766c0fb73babeac1107dc8c918a4e8020695a52f5
|
@staticmethod
def transparent_redirect_create_url():
'\n Returns the url to use for creating CreditCards through transparent redirect.\n '
warnings.warn('Please use TransparentRedirect.url instead', DeprecationWarning)
return Configuration.gateway().credit_card.transparent_redirect_create_url()
|
Returns the url to use for creating CreditCards through transparent redirect.
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
transparent_redirect_create_url
|
Fa67/saleor-shop
| 0
|
python
|
@staticmethod
def transparent_redirect_create_url():
'\n \n '
warnings.warn('Please use TransparentRedirect.url instead', DeprecationWarning)
return Configuration.gateway().credit_card.transparent_redirect_create_url()
|
@staticmethod
def transparent_redirect_create_url():
'\n \n '
warnings.warn('Please use TransparentRedirect.url instead', DeprecationWarning)
return Configuration.gateway().credit_card.transparent_redirect_create_url()<|docstring|>Returns the url to use for creating CreditCards through transparent redirect.<|endoftext|>
|
6ffc8ee6ac0c5396486dac56d46ec6fe3880509e603438ac72bc205017b729b6
|
@staticmethod
def tr_data_for_create(tr_data, redirect_url):
'\n Builds tr_data for CreditCard creation.\n '
return Configuration.gateway().credit_card.tr_data_for_create(tr_data, redirect_url)
|
Builds tr_data for CreditCard creation.
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
tr_data_for_create
|
Fa67/saleor-shop
| 0
|
python
|
@staticmethod
def tr_data_for_create(tr_data, redirect_url):
'\n \n '
return Configuration.gateway().credit_card.tr_data_for_create(tr_data, redirect_url)
|
@staticmethod
def tr_data_for_create(tr_data, redirect_url):
'\n \n '
return Configuration.gateway().credit_card.tr_data_for_create(tr_data, redirect_url)<|docstring|>Builds tr_data for CreditCard creation.<|endoftext|>
|
acff8c263dd24e9b2d93bd3a27a3a6bdb4d7de42e7dcb889525e350b6ddd2b0d
|
@staticmethod
def tr_data_for_update(tr_data, redirect_url):
'\n Builds tr_data for CreditCard updating.\n '
return Configuration.gateway().credit_card.tr_data_for_update(tr_data, redirect_url)
|
Builds tr_data for CreditCard updating.
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
tr_data_for_update
|
Fa67/saleor-shop
| 0
|
python
|
@staticmethod
def tr_data_for_update(tr_data, redirect_url):
'\n \n '
return Configuration.gateway().credit_card.tr_data_for_update(tr_data, redirect_url)
|
@staticmethod
def tr_data_for_update(tr_data, redirect_url):
'\n \n '
return Configuration.gateway().credit_card.tr_data_for_update(tr_data, redirect_url)<|docstring|>Builds tr_data for CreditCard updating.<|endoftext|>
|
1d5c7edd8a6dd19eaaf411934cb34fd66930b7ddd1af8e94b7b427db12850942
|
@staticmethod
def transparent_redirect_update_url():
'\n Returns the url to be used for updating CreditCards through transparent redirect.\n '
warnings.warn('Please use TransparentRedirect.url instead', DeprecationWarning)
return Configuration.gateway().credit_card.transparent_redirect_update_url()
|
Returns the url to be used for updating CreditCards through transparent redirect.
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
transparent_redirect_update_url
|
Fa67/saleor-shop
| 0
|
python
|
@staticmethod
def transparent_redirect_update_url():
'\n \n '
warnings.warn('Please use TransparentRedirect.url instead', DeprecationWarning)
return Configuration.gateway().credit_card.transparent_redirect_update_url()
|
@staticmethod
def transparent_redirect_update_url():
'\n \n '
warnings.warn('Please use TransparentRedirect.url instead', DeprecationWarning)
return Configuration.gateway().credit_card.transparent_redirect_update_url()<|docstring|>Returns the url to be used for updating CreditCards through transparent redirect.<|endoftext|>
|
61fab5329dd55017b57e1ca6e5df1381eb15d05a39c9fcda3048bf833b8d8b65
|
@property
def masked_number(self):
'\n Returns the masked number of the CreditCard.\n '
return ((self.bin + '******') + self.last_4)
|
Returns the masked number of the CreditCard.
|
myvenv/Lib/site-packages/braintree/credit_card.py
|
masked_number
|
Fa67/saleor-shop
| 0
|
python
|
@property
def masked_number(self):
'\n \n '
return ((self.bin + '******') + self.last_4)
|
@property
def masked_number(self):
'\n \n '
return ((self.bin + '******') + self.last_4)<|docstring|>Returns the masked number of the CreditCard.<|endoftext|>
|
434956ca06b9ff7e1644f8dd4aeffd3af113895e01284c1f8332497275577106
|
def populate_tvm_objs(dest_dir, objs):
'Replace tvm-prefixed files in a build worktree.\n\n This function is intended to be used to place TVM source files and libraries into a\n template on-device runtime project.\n\n Parameters\n ----------\n dest_dir : str\n Path to the destination directory.\n\n objs : List[MicroLibrary]\n List of MicroLibrary to place in the project directory.\n\n Returns\n -------\n List[str] :\n List of paths, each relative to `dest_dir` to the newly-copied MicroLibrary files.\n '
copied = []
for p in GLOB_PATTERNS:
for f in glob.glob(os.path.join(dest_dir, p)):
if os.path.isdir(f):
shutil.rmtree(f)
else:
os.unlink(f)
for obj in objs:
for lib_file in obj.library_files:
obj_base = os.path.basename(lib_file)
if obj_base.endswith('.a'):
dest_basename = f'libtvm__{obj_base}'
else:
dest_basename = f'__tvm_{obj_base}'
copied.append(dest_basename)
dest = os.path.join(dest_dir, dest_basename)
shutil.copy(obj.abspath(lib_file), dest)
return copied
|
Replace tvm-prefixed files in a build worktree.
This function is intended to be used to place TVM source files and libraries into a
template on-device runtime project.
Parameters
----------
dest_dir : str
Path to the destination directory.
objs : List[MicroLibrary]
List of MicroLibrary to place in the project directory.
Returns
-------
List[str] :
List of paths, each relative to `dest_dir` to the newly-copied MicroLibrary files.
|
python/tvm/micro/contrib/base.py
|
populate_tvm_objs
|
limenghao/incubator-tvm
| 90
|
python
|
def populate_tvm_objs(dest_dir, objs):
'Replace tvm-prefixed files in a build worktree.\n\n This function is intended to be used to place TVM source files and libraries into a\n template on-device runtime project.\n\n Parameters\n ----------\n dest_dir : str\n Path to the destination directory.\n\n objs : List[MicroLibrary]\n List of MicroLibrary to place in the project directory.\n\n Returns\n -------\n List[str] :\n List of paths, each relative to `dest_dir` to the newly-copied MicroLibrary files.\n '
copied = []
for p in GLOB_PATTERNS:
for f in glob.glob(os.path.join(dest_dir, p)):
if os.path.isdir(f):
shutil.rmtree(f)
else:
os.unlink(f)
for obj in objs:
for lib_file in obj.library_files:
obj_base = os.path.basename(lib_file)
if obj_base.endswith('.a'):
dest_basename = f'libtvm__{obj_base}'
else:
dest_basename = f'__tvm_{obj_base}'
copied.append(dest_basename)
dest = os.path.join(dest_dir, dest_basename)
shutil.copy(obj.abspath(lib_file), dest)
return copied
|
def populate_tvm_objs(dest_dir, objs):
'Replace tvm-prefixed files in a build worktree.\n\n This function is intended to be used to place TVM source files and libraries into a\n template on-device runtime project.\n\n Parameters\n ----------\n dest_dir : str\n Path to the destination directory.\n\n objs : List[MicroLibrary]\n List of MicroLibrary to place in the project directory.\n\n Returns\n -------\n List[str] :\n List of paths, each relative to `dest_dir` to the newly-copied MicroLibrary files.\n '
copied = []
for p in GLOB_PATTERNS:
for f in glob.glob(os.path.join(dest_dir, p)):
if os.path.isdir(f):
shutil.rmtree(f)
else:
os.unlink(f)
for obj in objs:
for lib_file in obj.library_files:
obj_base = os.path.basename(lib_file)
if obj_base.endswith('.a'):
dest_basename = f'libtvm__{obj_base}'
else:
dest_basename = f'__tvm_{obj_base}'
copied.append(dest_basename)
dest = os.path.join(dest_dir, dest_basename)
shutil.copy(obj.abspath(lib_file), dest)
return copied<|docstring|>Replace tvm-prefixed files in a build worktree.
This function is intended to be used to place TVM source files and libraries into a
template on-device runtime project.
Parameters
----------
dest_dir : str
Path to the destination directory.
objs : List[MicroLibrary]
List of MicroLibrary to place in the project directory.
Returns
-------
List[str] :
List of paths, each relative to `dest_dir` to the newly-copied MicroLibrary files.<|endoftext|>
|
43a1dc04cf6d68aa485751991f6331b1ba6022390afc6519aa275c3fe1938e06
|
def test_ksa_adapter_loading_defaults(self):
"No 'url' triggers ksa loading path with defaults."
my_context = context.RequestContext('userid', uuids.my_tenant, auth_token='token')
cl = neutronapi.get_client(my_context)
self.assertEqual('network', cl.httpclient.service_type)
self.assertIsNone(cl.httpclient.service_name)
self.assertEqual(['internal', 'public'], cl.httpclient.interface)
self.assertIsNone(cl.httpclient.region_name)
self.assertIsNone(cl.httpclient.endpoint_override)
|
No 'url' triggers ksa loading path with defaults.
|
nova/tests/unit/network/test_neutronv2.py
|
test_ksa_adapter_loading_defaults
|
cloudscale-ch/nova
| 1
|
python
|
def test_ksa_adapter_loading_defaults(self):
my_context = context.RequestContext('userid', uuids.my_tenant, auth_token='token')
cl = neutronapi.get_client(my_context)
self.assertEqual('network', cl.httpclient.service_type)
self.assertIsNone(cl.httpclient.service_name)
self.assertEqual(['internal', 'public'], cl.httpclient.interface)
self.assertIsNone(cl.httpclient.region_name)
self.assertIsNone(cl.httpclient.endpoint_override)
|
def test_ksa_adapter_loading_defaults(self):
my_context = context.RequestContext('userid', uuids.my_tenant, auth_token='token')
cl = neutronapi.get_client(my_context)
self.assertEqual('network', cl.httpclient.service_type)
self.assertIsNone(cl.httpclient.service_name)
self.assertEqual(['internal', 'public'], cl.httpclient.interface)
self.assertIsNone(cl.httpclient.region_name)
self.assertIsNone(cl.httpclient.endpoint_override)<|docstring|>No 'url' triggers ksa loading path with defaults.<|endoftext|>
|
4eb6fa378ffb9261c9445a4c3b42d063a6e32bbe76dfa6dc05815785bc65ddae
|
def test_ksa_adapter_loading(self):
'Test ksa loading path with specified values.'
self.flags(group='neutron', service_type='st', service_name='sn', valid_interfaces='admin', region_name='RegionTwo', endpoint_override='eo')
my_context = context.RequestContext('userid', uuids.my_tenant, auth_token='token')
cl = neutronapi.get_client(my_context)
self.assertEqual('st', cl.httpclient.service_type)
self.assertEqual('sn', cl.httpclient.service_name)
self.assertEqual(['admin'], cl.httpclient.interface)
self.assertEqual('RegionTwo', cl.httpclient.region_name)
self.assertEqual('eo', cl.httpclient.endpoint_override)
|
Test ksa loading path with specified values.
|
nova/tests/unit/network/test_neutronv2.py
|
test_ksa_adapter_loading
|
cloudscale-ch/nova
| 1
|
python
|
def test_ksa_adapter_loading(self):
self.flags(group='neutron', service_type='st', service_name='sn', valid_interfaces='admin', region_name='RegionTwo', endpoint_override='eo')
my_context = context.RequestContext('userid', uuids.my_tenant, auth_token='token')
cl = neutronapi.get_client(my_context)
self.assertEqual('st', cl.httpclient.service_type)
self.assertEqual('sn', cl.httpclient.service_name)
self.assertEqual(['admin'], cl.httpclient.interface)
self.assertEqual('RegionTwo', cl.httpclient.region_name)
self.assertEqual('eo', cl.httpclient.endpoint_override)
|
def test_ksa_adapter_loading(self):
self.flags(group='neutron', service_type='st', service_name='sn', valid_interfaces='admin', region_name='RegionTwo', endpoint_override='eo')
my_context = context.RequestContext('userid', uuids.my_tenant, auth_token='token')
cl = neutronapi.get_client(my_context)
self.assertEqual('st', cl.httpclient.service_type)
self.assertEqual('sn', cl.httpclient.service_name)
self.assertEqual(['admin'], cl.httpclient.interface)
self.assertEqual('RegionTwo', cl.httpclient.region_name)
self.assertEqual('eo', cl.httpclient.endpoint_override)<|docstring|>Test ksa loading path with specified values.<|endoftext|>
|
1bd28ce8d905085d7f55f4d8fd39e5ec65dc9fb42334e2f751c8b686703f6007
|
def _fake_get_instance_nw_info_helper(self, network_cache, current_neutron_ports, networks=None, port_ids=None):
'Helper function to test get_instance_nw_info.\n\n :param network_cache - data already in the nova network cache.\n :param current_neutron_ports - updated list of ports from neutron.\n :param networks - networks of ports being added to instance.\n :param port_ids - new ports being added to instance.\n '
original_port_ids = copy.copy(port_ids)
original_networks = copy.copy(networks)
api = neutronapi.API()
self.mox.StubOutWithMock(api.db, 'instance_info_cache_update')
api.db.instance_info_cache_update(mox.IgnoreArg(), self.instance['uuid'], mox.IgnoreArg()).AndReturn(fake_info_cache)
neutronapi.get_client(mox.IgnoreArg(), admin=True).MultipleTimes().AndReturn(self.moxed_client)
self.moxed_client.list_ports(tenant_id=self.instance['project_id'], device_id=self.instance['uuid']).AndReturn({'ports': current_neutron_ports})
ifaces = network_cache['info_cache']['network_info']
if (port_ids is None):
port_ids = [iface['id'] for iface in ifaces]
net_ids = [iface['network']['id'] for iface in ifaces]
nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces]
if (networks is None):
if ifaces:
self.moxed_client.list_networks(id=net_ids).AndReturn({'networks': nets})
else:
non_shared_nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces if (not iface['shared'])]
shared_nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces if iface['shared']]
self.moxed_client.list_networks(shared=False, tenant_id=self.instance['project_id']).AndReturn({'networks': non_shared_nets})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': shared_nets})
else:
networks = (networks + [dict(id=iface['network']['id'], name=iface['network']['label'], tenant_id=iface['network']['meta']['tenant_id']) for iface in ifaces])
port_ids = ([iface['id'] for iface in ifaces] + port_ids)
index = 0
current_neutron_port_map = {}
for current_neutron_port in current_neutron_ports:
current_neutron_port_map[current_neutron_port['id']] = current_neutron_port
for port_id in port_ids:
current_neutron_port = current_neutron_port_map.get(port_id)
if current_neutron_port:
for ip in current_neutron_port['fixed_ips']:
self.moxed_client.list_floatingips(fixed_ip_address=ip['ip_address'], port_id=current_neutron_port['id']).AndReturn({'floatingips': [self.float_data2[index]]})
self.moxed_client.list_subnets(id=mox.SameElementsAs([ip['subnet_id']])).AndReturn({'subnets': [self.subnet_data_n[index]]})
self.moxed_client.list_ports(network_id=current_neutron_port['network_id'], device_owner='network:dhcp').AndReturn({'ports': self.dhcp_port_data1})
index += 1
self.instance['info_cache'] = self._fake_instance_info_cache(network_cache['info_cache']['network_info'], self.instance['uuid'])
self.mox.StubOutWithMock(api.db, 'instance_info_cache_get')
api.db.instance_info_cache_get(mox.IgnoreArg(), self.instance['uuid']).MultipleTimes().AndReturn(self.instance['info_cache'])
self.mox.ReplayAll()
instance = self._fake_instance_object_with_info_cache(self.instance)
nw_infs = api.get_instance_nw_info(self.context, instance, networks=original_networks, port_ids=original_port_ids)
self.assertEqual(index, len(nw_infs))
for iface_index in range(index):
self.assertEqual(port_ids[iface_index], nw_infs[iface_index]['id'])
|
Helper function to test get_instance_nw_info.
:param network_cache - data already in the nova network cache.
:param current_neutron_ports - updated list of ports from neutron.
:param networks - networks of ports being added to instance.
:param port_ids - new ports being added to instance.
|
nova/tests/unit/network/test_neutronv2.py
|
_fake_get_instance_nw_info_helper
|
cloudscale-ch/nova
| 1
|
python
|
def _fake_get_instance_nw_info_helper(self, network_cache, current_neutron_ports, networks=None, port_ids=None):
'Helper function to test get_instance_nw_info.\n\n :param network_cache - data already in the nova network cache.\n :param current_neutron_ports - updated list of ports from neutron.\n :param networks - networks of ports being added to instance.\n :param port_ids - new ports being added to instance.\n '
original_port_ids = copy.copy(port_ids)
original_networks = copy.copy(networks)
api = neutronapi.API()
self.mox.StubOutWithMock(api.db, 'instance_info_cache_update')
api.db.instance_info_cache_update(mox.IgnoreArg(), self.instance['uuid'], mox.IgnoreArg()).AndReturn(fake_info_cache)
neutronapi.get_client(mox.IgnoreArg(), admin=True).MultipleTimes().AndReturn(self.moxed_client)
self.moxed_client.list_ports(tenant_id=self.instance['project_id'], device_id=self.instance['uuid']).AndReturn({'ports': current_neutron_ports})
ifaces = network_cache['info_cache']['network_info']
if (port_ids is None):
port_ids = [iface['id'] for iface in ifaces]
net_ids = [iface['network']['id'] for iface in ifaces]
nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces]
if (networks is None):
if ifaces:
self.moxed_client.list_networks(id=net_ids).AndReturn({'networks': nets})
else:
non_shared_nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces if (not iface['shared'])]
shared_nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces if iface['shared']]
self.moxed_client.list_networks(shared=False, tenant_id=self.instance['project_id']).AndReturn({'networks': non_shared_nets})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': shared_nets})
else:
networks = (networks + [dict(id=iface['network']['id'], name=iface['network']['label'], tenant_id=iface['network']['meta']['tenant_id']) for iface in ifaces])
port_ids = ([iface['id'] for iface in ifaces] + port_ids)
index = 0
current_neutron_port_map = {}
for current_neutron_port in current_neutron_ports:
current_neutron_port_map[current_neutron_port['id']] = current_neutron_port
for port_id in port_ids:
current_neutron_port = current_neutron_port_map.get(port_id)
if current_neutron_port:
for ip in current_neutron_port['fixed_ips']:
self.moxed_client.list_floatingips(fixed_ip_address=ip['ip_address'], port_id=current_neutron_port['id']).AndReturn({'floatingips': [self.float_data2[index]]})
self.moxed_client.list_subnets(id=mox.SameElementsAs([ip['subnet_id']])).AndReturn({'subnets': [self.subnet_data_n[index]]})
self.moxed_client.list_ports(network_id=current_neutron_port['network_id'], device_owner='network:dhcp').AndReturn({'ports': self.dhcp_port_data1})
index += 1
self.instance['info_cache'] = self._fake_instance_info_cache(network_cache['info_cache']['network_info'], self.instance['uuid'])
self.mox.StubOutWithMock(api.db, 'instance_info_cache_get')
api.db.instance_info_cache_get(mox.IgnoreArg(), self.instance['uuid']).MultipleTimes().AndReturn(self.instance['info_cache'])
self.mox.ReplayAll()
instance = self._fake_instance_object_with_info_cache(self.instance)
nw_infs = api.get_instance_nw_info(self.context, instance, networks=original_networks, port_ids=original_port_ids)
self.assertEqual(index, len(nw_infs))
for iface_index in range(index):
self.assertEqual(port_ids[iface_index], nw_infs[iface_index]['id'])
|
def _fake_get_instance_nw_info_helper(self, network_cache, current_neutron_ports, networks=None, port_ids=None):
'Helper function to test get_instance_nw_info.\n\n :param network_cache - data already in the nova network cache.\n :param current_neutron_ports - updated list of ports from neutron.\n :param networks - networks of ports being added to instance.\n :param port_ids - new ports being added to instance.\n '
original_port_ids = copy.copy(port_ids)
original_networks = copy.copy(networks)
api = neutronapi.API()
self.mox.StubOutWithMock(api.db, 'instance_info_cache_update')
api.db.instance_info_cache_update(mox.IgnoreArg(), self.instance['uuid'], mox.IgnoreArg()).AndReturn(fake_info_cache)
neutronapi.get_client(mox.IgnoreArg(), admin=True).MultipleTimes().AndReturn(self.moxed_client)
self.moxed_client.list_ports(tenant_id=self.instance['project_id'], device_id=self.instance['uuid']).AndReturn({'ports': current_neutron_ports})
ifaces = network_cache['info_cache']['network_info']
if (port_ids is None):
port_ids = [iface['id'] for iface in ifaces]
net_ids = [iface['network']['id'] for iface in ifaces]
nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces]
if (networks is None):
if ifaces:
self.moxed_client.list_networks(id=net_ids).AndReturn({'networks': nets})
else:
non_shared_nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces if (not iface['shared'])]
shared_nets = [{'id': iface['network']['id'], 'name': iface['network']['label'], 'tenant_id': iface['network']['meta']['tenant_id']} for iface in ifaces if iface['shared']]
self.moxed_client.list_networks(shared=False, tenant_id=self.instance['project_id']).AndReturn({'networks': non_shared_nets})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': shared_nets})
else:
networks = (networks + [dict(id=iface['network']['id'], name=iface['network']['label'], tenant_id=iface['network']['meta']['tenant_id']) for iface in ifaces])
port_ids = ([iface['id'] for iface in ifaces] + port_ids)
index = 0
current_neutron_port_map = {}
for current_neutron_port in current_neutron_ports:
current_neutron_port_map[current_neutron_port['id']] = current_neutron_port
for port_id in port_ids:
current_neutron_port = current_neutron_port_map.get(port_id)
if current_neutron_port:
for ip in current_neutron_port['fixed_ips']:
self.moxed_client.list_floatingips(fixed_ip_address=ip['ip_address'], port_id=current_neutron_port['id']).AndReturn({'floatingips': [self.float_data2[index]]})
self.moxed_client.list_subnets(id=mox.SameElementsAs([ip['subnet_id']])).AndReturn({'subnets': [self.subnet_data_n[index]]})
self.moxed_client.list_ports(network_id=current_neutron_port['network_id'], device_owner='network:dhcp').AndReturn({'ports': self.dhcp_port_data1})
index += 1
self.instance['info_cache'] = self._fake_instance_info_cache(network_cache['info_cache']['network_info'], self.instance['uuid'])
self.mox.StubOutWithMock(api.db, 'instance_info_cache_get')
api.db.instance_info_cache_get(mox.IgnoreArg(), self.instance['uuid']).MultipleTimes().AndReturn(self.instance['info_cache'])
self.mox.ReplayAll()
instance = self._fake_instance_object_with_info_cache(self.instance)
nw_infs = api.get_instance_nw_info(self.context, instance, networks=original_networks, port_ids=original_port_ids)
self.assertEqual(index, len(nw_infs))
for iface_index in range(index):
self.assertEqual(port_ids[iface_index], nw_infs[iface_index]['id'])<|docstring|>Helper function to test get_instance_nw_info.
:param network_cache - data already in the nova network cache.
:param current_neutron_ports - updated list of ports from neutron.
:param networks - networks of ports being added to instance.
:param port_ids - new ports being added to instance.<|endoftext|>
|
4236db6b3560ca507ec8cba0cbf47d388e2f190c68876e17bd7ab058c16ccde1
|
def test_allocate_for_instance_with_requested_non_available_network(self):
'verify that a non available network is ignored.\n self.nets2 (net_idx=2) is composed of self.nets3[0] and self.nets3[1]\n Do not create a port on a non available network self.nets3[2].\n '
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets3[0], self.nets3[2], self.nets3[1])])
requested_networks[0].tag = 'foo'
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self._allocate_for_instance(net_idx=2, requested_networks=requested_networks)
self.assertEqual(2, len(self._vifs_created))
vifs_really_created = [vif for vif in self._vifs_created if vif.create.called]
self.assertEqual(2, len(vifs_really_created))
self.assertEqual([('foo', ('fakemac1/%s' % uuids.fake)), (None, ('fakemac3/%s' % uuids.fake))], [(vif.tag, vif.address) for vif in vifs_really_created])
|
verify that a non available network is ignored.
self.nets2 (net_idx=2) is composed of self.nets3[0] and self.nets3[1]
Do not create a port on a non available network self.nets3[2].
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_with_requested_non_available_network
|
cloudscale-ch/nova
| 1
|
python
|
def test_allocate_for_instance_with_requested_non_available_network(self):
'verify that a non available network is ignored.\n self.nets2 (net_idx=2) is composed of self.nets3[0] and self.nets3[1]\n Do not create a port on a non available network self.nets3[2].\n '
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets3[0], self.nets3[2], self.nets3[1])])
requested_networks[0].tag = 'foo'
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self._allocate_for_instance(net_idx=2, requested_networks=requested_networks)
self.assertEqual(2, len(self._vifs_created))
vifs_really_created = [vif for vif in self._vifs_created if vif.create.called]
self.assertEqual(2, len(vifs_really_created))
self.assertEqual([('foo', ('fakemac1/%s' % uuids.fake)), (None, ('fakemac3/%s' % uuids.fake))], [(vif.tag, vif.address) for vif in vifs_really_created])
|
def test_allocate_for_instance_with_requested_non_available_network(self):
'verify that a non available network is ignored.\n self.nets2 (net_idx=2) is composed of self.nets3[0] and self.nets3[1]\n Do not create a port on a non available network self.nets3[2].\n '
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets3[0], self.nets3[2], self.nets3[1])])
requested_networks[0].tag = 'foo'
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self._allocate_for_instance(net_idx=2, requested_networks=requested_networks)
self.assertEqual(2, len(self._vifs_created))
vifs_really_created = [vif for vif in self._vifs_created if vif.create.called]
self.assertEqual(2, len(vifs_really_created))
self.assertEqual([('foo', ('fakemac1/%s' % uuids.fake)), (None, ('fakemac3/%s' % uuids.fake))], [(vif.tag, vif.address) for vif in vifs_really_created])<|docstring|>verify that a non available network is ignored.
self.nets2 (net_idx=2) is composed of self.nets3[0] and self.nets3[1]
Do not create a port on a non available network self.nets3[2].<|endoftext|>
|
681bcc3b574a831d0cdbb6c0db349f0fc60e6272ab0c0cce04a1d073f9baf64d
|
def test_allocate_for_instance_no_networks(self):
'verify the exception thrown when there are no networks defined.'
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': model.NetworkInfo([])})
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(shared=True).AndReturn({'networks': model.NetworkInfo([])})
self.mox.ReplayAll()
nwinfo = api.allocate_for_instance(self.context, self.instance, False, None)
self.assertEqual(0, len(nwinfo))
|
verify the exception thrown when there are no networks defined.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_no_networks
|
cloudscale-ch/nova
| 1
|
python
|
def test_allocate_for_instance_no_networks(self):
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': model.NetworkInfo([])})
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(shared=True).AndReturn({'networks': model.NetworkInfo([])})
self.mox.ReplayAll()
nwinfo = api.allocate_for_instance(self.context, self.instance, False, None)
self.assertEqual(0, len(nwinfo))
|
def test_allocate_for_instance_no_networks(self):
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': model.NetworkInfo([])})
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(shared=True).AndReturn({'networks': model.NetworkInfo([])})
self.mox.ReplayAll()
nwinfo = api.allocate_for_instance(self.context, self.instance, False, None)
self.assertEqual(0, len(nwinfo))<|docstring|>verify the exception thrown when there are no networks defined.<|endoftext|>
|
04487d3193dd561234e6756dca821595b0fb3b3de973681b321f714722dcd3a7
|
@mock.patch('nova.network.neutronv2.api.API._populate_neutron_extension_values')
@mock.patch('nova.network.neutronv2.api.API._create_ports_for_instance')
@mock.patch('nova.network.neutronv2.api.API._unbind_ports')
def test_allocate_for_instance_ex1(self, mock_unbind, mock_create_ports, mock_populate):
'verify we will delete created ports\n if we fail to allocate all net resources.\n\n Mox to raise exception when creating a second port.\n In this case, the code should delete the first created port.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets2[0], self.nets2[1])])
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(id=[uuids.my_netid1, uuids.my_netid2]).AndReturn({'networks': self.nets2})
mock_create_ports.return_value = [(request, getattr(uuids, ('portid_%s' % request.network_id))) for request in requested_networks]
neutronapi.get_client(mox.IgnoreArg(), admin=True).AndReturn(self.moxed_client)
index = 0
for network in self.nets2:
binding_port_req_body = {'port': {'device_id': self.instance.uuid, 'device_owner': 'compute:nova'}}
port_req_body = {'port': {'network_id': network['id'], 'admin_state_up': True, 'tenant_id': self.instance.project_id}}
port_req_body['port'].update(binding_port_req_body['port'])
port_id = getattr(uuids, ('portid_%s' % network['id']))
port = {'id': port_id, 'mac_address': 'foo'}
if (index == 0):
self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndReturn({'port': port})
else:
NeutronOverQuota = exceptions.MacAddressInUseClient()
self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndRaise(NeutronOverQuota)
index += 1
self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[0]['id'])))
self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[1]['id'])))
self.mox.ReplayAll()
self.assertRaises(exception.PortInUse, api.allocate_for_instance, self.context, self.instance, False, requested_networks=requested_networks)
mock_unbind.assert_called_once_with(self.context, [], self.moxed_client, mock.ANY)
|
verify we will delete created ports
if we fail to allocate all net resources.
Mox to raise exception when creating a second port.
In this case, the code should delete the first created port.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_ex1
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch('nova.network.neutronv2.api.API._populate_neutron_extension_values')
@mock.patch('nova.network.neutronv2.api.API._create_ports_for_instance')
@mock.patch('nova.network.neutronv2.api.API._unbind_ports')
def test_allocate_for_instance_ex1(self, mock_unbind, mock_create_ports, mock_populate):
'verify we will delete created ports\n if we fail to allocate all net resources.\n\n Mox to raise exception when creating a second port.\n In this case, the code should delete the first created port.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets2[0], self.nets2[1])])
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(id=[uuids.my_netid1, uuids.my_netid2]).AndReturn({'networks': self.nets2})
mock_create_ports.return_value = [(request, getattr(uuids, ('portid_%s' % request.network_id))) for request in requested_networks]
neutronapi.get_client(mox.IgnoreArg(), admin=True).AndReturn(self.moxed_client)
index = 0
for network in self.nets2:
binding_port_req_body = {'port': {'device_id': self.instance.uuid, 'device_owner': 'compute:nova'}}
port_req_body = {'port': {'network_id': network['id'], 'admin_state_up': True, 'tenant_id': self.instance.project_id}}
port_req_body['port'].update(binding_port_req_body['port'])
port_id = getattr(uuids, ('portid_%s' % network['id']))
port = {'id': port_id, 'mac_address': 'foo'}
if (index == 0):
self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndReturn({'port': port})
else:
NeutronOverQuota = exceptions.MacAddressInUseClient()
self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndRaise(NeutronOverQuota)
index += 1
self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[0]['id'])))
self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[1]['id'])))
self.mox.ReplayAll()
self.assertRaises(exception.PortInUse, api.allocate_for_instance, self.context, self.instance, False, requested_networks=requested_networks)
mock_unbind.assert_called_once_with(self.context, [], self.moxed_client, mock.ANY)
|
@mock.patch('nova.network.neutronv2.api.API._populate_neutron_extension_values')
@mock.patch('nova.network.neutronv2.api.API._create_ports_for_instance')
@mock.patch('nova.network.neutronv2.api.API._unbind_ports')
def test_allocate_for_instance_ex1(self, mock_unbind, mock_create_ports, mock_populate):
'verify we will delete created ports\n if we fail to allocate all net resources.\n\n Mox to raise exception when creating a second port.\n In this case, the code should delete the first created port.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets2[0], self.nets2[1])])
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(id=[uuids.my_netid1, uuids.my_netid2]).AndReturn({'networks': self.nets2})
mock_create_ports.return_value = [(request, getattr(uuids, ('portid_%s' % request.network_id))) for request in requested_networks]
neutronapi.get_client(mox.IgnoreArg(), admin=True).AndReturn(self.moxed_client)
index = 0
for network in self.nets2:
binding_port_req_body = {'port': {'device_id': self.instance.uuid, 'device_owner': 'compute:nova'}}
port_req_body = {'port': {'network_id': network['id'], 'admin_state_up': True, 'tenant_id': self.instance.project_id}}
port_req_body['port'].update(binding_port_req_body['port'])
port_id = getattr(uuids, ('portid_%s' % network['id']))
port = {'id': port_id, 'mac_address': 'foo'}
if (index == 0):
self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndReturn({'port': port})
else:
NeutronOverQuota = exceptions.MacAddressInUseClient()
self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndRaise(NeutronOverQuota)
index += 1
self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[0]['id'])))
self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[1]['id'])))
self.mox.ReplayAll()
self.assertRaises(exception.PortInUse, api.allocate_for_instance, self.context, self.instance, False, requested_networks=requested_networks)
mock_unbind.assert_called_once_with(self.context, [], self.moxed_client, mock.ANY)<|docstring|>verify we will delete created ports
if we fail to allocate all net resources.
Mox to raise exception when creating a second port.
In this case, the code should delete the first created port.<|endoftext|>
|
0cb796baa42576f944a6733c46240bdfb66255083330d18aed5e42fb641f3c01
|
def test_allocate_for_instance_ex2(self):
'verify we have no port to delete\n if we fail to allocate the first net resource.\n\n Mox to raise exception when creating the first port.\n In this case, the code should not delete any ports.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets2[0], self.nets2[1])])
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(id=[uuids.my_netid1, uuids.my_netid2]).AndReturn({'networks': self.nets2})
port_req_body = {'port': {'network_id': self.nets2[0]['id'], 'admin_state_up': True, 'device_id': self.instance.uuid, 'tenant_id': self.instance.project_id}}
self.moxed_client.create_port(MyComparator(port_req_body)).AndRaise(Exception('fail to create port'))
self.mox.ReplayAll()
self.assertRaises(NEUTRON_CLIENT_EXCEPTION, api.allocate_for_instance, self.context, self.instance, False, requested_networks=requested_networks)
|
verify we have no port to delete
if we fail to allocate the first net resource.
Mox to raise exception when creating the first port.
In this case, the code should not delete any ports.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_ex2
|
cloudscale-ch/nova
| 1
|
python
|
def test_allocate_for_instance_ex2(self):
'verify we have no port to delete\n if we fail to allocate the first net resource.\n\n Mox to raise exception when creating the first port.\n In this case, the code should not delete any ports.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets2[0], self.nets2[1])])
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(id=[uuids.my_netid1, uuids.my_netid2]).AndReturn({'networks': self.nets2})
port_req_body = {'port': {'network_id': self.nets2[0]['id'], 'admin_state_up': True, 'device_id': self.instance.uuid, 'tenant_id': self.instance.project_id}}
self.moxed_client.create_port(MyComparator(port_req_body)).AndRaise(Exception('fail to create port'))
self.mox.ReplayAll()
self.assertRaises(NEUTRON_CLIENT_EXCEPTION, api.allocate_for_instance, self.context, self.instance, False, requested_networks=requested_networks)
|
def test_allocate_for_instance_ex2(self):
'verify we have no port to delete\n if we fail to allocate the first net resource.\n\n Mox to raise exception when creating the first port.\n In this case, the code should not delete any ports.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
api = neutronapi.API()
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets2[0], self.nets2[1])])
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(id=[uuids.my_netid1, uuids.my_netid2]).AndReturn({'networks': self.nets2})
port_req_body = {'port': {'network_id': self.nets2[0]['id'], 'admin_state_up': True, 'device_id': self.instance.uuid, 'tenant_id': self.instance.project_id}}
self.moxed_client.create_port(MyComparator(port_req_body)).AndRaise(Exception('fail to create port'))
self.mox.ReplayAll()
self.assertRaises(NEUTRON_CLIENT_EXCEPTION, api.allocate_for_instance, self.context, self.instance, False, requested_networks=requested_networks)<|docstring|>verify we have no port to delete
if we fail to allocate the first net resource.
Mox to raise exception when creating the first port.
In this case, the code should not delete any ports.<|endoftext|>
|
17652a8bf05b36f49adbd4b72eae33165e8d117397c421e344a3cad7ea05330f
|
def test_allocate_for_instance_with_externalnet_forbidden(self):
"Only one network is available, it's external, and the client\n is unauthorized to use it.\n "
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': model.NetworkInfo([])})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': self.nets8})
self.mox.ReplayAll()
api = neutronapi.API()
self.assertRaises(exception.ExternalNetworkAttachForbidden, api.allocate_for_instance, self.context, self.instance, False, None)
|
Only one network is available, it's external, and the client
is unauthorized to use it.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_with_externalnet_forbidden
|
cloudscale-ch/nova
| 1
|
python
|
def test_allocate_for_instance_with_externalnet_forbidden(self):
"Only one network is available, it's external, and the client\n is unauthorized to use it.\n "
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': model.NetworkInfo([])})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': self.nets8})
self.mox.ReplayAll()
api = neutronapi.API()
self.assertRaises(exception.ExternalNetworkAttachForbidden, api.allocate_for_instance, self.context, self.instance, False, None)
|
def test_allocate_for_instance_with_externalnet_forbidden(self):
"Only one network is available, it's external, and the client\n is unauthorized to use it.\n "
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': model.NetworkInfo([])})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': self.nets8})
self.mox.ReplayAll()
api = neutronapi.API()
self.assertRaises(exception.ExternalNetworkAttachForbidden, api.allocate_for_instance, self.context, self.instance, False, None)<|docstring|>Only one network is available, it's external, and the client
is unauthorized to use it.<|endoftext|>
|
9aebc12e904003ebf702b1e59f39d24ec1eb7de15d1bfb2705cf936c64118bbc
|
def test_allocate_for_instance_with_externalnet_multiple(self):
'Multiple networks are available, one the client is authorized\n to use, and an external one the client is unauthorized to use.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': self.nets1})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': self.nets8})
self.mox.ReplayAll()
api = neutronapi.API()
self.assertRaises(exception.NetworkAmbiguous, api.allocate_for_instance, self.context, self.instance, False, None)
|
Multiple networks are available, one the client is authorized
to use, and an external one the client is unauthorized to use.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_with_externalnet_multiple
|
cloudscale-ch/nova
| 1
|
python
|
def test_allocate_for_instance_with_externalnet_multiple(self):
'Multiple networks are available, one the client is authorized\n to use, and an external one the client is unauthorized to use.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': self.nets1})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': self.nets8})
self.mox.ReplayAll()
api = neutronapi.API()
self.assertRaises(exception.NetworkAmbiguous, api.allocate_for_instance, self.context, self.instance, False, None)
|
def test_allocate_for_instance_with_externalnet_multiple(self):
'Multiple networks are available, one the client is authorized\n to use, and an external one the client is unauthorized to use.\n '
self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
self.moxed_client.list_networks(tenant_id=self.instance.project_id, shared=False).AndReturn({'networks': self.nets1})
self.moxed_client.list_networks(shared=True).AndReturn({'networks': self.nets8})
self.mox.ReplayAll()
api = neutronapi.API()
self.assertRaises(exception.NetworkAmbiguous, api.allocate_for_instance, self.context, self.instance, False, None)<|docstring|>Multiple networks are available, one the client is authorized
to use, and an external one the client is unauthorized to use.<|endoftext|>
|
f4b20a3f47885e83f8603d9b170c1c8125ca55dbd46dee5e8ad1b8c7712aa27a
|
def test_allocate_for_instance_with_externalnet_admin_ctx(self):
"Only one network is available, it's external, and the client\n is authorized.\n "
admin_ctx = context.RequestContext('userid', uuids.my_tenant, is_admin=True)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
api = self._stub_allocate_for_instance(net_idx=8)
api.allocate_for_instance(admin_ctx, self.instance, False, None)
|
Only one network is available, it's external, and the client
is authorized.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_with_externalnet_admin_ctx
|
cloudscale-ch/nova
| 1
|
python
|
def test_allocate_for_instance_with_externalnet_admin_ctx(self):
"Only one network is available, it's external, and the client\n is authorized.\n "
admin_ctx = context.RequestContext('userid', uuids.my_tenant, is_admin=True)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
api = self._stub_allocate_for_instance(net_idx=8)
api.allocate_for_instance(admin_ctx, self.instance, False, None)
|
def test_allocate_for_instance_with_externalnet_admin_ctx(self):
"Only one network is available, it's external, and the client\n is authorized.\n "
admin_ctx = context.RequestContext('userid', uuids.my_tenant, is_admin=True)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
api = self._stub_allocate_for_instance(net_idx=8)
api.allocate_for_instance(admin_ctx, self.instance, False, None)<|docstring|>Only one network is available, it's external, and the client
is authorized.<|endoftext|>
|
0105b0fd91bbb1d7fa6e0482a9ba11146ddb1925de12efcb79ca97dce4e7d15e
|
def test_allocate_for_instance_with_external_shared_net(self):
"Only one network is available, it's external and shared."
ctx = context.RequestContext('userid', uuids.my_tenant)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
api = self._stub_allocate_for_instance(net_idx=10)
api.allocate_for_instance(ctx, self.instance, False, None)
|
Only one network is available, it's external and shared.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_for_instance_with_external_shared_net
|
cloudscale-ch/nova
| 1
|
python
|
def test_allocate_for_instance_with_external_shared_net(self):
ctx = context.RequestContext('userid', uuids.my_tenant)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
api = self._stub_allocate_for_instance(net_idx=10)
api.allocate_for_instance(ctx, self.instance, False, None)
|
def test_allocate_for_instance_with_external_shared_net(self):
ctx = context.RequestContext('userid', uuids.my_tenant)
neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
api = self._stub_allocate_for_instance(net_idx=10)
api.allocate_for_instance(ctx, self.instance, False, None)<|docstring|>Only one network is available, it's external and shared.<|endoftext|>
|
ae1e3d91a8a2ceacdc21d9149e742d74203469317d6e2395f2ac3d7fa09697a8
|
@mock.patch('nova.network.neutronv2.api.LOG')
def test_get_instance_nw_info_verify_duplicates_ignored(self, mock_log):
'test that the returned networks & port_ids from\n _gather_port_ids_and_networks doesn\'t contain any duplicates\n\n The test fakes an instance with two ports connected to two networks.\n The _gather_port_ids_and_networks method will be called with the\n instance and a list of port ids of which one port id is configured\n already to the instance (== duplicate #1) and a list of\n networks that already contains a network to which an instance port\n is connected (== duplicate #2).\n\n All-in-all, we expect the resulting port ids list to contain 3 items\n (["instance_port_1", "port_1", "port_2"]) and the resulting networks\n list to contain 3 items (["net_1", "net_2", "instance_network_1"])\n while the warning message for duplicate items was executed twice\n (due to "duplicate #1" & "duplicate #2")\n '
networks = [model.Network(id='net_1'), model.Network(id='net_2')]
port_ids = ['port_1', 'port_2']
instance_networks = [{'id': 'instance_network_1', 'name': 'fake_network', 'tenant_id': 'fake_tenant_id'}]
instance_port_ids = ['instance_port_1']
network_info = model.NetworkInfo([{'id': port_ids[0], 'network': networks[0]}, {'id': instance_port_ids[0], 'network': model.Network(id=instance_networks[0]['id'], label=instance_networks[0]['name'], meta={'tenant_id': instance_networks[0]['tenant_id']})}])
instance_uuid = uuids.fake
instance = objects.Instance(uuid=instance_uuid, info_cache=objects.InstanceInfoCache(context=self.context, instance_uuid=instance_uuid, network_info=network_info))
(new_networks, new_port_ids) = self.api._gather_port_ids_and_networks(self.context, instance, networks, port_ids)
self.assertEqual(new_networks, (networks + instance_networks))
self.assertEqual(new_port_ids, (instance_port_ids + port_ids))
self.assertEqual(2, mock_log.warning.call_count)
|
test that the returned networks & port_ids from
_gather_port_ids_and_networks doesn't contain any duplicates
The test fakes an instance with two ports connected to two networks.
The _gather_port_ids_and_networks method will be called with the
instance and a list of port ids of which one port id is configured
already to the instance (== duplicate #1) and a list of
networks that already contains a network to which an instance port
is connected (== duplicate #2).
All-in-all, we expect the resulting port ids list to contain 3 items
(["instance_port_1", "port_1", "port_2"]) and the resulting networks
list to contain 3 items (["net_1", "net_2", "instance_network_1"])
while the warning message for duplicate items was executed twice
(due to "duplicate #1" & "duplicate #2")
|
nova/tests/unit/network/test_neutronv2.py
|
test_get_instance_nw_info_verify_duplicates_ignored
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch('nova.network.neutronv2.api.LOG')
def test_get_instance_nw_info_verify_duplicates_ignored(self, mock_log):
'test that the returned networks & port_ids from\n _gather_port_ids_and_networks doesn\'t contain any duplicates\n\n The test fakes an instance with two ports connected to two networks.\n The _gather_port_ids_and_networks method will be called with the\n instance and a list of port ids of which one port id is configured\n already to the instance (== duplicate #1) and a list of\n networks that already contains a network to which an instance port\n is connected (== duplicate #2).\n\n All-in-all, we expect the resulting port ids list to contain 3 items\n (["instance_port_1", "port_1", "port_2"]) and the resulting networks\n list to contain 3 items (["net_1", "net_2", "instance_network_1"])\n while the warning message for duplicate items was executed twice\n (due to "duplicate #1" & "duplicate #2")\n '
networks = [model.Network(id='net_1'), model.Network(id='net_2')]
port_ids = ['port_1', 'port_2']
instance_networks = [{'id': 'instance_network_1', 'name': 'fake_network', 'tenant_id': 'fake_tenant_id'}]
instance_port_ids = ['instance_port_1']
network_info = model.NetworkInfo([{'id': port_ids[0], 'network': networks[0]}, {'id': instance_port_ids[0], 'network': model.Network(id=instance_networks[0]['id'], label=instance_networks[0]['name'], meta={'tenant_id': instance_networks[0]['tenant_id']})}])
instance_uuid = uuids.fake
instance = objects.Instance(uuid=instance_uuid, info_cache=objects.InstanceInfoCache(context=self.context, instance_uuid=instance_uuid, network_info=network_info))
(new_networks, new_port_ids) = self.api._gather_port_ids_and_networks(self.context, instance, networks, port_ids)
self.assertEqual(new_networks, (networks + instance_networks))
self.assertEqual(new_port_ids, (instance_port_ids + port_ids))
self.assertEqual(2, mock_log.warning.call_count)
|
@mock.patch('nova.network.neutronv2.api.LOG')
def test_get_instance_nw_info_verify_duplicates_ignored(self, mock_log):
'test that the returned networks & port_ids from\n _gather_port_ids_and_networks doesn\'t contain any duplicates\n\n The test fakes an instance with two ports connected to two networks.\n The _gather_port_ids_and_networks method will be called with the\n instance and a list of port ids of which one port id is configured\n already to the instance (== duplicate #1) and a list of\n networks that already contains a network to which an instance port\n is connected (== duplicate #2).\n\n All-in-all, we expect the resulting port ids list to contain 3 items\n (["instance_port_1", "port_1", "port_2"]) and the resulting networks\n list to contain 3 items (["net_1", "net_2", "instance_network_1"])\n while the warning message for duplicate items was executed twice\n (due to "duplicate #1" & "duplicate #2")\n '
networks = [model.Network(id='net_1'), model.Network(id='net_2')]
port_ids = ['port_1', 'port_2']
instance_networks = [{'id': 'instance_network_1', 'name': 'fake_network', 'tenant_id': 'fake_tenant_id'}]
instance_port_ids = ['instance_port_1']
network_info = model.NetworkInfo([{'id': port_ids[0], 'network': networks[0]}, {'id': instance_port_ids[0], 'network': model.Network(id=instance_networks[0]['id'], label=instance_networks[0]['name'], meta={'tenant_id': instance_networks[0]['tenant_id']})}])
instance_uuid = uuids.fake
instance = objects.Instance(uuid=instance_uuid, info_cache=objects.InstanceInfoCache(context=self.context, instance_uuid=instance_uuid, network_info=network_info))
(new_networks, new_port_ids) = self.api._gather_port_ids_and_networks(self.context, instance, networks, port_ids)
self.assertEqual(new_networks, (networks + instance_networks))
self.assertEqual(new_port_ids, (instance_port_ids + port_ids))
self.assertEqual(2, mock_log.warning.call_count)<|docstring|>test that the returned networks & port_ids from
_gather_port_ids_and_networks doesn't contain any duplicates
The test fakes an instance with two ports connected to two networks.
The _gather_port_ids_and_networks method will be called with the
instance and a list of port ids of which one port id is configured
already to the instance (== duplicate #1) and a list of
networks that already contains a network to which an instance port
is connected (== duplicate #2).
All-in-all, we expect the resulting port ids list to contain 3 items
(["instance_port_1", "port_1", "port_2"]) and the resulting networks
list to contain 3 items (["net_1", "net_2", "instance_network_1"])
while the warning message for duplicate items was executed twice
(due to "duplicate #1" & "duplicate #2")<|endoftext|>
|
e7e119a20e1d6c70f4cfbf2de8ef7470440ca5db505012ab4ae5514a3404aa44
|
def test_validate_networks_over_limit_quota(self):
'Test validates that a relevant exception is being raised when\n there are more ports defined, than there is a quota for it.\n '
requested_networks = [(uuids.my_netid1, '10.0.1.2', None, None), (uuids.my_netid2, '10.0.1.3', None, None)]
list_port_values = [({'network_id': uuids.my_netid1, 'fixed_ips': 'ip_address=10.0.1.2', 'fields': 'device_id'}, {'ports': []}), ({'network_id': uuids.my_netid2, 'fixed_ips': 'ip_address=10.0.1.3', 'fields': 'device_id'}, {'ports': []}), ({'tenant_id': 'fake-project', 'fields': ['id']}, {'ports': [1, 2, 3, 4, 5]})]
nets = [{'subnets': '1'}, {'subnets': '2'}]
def _fake_list_ports(**search_opts):
for (args, return_value) in list_port_values:
if (args == search_opts):
return return_value
with test.nested(mock.patch.object(self.api, '_get_available_networks', return_value=nets), mock.patch.object(client.Client, 'list_ports', side_effect=_fake_list_ports), mock.patch.object(client.Client, 'show_quota', return_value={'quota': {'port': 1}})):
exc = self.assertRaises(exception.PortLimitExceeded, self.api.validate_networks, self.context, requested_networks, 1)
expected_exception_msg = ('The number of defined ports: %(ports)d is over the limit: %(quota)d' % {'ports': 5, 'quota': 1})
self.assertEqual(expected_exception_msg, str(exc))
|
Test validates that a relevant exception is being raised when
there are more ports defined, than there is a quota for it.
|
nova/tests/unit/network/test_neutronv2.py
|
test_validate_networks_over_limit_quota
|
cloudscale-ch/nova
| 1
|
python
|
def test_validate_networks_over_limit_quota(self):
'Test validates that a relevant exception is being raised when\n there are more ports defined, than there is a quota for it.\n '
requested_networks = [(uuids.my_netid1, '10.0.1.2', None, None), (uuids.my_netid2, '10.0.1.3', None, None)]
list_port_values = [({'network_id': uuids.my_netid1, 'fixed_ips': 'ip_address=10.0.1.2', 'fields': 'device_id'}, {'ports': []}), ({'network_id': uuids.my_netid2, 'fixed_ips': 'ip_address=10.0.1.3', 'fields': 'device_id'}, {'ports': []}), ({'tenant_id': 'fake-project', 'fields': ['id']}, {'ports': [1, 2, 3, 4, 5]})]
nets = [{'subnets': '1'}, {'subnets': '2'}]
def _fake_list_ports(**search_opts):
for (args, return_value) in list_port_values:
if (args == search_opts):
return return_value
with test.nested(mock.patch.object(self.api, '_get_available_networks', return_value=nets), mock.patch.object(client.Client, 'list_ports', side_effect=_fake_list_ports), mock.patch.object(client.Client, 'show_quota', return_value={'quota': {'port': 1}})):
exc = self.assertRaises(exception.PortLimitExceeded, self.api.validate_networks, self.context, requested_networks, 1)
expected_exception_msg = ('The number of defined ports: %(ports)d is over the limit: %(quota)d' % {'ports': 5, 'quota': 1})
self.assertEqual(expected_exception_msg, str(exc))
|
def test_validate_networks_over_limit_quota(self):
'Test validates that a relevant exception is being raised when\n there are more ports defined, than there is a quota for it.\n '
requested_networks = [(uuids.my_netid1, '10.0.1.2', None, None), (uuids.my_netid2, '10.0.1.3', None, None)]
list_port_values = [({'network_id': uuids.my_netid1, 'fixed_ips': 'ip_address=10.0.1.2', 'fields': 'device_id'}, {'ports': []}), ({'network_id': uuids.my_netid2, 'fixed_ips': 'ip_address=10.0.1.3', 'fields': 'device_id'}, {'ports': []}), ({'tenant_id': 'fake-project', 'fields': ['id']}, {'ports': [1, 2, 3, 4, 5]})]
nets = [{'subnets': '1'}, {'subnets': '2'}]
def _fake_list_ports(**search_opts):
for (args, return_value) in list_port_values:
if (args == search_opts):
return return_value
with test.nested(mock.patch.object(self.api, '_get_available_networks', return_value=nets), mock.patch.object(client.Client, 'list_ports', side_effect=_fake_list_ports), mock.patch.object(client.Client, 'show_quota', return_value={'quota': {'port': 1}})):
exc = self.assertRaises(exception.PortLimitExceeded, self.api.validate_networks, self.context, requested_networks, 1)
expected_exception_msg = ('The number of defined ports: %(ports)d is over the limit: %(quota)d' % {'ports': 5, 'quota': 1})
self.assertEqual(expected_exception_msg, str(exc))<|docstring|>Test validates that a relevant exception is being raised when
there are more ports defined, than there is a quota for it.<|endoftext|>
|
2e501da9acec18cb874795c69a380d2c80224cc706ba3167ac587a7d69fc789d
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': None, 'id': 'abc'})
def test_release_floating_ip(self, mock_get_ip, mock_ntrn):
'Validate default behavior.'
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
address = '172.24.4.227'
self.api.release_floating_ip(self.context, address)
mock_ntrn.assert_called_once_with(self.context)
mock_get_ip.assert_called_once_with(mock_nc, address)
mock_nc.delete_floatingip.assert_called_once_with('abc')
|
Validate default behavior.
|
nova/tests/unit/network/test_neutronv2.py
|
test_release_floating_ip
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': None, 'id': 'abc'})
def test_release_floating_ip(self, mock_get_ip, mock_ntrn):
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
address = '172.24.4.227'
self.api.release_floating_ip(self.context, address)
mock_ntrn.assert_called_once_with(self.context)
mock_get_ip.assert_called_once_with(mock_nc, address)
mock_nc.delete_floatingip.assert_called_once_with('abc')
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': None, 'id': 'abc'})
def test_release_floating_ip(self, mock_get_ip, mock_ntrn):
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
address = '172.24.4.227'
self.api.release_floating_ip(self.context, address)
mock_ntrn.assert_called_once_with(self.context)
mock_get_ip.assert_called_once_with(mock_nc, address)
mock_nc.delete_floatingip.assert_called_once_with('abc')<|docstring|>Validate default behavior.<|endoftext|>
|
016c21ebe7f328ac48fbcd89b4d8166e4059d423888d1a336a90b89769abb2d3
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': 'abc', 'id': 'abc'})
def test_release_floating_ip_associated(self, mock_get_ip, mock_ntrn):
'Ensure release fails if a port is still associated with it.\n\n If the floating IP has a port associated with it, as indicated by a\n configured port_id, then any attempt to release should fail.\n '
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
address = '172.24.4.227'
self.assertRaises(exception.FloatingIpAssociated, self.api.release_floating_ip, self.context, address)
|
Ensure release fails if a port is still associated with it.
If the floating IP has a port associated with it, as indicated by a
configured port_id, then any attempt to release should fail.
|
nova/tests/unit/network/test_neutronv2.py
|
test_release_floating_ip_associated
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': 'abc', 'id': 'abc'})
def test_release_floating_ip_associated(self, mock_get_ip, mock_ntrn):
'Ensure release fails if a port is still associated with it.\n\n If the floating IP has a port associated with it, as indicated by a\n configured port_id, then any attempt to release should fail.\n '
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
address = '172.24.4.227'
self.assertRaises(exception.FloatingIpAssociated, self.api.release_floating_ip, self.context, address)
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': 'abc', 'id': 'abc'})
def test_release_floating_ip_associated(self, mock_get_ip, mock_ntrn):
'Ensure release fails if a port is still associated with it.\n\n If the floating IP has a port associated with it, as indicated by a\n configured port_id, then any attempt to release should fail.\n '
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
address = '172.24.4.227'
self.assertRaises(exception.FloatingIpAssociated, self.api.release_floating_ip, self.context, address)<|docstring|>Ensure release fails if a port is still associated with it.
If the floating IP has a port associated with it, as indicated by a
configured port_id, then any attempt to release should fail.<|endoftext|>
|
fea5ec2b9f36d182548231581cbc56218cb065ff6ac64e5894146f5543ce8c7b
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': None, 'id': 'abc'})
def test_release_floating_ip_not_found(self, mock_get_ip, mock_ntrn):
"Ensure neutron's NotFound exception is correctly handled.\n\n Sometimes, trying to delete a floating IP multiple times in a short\n delay can trigger an exception because the operation is not atomic. If\n neutronclient's call to delete fails with a NotFound error, then we\n should correctly handle this.\n "
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
mock_nc.delete_floatingip.side_effect = exceptions.NotFound()
address = '172.24.4.227'
self.assertRaises(exception.FloatingIpNotFoundForAddress, self.api.release_floating_ip, self.context, address)
|
Ensure neutron's NotFound exception is correctly handled.
Sometimes, trying to delete a floating IP multiple times in a short
delay can trigger an exception because the operation is not atomic. If
neutronclient's call to delete fails with a NotFound error, then we
should correctly handle this.
|
nova/tests/unit/network/test_neutronv2.py
|
test_release_floating_ip_not_found
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': None, 'id': 'abc'})
def test_release_floating_ip_not_found(self, mock_get_ip, mock_ntrn):
"Ensure neutron's NotFound exception is correctly handled.\n\n Sometimes, trying to delete a floating IP multiple times in a short\n delay can trigger an exception because the operation is not atomic. If\n neutronclient's call to delete fails with a NotFound error, then we\n should correctly handle this.\n "
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
mock_nc.delete_floatingip.side_effect = exceptions.NotFound()
address = '172.24.4.227'
self.assertRaises(exception.FloatingIpNotFoundForAddress, self.api.release_floating_ip, self.context, address)
|
@mock.patch('nova.network.neutronv2.api.get_client')
@mock.patch('nova.network.neutronv2.api.API._get_floating_ip_by_address', return_value={'port_id': None, 'id': 'abc'})
def test_release_floating_ip_not_found(self, mock_get_ip, mock_ntrn):
"Ensure neutron's NotFound exception is correctly handled.\n\n Sometimes, trying to delete a floating IP multiple times in a short\n delay can trigger an exception because the operation is not atomic. If\n neutronclient's call to delete fails with a NotFound error, then we\n should correctly handle this.\n "
mock_nc = mock.Mock()
mock_ntrn.return_value = mock_nc
mock_nc.delete_floatingip.side_effect = exceptions.NotFound()
address = '172.24.4.227'
self.assertRaises(exception.FloatingIpNotFoundForAddress, self.api.release_floating_ip, self.context, address)<|docstring|>Ensure neutron's NotFound exception is correctly handled.
Sometimes, trying to delete a floating IP multiple times in a short
delay can trigger an exception because the operation is not atomic. If
neutronclient's call to delete fails with a NotFound error, then we
should correctly handle this.<|endoftext|>
|
22e29acae7febd9ed23e85d6f6dc772ef20ce8e245c13793c6b371357fc632a8
|
@mock.patch.object(neutronapi, 'get_client', return_value=mock.Mock())
def test_update_port_bindings_for_instance_binding_profile_none(self, get_client_mock):
'Tests _update_port_binding_for_instance when the binding:profile\n value is None.\n '
instance = fake_instance.fake_instance_obj(self.context)
self.api._has_port_binding_extension = mock.Mock(return_value=True)
fake_ports = {'ports': [{'id': uuids.portid, neutronapi.BINDING_PROFILE: None, neutronapi.BINDING_HOST_ID: instance.host}]}
list_ports_mock = mock.Mock(return_value=fake_ports)
get_client_mock.return_value.list_ports = list_ports_mock
update_port_mock = mock.Mock()
get_client_mock.return_value.update_port = update_port_mock
self.api._update_port_binding_for_instance(self.context, instance, 'my-host')
update_port_mock.assert_called_once_with(uuids.portid, {'port': {neutronapi.BINDING_HOST_ID: 'my-host'}})
|
Tests _update_port_binding_for_instance when the binding:profile
value is None.
|
nova/tests/unit/network/test_neutronv2.py
|
test_update_port_bindings_for_instance_binding_profile_none
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch.object(neutronapi, 'get_client', return_value=mock.Mock())
def test_update_port_bindings_for_instance_binding_profile_none(self, get_client_mock):
'Tests _update_port_binding_for_instance when the binding:profile\n value is None.\n '
instance = fake_instance.fake_instance_obj(self.context)
self.api._has_port_binding_extension = mock.Mock(return_value=True)
fake_ports = {'ports': [{'id': uuids.portid, neutronapi.BINDING_PROFILE: None, neutronapi.BINDING_HOST_ID: instance.host}]}
list_ports_mock = mock.Mock(return_value=fake_ports)
get_client_mock.return_value.list_ports = list_ports_mock
update_port_mock = mock.Mock()
get_client_mock.return_value.update_port = update_port_mock
self.api._update_port_binding_for_instance(self.context, instance, 'my-host')
update_port_mock.assert_called_once_with(uuids.portid, {'port': {neutronapi.BINDING_HOST_ID: 'my-host'}})
|
@mock.patch.object(neutronapi, 'get_client', return_value=mock.Mock())
def test_update_port_bindings_for_instance_binding_profile_none(self, get_client_mock):
'Tests _update_port_binding_for_instance when the binding:profile\n value is None.\n '
instance = fake_instance.fake_instance_obj(self.context)
self.api._has_port_binding_extension = mock.Mock(return_value=True)
fake_ports = {'ports': [{'id': uuids.portid, neutronapi.BINDING_PROFILE: None, neutronapi.BINDING_HOST_ID: instance.host}]}
list_ports_mock = mock.Mock(return_value=fake_ports)
get_client_mock.return_value.list_ports = list_ports_mock
update_port_mock = mock.Mock()
get_client_mock.return_value.update_port = update_port_mock
self.api._update_port_binding_for_instance(self.context, instance, 'my-host')
update_port_mock.assert_called_once_with(uuids.portid, {'port': {neutronapi.BINDING_HOST_ID: 'my-host'}})<|docstring|>Tests _update_port_binding_for_instance when the binding:profile
value is None.<|endoftext|>
|
b62fbc9144eddf73cf88d419dd8c8f18812537a343f37a5e4d119d749ea3898b
|
@mock.patch.object(neutronapi, 'get_client', return_value=mock.Mock())
def test_update_port_profile_for_migration_teardown_false_none_profile(self, get_client_mock):
'Tests setup_networks_on_host when migrating the port to the\n destination host and the binding:profile is None in the port.\n '
instance = fake_instance.fake_instance_obj(self.context)
self.api._has_port_binding_extension = mock.Mock(return_value=True)
get_ports = {'ports': [{'id': uuids.port_id, neutronapi.BINDING_HOST_ID: instance.host, neutronapi.BINDING_PROFILE: None}]}
self.api.list_ports = mock.Mock(return_value=get_ports)
update_port_mock = mock.Mock()
get_client_mock.return_value.update_port = update_port_mock
migrate_profile = {neutronapi.MIGRATING_ATTR: 'my-new-host'}
port_data = {'port': {neutronapi.BINDING_PROFILE: migrate_profile}}
self.api.setup_networks_on_host(self.context, instance, host='my-new-host', teardown=False)
update_port_mock.assert_called_once_with(uuids.port_id, port_data)
|
Tests setup_networks_on_host when migrating the port to the
destination host and the binding:profile is None in the port.
|
nova/tests/unit/network/test_neutronv2.py
|
test_update_port_profile_for_migration_teardown_false_none_profile
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch.object(neutronapi, 'get_client', return_value=mock.Mock())
def test_update_port_profile_for_migration_teardown_false_none_profile(self, get_client_mock):
'Tests setup_networks_on_host when migrating the port to the\n destination host and the binding:profile is None in the port.\n '
instance = fake_instance.fake_instance_obj(self.context)
self.api._has_port_binding_extension = mock.Mock(return_value=True)
get_ports = {'ports': [{'id': uuids.port_id, neutronapi.BINDING_HOST_ID: instance.host, neutronapi.BINDING_PROFILE: None}]}
self.api.list_ports = mock.Mock(return_value=get_ports)
update_port_mock = mock.Mock()
get_client_mock.return_value.update_port = update_port_mock
migrate_profile = {neutronapi.MIGRATING_ATTR: 'my-new-host'}
port_data = {'port': {neutronapi.BINDING_PROFILE: migrate_profile}}
self.api.setup_networks_on_host(self.context, instance, host='my-new-host', teardown=False)
update_port_mock.assert_called_once_with(uuids.port_id, port_data)
|
@mock.patch.object(neutronapi, 'get_client', return_value=mock.Mock())
def test_update_port_profile_for_migration_teardown_false_none_profile(self, get_client_mock):
'Tests setup_networks_on_host when migrating the port to the\n destination host and the binding:profile is None in the port.\n '
instance = fake_instance.fake_instance_obj(self.context)
self.api._has_port_binding_extension = mock.Mock(return_value=True)
get_ports = {'ports': [{'id': uuids.port_id, neutronapi.BINDING_HOST_ID: instance.host, neutronapi.BINDING_PROFILE: None}]}
self.api.list_ports = mock.Mock(return_value=get_ports)
update_port_mock = mock.Mock()
get_client_mock.return_value.update_port = update_port_mock
migrate_profile = {neutronapi.MIGRATING_ATTR: 'my-new-host'}
port_data = {'port': {neutronapi.BINDING_PROFILE: migrate_profile}}
self.api.setup_networks_on_host(self.context, instance, host='my-new-host', teardown=False)
update_port_mock.assert_called_once_with(uuids.port_id, port_data)<|docstring|>Tests setup_networks_on_host when migrating the port to the
destination host and the binding:profile is None in the port.<|endoftext|>
|
0a20dbe0b5da63112cc9fefaf29b515848b2e76acde62401494effd07971a686
|
def test__setup_migration_port_profile_no_update(self):
'Tests the case that the port binding profile already has the\n "migrating_to" attribute set to the provided host so the port update\n call is skipped.\n '
ports = ([{neutronapi.BINDING_HOST_ID: 'source-host', neutronapi.BINDING_PROFILE: {neutronapi.MIGRATING_ATTR: 'dest-host'}}] * 2)
with mock.patch.object(self.api, '_update_port_with_migration_profile', new_callable=mock.NonCallableMock):
self.api._setup_migration_port_profile(self.context, mock.sentinel.instance, 'dest-host', mock.sentinel.admin_client, ports)
|
Tests the case that the port binding profile already has the
"migrating_to" attribute set to the provided host so the port update
call is skipped.
|
nova/tests/unit/network/test_neutronv2.py
|
test__setup_migration_port_profile_no_update
|
cloudscale-ch/nova
| 1
|
python
|
def test__setup_migration_port_profile_no_update(self):
'Tests the case that the port binding profile already has the\n "migrating_to" attribute set to the provided host so the port update\n call is skipped.\n '
ports = ([{neutronapi.BINDING_HOST_ID: 'source-host', neutronapi.BINDING_PROFILE: {neutronapi.MIGRATING_ATTR: 'dest-host'}}] * 2)
with mock.patch.object(self.api, '_update_port_with_migration_profile', new_callable=mock.NonCallableMock):
self.api._setup_migration_port_profile(self.context, mock.sentinel.instance, 'dest-host', mock.sentinel.admin_client, ports)
|
def test__setup_migration_port_profile_no_update(self):
'Tests the case that the port binding profile already has the\n "migrating_to" attribute set to the provided host so the port update\n call is skipped.\n '
ports = ([{neutronapi.BINDING_HOST_ID: 'source-host', neutronapi.BINDING_PROFILE: {neutronapi.MIGRATING_ATTR: 'dest-host'}}] * 2)
with mock.patch.object(self.api, '_update_port_with_migration_profile', new_callable=mock.NonCallableMock):
self.api._setup_migration_port_profile(self.context, mock.sentinel.instance, 'dest-host', mock.sentinel.admin_client, ports)<|docstring|>Tests the case that the port binding profile already has the
"migrating_to" attribute set to the provided host so the port update
call is skipped.<|endoftext|>
|
e5684995d48f4658ced8024e91b1ae1bcce32d26a08cfc3a61b3ba01186bd30e
|
@mock.patch('nova.network.neutronv2.api._filter_hypervisor_macs')
@mock.patch('nova.network.neutronv2.api.API._validate_requested_port_ids')
@mock.patch('nova.network.neutronv2.api.API._get_available_networks')
@mock.patch('nova.network.neutronv2.api.get_client')
def test_allocate_port_for_instance_no_networks(self, mock_getclient, mock_avail_nets, mock_validate_port_ids, mock_filter_macs):
'Tests that if no networks are requested and no networks are\n available, we fail with InterfaceAttachFailedNoNetwork.\n '
instance = fake_instance.fake_instance_obj(self.context)
mock_validate_port_ids.return_value = ({}, [])
mock_filter_macs.return_value = None
mock_avail_nets.return_value = []
api = neutronapi.API()
ex = self.assertRaises(exception.InterfaceAttachFailedNoNetwork, api.allocate_port_for_instance, self.context, instance, port_id=None)
self.assertEqual("No specific network was requested and none are available for project 'fake-project'.", six.text_type(ex))
|
Tests that if no networks are requested and no networks are
available, we fail with InterfaceAttachFailedNoNetwork.
|
nova/tests/unit/network/test_neutronv2.py
|
test_allocate_port_for_instance_no_networks
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch('nova.network.neutronv2.api._filter_hypervisor_macs')
@mock.patch('nova.network.neutronv2.api.API._validate_requested_port_ids')
@mock.patch('nova.network.neutronv2.api.API._get_available_networks')
@mock.patch('nova.network.neutronv2.api.get_client')
def test_allocate_port_for_instance_no_networks(self, mock_getclient, mock_avail_nets, mock_validate_port_ids, mock_filter_macs):
'Tests that if no networks are requested and no networks are\n available, we fail with InterfaceAttachFailedNoNetwork.\n '
instance = fake_instance.fake_instance_obj(self.context)
mock_validate_port_ids.return_value = ({}, [])
mock_filter_macs.return_value = None
mock_avail_nets.return_value = []
api = neutronapi.API()
ex = self.assertRaises(exception.InterfaceAttachFailedNoNetwork, api.allocate_port_for_instance, self.context, instance, port_id=None)
self.assertEqual("No specific network was requested and none are available for project 'fake-project'.", six.text_type(ex))
|
@mock.patch('nova.network.neutronv2.api._filter_hypervisor_macs')
@mock.patch('nova.network.neutronv2.api.API._validate_requested_port_ids')
@mock.patch('nova.network.neutronv2.api.API._get_available_networks')
@mock.patch('nova.network.neutronv2.api.get_client')
def test_allocate_port_for_instance_no_networks(self, mock_getclient, mock_avail_nets, mock_validate_port_ids, mock_filter_macs):
'Tests that if no networks are requested and no networks are\n available, we fail with InterfaceAttachFailedNoNetwork.\n '
instance = fake_instance.fake_instance_obj(self.context)
mock_validate_port_ids.return_value = ({}, [])
mock_filter_macs.return_value = None
mock_avail_nets.return_value = []
api = neutronapi.API()
ex = self.assertRaises(exception.InterfaceAttachFailedNoNetwork, api.allocate_port_for_instance, self.context, instance, port_id=None)
self.assertEqual("No specific network was requested and none are available for project 'fake-project'.", six.text_type(ex))<|docstring|>Tests that if no networks are requested and no networks are
available, we fail with InterfaceAttachFailedNoNetwork.<|endoftext|>
|
b710800298c09b06428336ffc09377073e5e0a545b049a388e62168282511bb0
|
@mock.patch('nova.network.neutronv2.api.API._populate_neutron_extension_values')
@mock.patch('nova.network.neutronv2.api.API._update_port', side_effect=(mock.MagicMock(), exception.PortInUse(port_id=uuids.created_port_id)))
@mock.patch.object(objects.VirtualInterface, 'create')
@mock.patch.object(objects.VirtualInterface, 'destroy')
@mock.patch('nova.network.neutronv2.api.API._unbind_ports')
@mock.patch('nova.network.neutronv2.api.API._delete_ports')
def test_update_ports_for_instance_fails_rollback_ports_and_vifs(self, mock_delete_ports, mock_unbind_ports, mock_vif_destroy, mock_vif_create, mock_update_port, mock_populate_ext_values):
'Makes sure we rollback ports and VIFs if we fail updating ports'
instance = fake_instance.fake_instance_obj(self.context)
ntrn = mock.Mock(spec='neutronclient.v2_0.client.Client')
requests_and_created_ports = [(objects.NetworkRequest(network_id=uuids.network_id, port_id=uuids.preexisting_port_id), None), (objects.NetworkRequest(network_id=uuids.network_id, port_id=uuids.created_port_id), uuids.created_port_id)]
network = {'id': uuids.network_id}
nets = {uuids.network_id: network}
self.assertRaises(exception.PortInUse, self.api._update_ports_for_instance, self.context, instance, ntrn, ntrn, requests_and_created_ports, nets, bind_host_id=None, available_macs=None, requested_ports_dict=None)
mock_update_port.assert_has_calls([mock.call(ntrn, instance, uuids.preexisting_port_id, mock.ANY), mock.call(ntrn, instance, uuids.created_port_id, mock.ANY)])
mock_vif_create.assert_called_once_with()
mock_vif_destroy.assert_called_once_with()
mock_unbind_ports.assert_called_once_with(self.context, [uuids.preexisting_port_id], ntrn, ntrn)
mock_delete_ports.assert_called_once_with(ntrn, instance, [uuids.created_port_id])
|
Makes sure we rollback ports and VIFs if we fail updating ports
|
nova/tests/unit/network/test_neutronv2.py
|
test_update_ports_for_instance_fails_rollback_ports_and_vifs
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch('nova.network.neutronv2.api.API._populate_neutron_extension_values')
@mock.patch('nova.network.neutronv2.api.API._update_port', side_effect=(mock.MagicMock(), exception.PortInUse(port_id=uuids.created_port_id)))
@mock.patch.object(objects.VirtualInterface, 'create')
@mock.patch.object(objects.VirtualInterface, 'destroy')
@mock.patch('nova.network.neutronv2.api.API._unbind_ports')
@mock.patch('nova.network.neutronv2.api.API._delete_ports')
def test_update_ports_for_instance_fails_rollback_ports_and_vifs(self, mock_delete_ports, mock_unbind_ports, mock_vif_destroy, mock_vif_create, mock_update_port, mock_populate_ext_values):
instance = fake_instance.fake_instance_obj(self.context)
ntrn = mock.Mock(spec='neutronclient.v2_0.client.Client')
requests_and_created_ports = [(objects.NetworkRequest(network_id=uuids.network_id, port_id=uuids.preexisting_port_id), None), (objects.NetworkRequest(network_id=uuids.network_id, port_id=uuids.created_port_id), uuids.created_port_id)]
network = {'id': uuids.network_id}
nets = {uuids.network_id: network}
self.assertRaises(exception.PortInUse, self.api._update_ports_for_instance, self.context, instance, ntrn, ntrn, requests_and_created_ports, nets, bind_host_id=None, available_macs=None, requested_ports_dict=None)
mock_update_port.assert_has_calls([mock.call(ntrn, instance, uuids.preexisting_port_id, mock.ANY), mock.call(ntrn, instance, uuids.created_port_id, mock.ANY)])
mock_vif_create.assert_called_once_with()
mock_vif_destroy.assert_called_once_with()
mock_unbind_ports.assert_called_once_with(self.context, [uuids.preexisting_port_id], ntrn, ntrn)
mock_delete_ports.assert_called_once_with(ntrn, instance, [uuids.created_port_id])
|
@mock.patch('nova.network.neutronv2.api.API._populate_neutron_extension_values')
@mock.patch('nova.network.neutronv2.api.API._update_port', side_effect=(mock.MagicMock(), exception.PortInUse(port_id=uuids.created_port_id)))
@mock.patch.object(objects.VirtualInterface, 'create')
@mock.patch.object(objects.VirtualInterface, 'destroy')
@mock.patch('nova.network.neutronv2.api.API._unbind_ports')
@mock.patch('nova.network.neutronv2.api.API._delete_ports')
def test_update_ports_for_instance_fails_rollback_ports_and_vifs(self, mock_delete_ports, mock_unbind_ports, mock_vif_destroy, mock_vif_create, mock_update_port, mock_populate_ext_values):
instance = fake_instance.fake_instance_obj(self.context)
ntrn = mock.Mock(spec='neutronclient.v2_0.client.Client')
requests_and_created_ports = [(objects.NetworkRequest(network_id=uuids.network_id, port_id=uuids.preexisting_port_id), None), (objects.NetworkRequest(network_id=uuids.network_id, port_id=uuids.created_port_id), uuids.created_port_id)]
network = {'id': uuids.network_id}
nets = {uuids.network_id: network}
self.assertRaises(exception.PortInUse, self.api._update_ports_for_instance, self.context, instance, ntrn, ntrn, requests_and_created_ports, nets, bind_host_id=None, available_macs=None, requested_ports_dict=None)
mock_update_port.assert_has_calls([mock.call(ntrn, instance, uuids.preexisting_port_id, mock.ANY), mock.call(ntrn, instance, uuids.created_port_id, mock.ANY)])
mock_vif_create.assert_called_once_with()
mock_vif_destroy.assert_called_once_with()
mock_unbind_ports.assert_called_once_with(self.context, [uuids.preexisting_port_id], ntrn, ntrn)
mock_delete_ports.assert_called_once_with(ntrn, instance, [uuids.created_port_id])<|docstring|>Makes sure we rollback ports and VIFs if we fail updating ports<|endoftext|>
|
82cce8a8ec5b878c0e844933a5d7a4f5236c6ba14a2a99ff905618230cb2d07c
|
@mock.patch.object(neutronapi, 'get_client')
def test_create_pci_requests_for_sriov_ports_no_allocate(self, getclient):
'Tests that create_pci_requests_for_sriov_ports is a noop if\n networks are specifically requested to not be allocated.\n '
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net_req_obj.NETWORK_ID_NONE)])
pci_requests = objects.InstancePCIRequests()
api = neutronapi.API()
api.create_pci_requests_for_sriov_ports(self.context, pci_requests, requested_networks)
self.assertFalse(getclient.called)
|
Tests that create_pci_requests_for_sriov_ports is a noop if
networks are specifically requested to not be allocated.
|
nova/tests/unit/network/test_neutronv2.py
|
test_create_pci_requests_for_sriov_ports_no_allocate
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch.object(neutronapi, 'get_client')
def test_create_pci_requests_for_sriov_ports_no_allocate(self, getclient):
'Tests that create_pci_requests_for_sriov_ports is a noop if\n networks are specifically requested to not be allocated.\n '
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net_req_obj.NETWORK_ID_NONE)])
pci_requests = objects.InstancePCIRequests()
api = neutronapi.API()
api.create_pci_requests_for_sriov_ports(self.context, pci_requests, requested_networks)
self.assertFalse(getclient.called)
|
@mock.patch.object(neutronapi, 'get_client')
def test_create_pci_requests_for_sriov_ports_no_allocate(self, getclient):
'Tests that create_pci_requests_for_sriov_ports is a noop if\n networks are specifically requested to not be allocated.\n '
requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net_req_obj.NETWORK_ID_NONE)])
pci_requests = objects.InstancePCIRequests()
api = neutronapi.API()
api.create_pci_requests_for_sriov_ports(self.context, pci_requests, requested_networks)
self.assertFalse(getclient.called)<|docstring|>Tests that create_pci_requests_for_sriov_ports is a noop if
networks are specifically requested to not be allocated.<|endoftext|>
|
996440315fa186638a852f86d052162060fa6f2882e45a9c66c1abf4f0427589
|
@mock.patch.object(neutronapi, 'get_client')
def test_associate_floating_ip_conflict(self, mock_get_client):
'Tests that if Neutron raises a Conflict we handle it and re-raise\n as a nova-specific exception.\n '
mock_get_client.return_value.update_floatingip.side_effect = exceptions.Conflict('Cannot associate floating IP 172.24.5.15 (60a8f00b-4404-4518-ad66-00448a155904) with port 95ee1ffb-6d41-447d-a90e-b6ce5d9c92fa using fixed IP 10.1.0.9, as that fixed IP already has a floating IP on external network bdcda645-f612-40ab-a956-0d95af42cf7c.')
with test.nested(mock.patch.object(self.api, '_get_port_id_by_fixed_address', return_value='95ee1ffb-6d41-447d-a90e-b6ce5d9c92fa'), mock.patch.object(self.api, '_get_floating_ip_by_address', return_value={'id': uuids.floating_ip_id})) as (_get_floating_ip_by_address, _get_port_id_by_fixed_address):
instance = fake_instance.fake_instance_obj(self.context, uuid='2a2200ec-02fe-484e-885b-9bae7b21ecba')
self.assertRaises(exception.FloatingIpAssociateFailed, self.api.associate_floating_ip, self.context, instance, '172.24.5.15', '10.1.0.9')
|
Tests that if Neutron raises a Conflict we handle it and re-raise
as a nova-specific exception.
|
nova/tests/unit/network/test_neutronv2.py
|
test_associate_floating_ip_conflict
|
cloudscale-ch/nova
| 1
|
python
|
@mock.patch.object(neutronapi, 'get_client')
def test_associate_floating_ip_conflict(self, mock_get_client):
'Tests that if Neutron raises a Conflict we handle it and re-raise\n as a nova-specific exception.\n '
mock_get_client.return_value.update_floatingip.side_effect = exceptions.Conflict('Cannot associate floating IP 172.24.5.15 (60a8f00b-4404-4518-ad66-00448a155904) with port 95ee1ffb-6d41-447d-a90e-b6ce5d9c92fa using fixed IP 10.1.0.9, as that fixed IP already has a floating IP on external network bdcda645-f612-40ab-a956-0d95af42cf7c.')
with test.nested(mock.patch.object(self.api, '_get_port_id_by_fixed_address', return_value='95ee1ffb-6d41-447d-a90e-b6ce5d9c92fa'), mock.patch.object(self.api, '_get_floating_ip_by_address', return_value={'id': uuids.floating_ip_id})) as (_get_floating_ip_by_address, _get_port_id_by_fixed_address):
instance = fake_instance.fake_instance_obj(self.context, uuid='2a2200ec-02fe-484e-885b-9bae7b21ecba')
self.assertRaises(exception.FloatingIpAssociateFailed, self.api.associate_floating_ip, self.context, instance, '172.24.5.15', '10.1.0.9')
|
@mock.patch.object(neutronapi, 'get_client')
def test_associate_floating_ip_conflict(self, mock_get_client):
'Tests that if Neutron raises a Conflict we handle it and re-raise\n as a nova-specific exception.\n '
mock_get_client.return_value.update_floatingip.side_effect = exceptions.Conflict('Cannot associate floating IP 172.24.5.15 (60a8f00b-4404-4518-ad66-00448a155904) with port 95ee1ffb-6d41-447d-a90e-b6ce5d9c92fa using fixed IP 10.1.0.9, as that fixed IP already has a floating IP on external network bdcda645-f612-40ab-a956-0d95af42cf7c.')
with test.nested(mock.patch.object(self.api, '_get_port_id_by_fixed_address', return_value='95ee1ffb-6d41-447d-a90e-b6ce5d9c92fa'), mock.patch.object(self.api, '_get_floating_ip_by_address', return_value={'id': uuids.floating_ip_id})) as (_get_floating_ip_by_address, _get_port_id_by_fixed_address):
instance = fake_instance.fake_instance_obj(self.context, uuid='2a2200ec-02fe-484e-885b-9bae7b21ecba')
self.assertRaises(exception.FloatingIpAssociateFailed, self.api.associate_floating_ip, self.context, instance, '172.24.5.15', '10.1.0.9')<|docstring|>Tests that if Neutron raises a Conflict we handle it and re-raise
as a nova-specific exception.<|endoftext|>
|
423ac0730ec717b93c8df91d322fcfd1f3e918c9da5eb3f8ccef58e1cfa67fe7
|
def __init__(self):
'\n Initializes Tree global variables\n '
self.layout = None
self.positive_links = None
self.negative_links = None
self.edges = None
self.nodes = None
self.path = None
|
Initializes Tree global variables
|
networkgx/trees.py
|
__init__
|
skyliquid22/networkgx
| 0
|
python
|
def __init__(self):
'\n \n '
self.layout = None
self.positive_links = None
self.negative_links = None
self.edges = None
self.nodes = None
self.path = None
|
def __init__(self):
'\n \n '
self.layout = None
self.positive_links = None
self.negative_links = None
self.edges = None
self.nodes = None
self.path = None<|docstring|>Initializes Tree global variables<|endoftext|>
|
30255639b1da17193eea0fb9e91760ecb7bec5272cc67f93629d5b4752401363
|
def set_layout(self):
'\n Creates the positions dictionary for nodes\n '
G = nx.Graph()
G.add_edges_from(self.edges)
self.layout = nx.spring_layout(G)
|
Creates the positions dictionary for nodes
|
networkgx/trees.py
|
set_layout
|
skyliquid22/networkgx
| 0
|
python
|
def set_layout(self):
'\n \n '
G = nx.Graph()
G.add_edges_from(self.edges)
self.layout = nx.spring_layout(G)
|
def set_layout(self):
'\n \n '
G = nx.Graph()
G.add_edges_from(self.edges)
self.layout = nx.spring_layout(G)<|docstring|>Creates the positions dictionary for nodes<|endoftext|>
|
b956ab28267c1beafd106348c01c41d68c1b7b18cfe2f0fd3d50c49cb7cc0d8e
|
def minimum_spanning_tree(self, algorithm='kruskal', draw=False):
'\n Finds the minimum spanning tree\n\n :param algorithm: (str) The algorithm used to find the minimum spanning tree. (``kruskal`` by default, ``prim``,\n ``boruvka``)\n :param draw: (bool) If True, The function will plot the minimum spanning tree. (``False`` by default)\n Returns the networx graph object\n '
tree = nx.Graph()
tree.add_edges_from(self.edges)
self.path = nx.algorithms.minimum_spanning_edges(tree, weight='corr_value', algorithm=algorithm, data=True)
min_spanning_tree = nx.Graph()
min_spanning_tree.add_edges_from(self.path)
if draw:
draw_style = {'with_labels': True, 'node_color': 'orange', 'node_size': 400, 'edge_color': 'grey', 'linewidths': 1, 'font_size': 10, 'width': 1.5}
plt.figure(figsize=(10, 6))
ax = plt.subplot(111)
plt.title('Minimum Spanning Tree', fontdict={'fontsize': 20})
nx.draw(min_spanning_tree, ax=ax, label='Minimum Spanning Tree', **draw_style)
plt.show()
return min_spanning_tree
|
Finds the minimum spanning tree
:param algorithm: (str) The algorithm used to find the minimum spanning tree. (``kruskal`` by default, ``prim``,
``boruvka``)
:param draw: (bool) If True, The function will plot the minimum spanning tree. (``False`` by default)
Returns the networx graph object
|
networkgx/trees.py
|
minimum_spanning_tree
|
skyliquid22/networkgx
| 0
|
python
|
def minimum_spanning_tree(self, algorithm='kruskal', draw=False):
'\n Finds the minimum spanning tree\n\n :param algorithm: (str) The algorithm used to find the minimum spanning tree. (``kruskal`` by default, ``prim``,\n ``boruvka``)\n :param draw: (bool) If True, The function will plot the minimum spanning tree. (``False`` by default)\n Returns the networx graph object\n '
tree = nx.Graph()
tree.add_edges_from(self.edges)
self.path = nx.algorithms.minimum_spanning_edges(tree, weight='corr_value', algorithm=algorithm, data=True)
min_spanning_tree = nx.Graph()
min_spanning_tree.add_edges_from(self.path)
if draw:
draw_style = {'with_labels': True, 'node_color': 'orange', 'node_size': 400, 'edge_color': 'grey', 'linewidths': 1, 'font_size': 10, 'width': 1.5}
plt.figure(figsize=(10, 6))
ax = plt.subplot(111)
plt.title('Minimum Spanning Tree', fontdict={'fontsize': 20})
nx.draw(min_spanning_tree, ax=ax, label='Minimum Spanning Tree', **draw_style)
plt.show()
return min_spanning_tree
|
def minimum_spanning_tree(self, algorithm='kruskal', draw=False):
'\n Finds the minimum spanning tree\n\n :param algorithm: (str) The algorithm used to find the minimum spanning tree. (``kruskal`` by default, ``prim``,\n ``boruvka``)\n :param draw: (bool) If True, The function will plot the minimum spanning tree. (``False`` by default)\n Returns the networx graph object\n '
tree = nx.Graph()
tree.add_edges_from(self.edges)
self.path = nx.algorithms.minimum_spanning_edges(tree, weight='corr_value', algorithm=algorithm, data=True)
min_spanning_tree = nx.Graph()
min_spanning_tree.add_edges_from(self.path)
if draw:
draw_style = {'with_labels': True, 'node_color': 'orange', 'node_size': 400, 'edge_color': 'grey', 'linewidths': 1, 'font_size': 10, 'width': 1.5}
plt.figure(figsize=(10, 6))
ax = plt.subplot(111)
plt.title('Minimum Spanning Tree', fontdict={'fontsize': 20})
nx.draw(min_spanning_tree, ax=ax, label='Minimum Spanning Tree', **draw_style)
plt.show()
return min_spanning_tree<|docstring|>Finds the minimum spanning tree
:param algorithm: (str) The algorithm used to find the minimum spanning tree. (``kruskal`` by default, ``prim``,
``boruvka``)
:param draw: (bool) If True, The function will plot the minimum spanning tree. (``False`` by default)
Returns the networx graph object<|endoftext|>
|
56c387f618ed8400f98c771a4385de7640eabdb576ac0f36c375af56ce86609c
|
def get_links(self):
'\n returns the links array\n '
return (self.positive_links, self.negative_links)
|
returns the links array
|
networkgx/trees.py
|
get_links
|
skyliquid22/networkgx
| 0
|
python
|
def get_links(self):
'\n \n '
return (self.positive_links, self.negative_links)
|
def get_links(self):
'\n \n '
return (self.positive_links, self.negative_links)<|docstring|>returns the links array<|endoftext|>
|
c49c3b08688dea81a781c3d632de90b7d9d11e6d532f790c80691492bf90b1dd
|
def build(self, data: pd.DataFrame) -> nx.classes.graph.Graph:
'\n The class backbone\n '
self._make_links_from_corr(data)
self.edges = self._get_edges(self.positive_links)
self.set_layout()
mst = self.minimum_spanning_tree(draw=False)
return mst
|
The class backbone
|
networkgx/trees.py
|
build
|
skyliquid22/networkgx
| 0
|
python
|
def build(self, data: pd.DataFrame) -> nx.classes.graph.Graph:
'\n \n '
self._make_links_from_corr(data)
self.edges = self._get_edges(self.positive_links)
self.set_layout()
mst = self.minimum_spanning_tree(draw=False)
return mst
|
def build(self, data: pd.DataFrame) -> nx.classes.graph.Graph:
'\n \n '
self._make_links_from_corr(data)
self.edges = self._get_edges(self.positive_links)
self.set_layout()
mst = self.minimum_spanning_tree(draw=False)
return mst<|docstring|>The class backbone<|endoftext|>
|
62e6cfdc64da6eb858cf3fe98bd4e20833120371644d8f5a3e800d6a3b15474c
|
def _make_links_from_corr(self, corr, threshold=0):
'\n TODO: make method accept multi dimensional corr\n make method split negative and positive corr\n\n Creates the links array which will reshape the correlation matrix to a DataFrame of the networks links, where\n first two columns are the source, and target nodes. and the last column is the dictionary of attributes.\n\n :param corr: (pd.DataFrame) The correlation matrix\n :param threshold: (None, float) The threshold value to return only weights above the threshold limit\n '
links = corr.stack().reset_index()
links.columns = ['src', 'trgt', 'att']
links = links.loc[(links['src'] != links['trgt'])].copy()
positive_links = links.loc[(links['att'] >= threshold)]
negative_links = links.loc[(links['att'] < threshold)]
positive_links.loc[(:, 'att')] = [{'corr_value': x} for x in positive_links.loc[(:, 'att')]]
negative_links.loc[(:, 'att')] = [{'corr_value': x} for x in negative_links.loc[(:, 'att')]]
self.positive_links = positive_links
self.negative_links = negative_links
|
TODO: make method accept multi dimensional corr
make method split negative and positive corr
Creates the links array which will reshape the correlation matrix to a DataFrame of the networks links, where
first two columns are the source, and target nodes. and the last column is the dictionary of attributes.
:param corr: (pd.DataFrame) The correlation matrix
:param threshold: (None, float) The threshold value to return only weights above the threshold limit
|
networkgx/trees.py
|
_make_links_from_corr
|
skyliquid22/networkgx
| 0
|
python
|
def _make_links_from_corr(self, corr, threshold=0):
'\n TODO: make method accept multi dimensional corr\n make method split negative and positive corr\n\n Creates the links array which will reshape the correlation matrix to a DataFrame of the networks links, where\n first two columns are the source, and target nodes. and the last column is the dictionary of attributes.\n\n :param corr: (pd.DataFrame) The correlation matrix\n :param threshold: (None, float) The threshold value to return only weights above the threshold limit\n '
links = corr.stack().reset_index()
links.columns = ['src', 'trgt', 'att']
links = links.loc[(links['src'] != links['trgt'])].copy()
positive_links = links.loc[(links['att'] >= threshold)]
negative_links = links.loc[(links['att'] < threshold)]
positive_links.loc[(:, 'att')] = [{'corr_value': x} for x in positive_links.loc[(:, 'att')]]
negative_links.loc[(:, 'att')] = [{'corr_value': x} for x in negative_links.loc[(:, 'att')]]
self.positive_links = positive_links
self.negative_links = negative_links
|
def _make_links_from_corr(self, corr, threshold=0):
'\n TODO: make method accept multi dimensional corr\n make method split negative and positive corr\n\n Creates the links array which will reshape the correlation matrix to a DataFrame of the networks links, where\n first two columns are the source, and target nodes. and the last column is the dictionary of attributes.\n\n :param corr: (pd.DataFrame) The correlation matrix\n :param threshold: (None, float) The threshold value to return only weights above the threshold limit\n '
links = corr.stack().reset_index()
links.columns = ['src', 'trgt', 'att']
links = links.loc[(links['src'] != links['trgt'])].copy()
positive_links = links.loc[(links['att'] >= threshold)]
negative_links = links.loc[(links['att'] < threshold)]
positive_links.loc[(:, 'att')] = [{'corr_value': x} for x in positive_links.loc[(:, 'att')]]
negative_links.loc[(:, 'att')] = [{'corr_value': x} for x in negative_links.loc[(:, 'att')]]
self.positive_links = positive_links
self.negative_links = negative_links<|docstring|>TODO: make method accept multi dimensional corr
make method split negative and positive corr
Creates the links array which will reshape the correlation matrix to a DataFrame of the networks links, where
first two columns are the source, and target nodes. and the last column is the dictionary of attributes.
:param corr: (pd.DataFrame) The correlation matrix
:param threshold: (None, float) The threshold value to return only weights above the threshold limit<|endoftext|>
|
21a4a570e5cdc03cb8fa5bedf4a69169fbed452c03ace2959c371ca551a3d385
|
@staticmethod
def _get_edges(links, filtered=True, sort=True):
'\n TODO: add support for links with multivariate random variables.\n Returns the edges for the graphs from the links array.\n '
edges = list(zip(links.iloc[(:, 0)], links.iloc[(:, 1)], links.iloc[(:, 2)]))
if filtered:
seen = set()
edges = [(a, b, c) for (a, b, c) in edges if (not (((a, b) in seen) or seen.add((a, b)) or seen.add((b, a))))]
if sort:
edges = sorted(edges, key=(lambda x: x[2]['corr_value']))
return edges
|
TODO: add support for links with multivariate random variables.
Returns the edges for the graphs from the links array.
|
networkgx/trees.py
|
_get_edges
|
skyliquid22/networkgx
| 0
|
python
|
@staticmethod
def _get_edges(links, filtered=True, sort=True):
'\n TODO: add support for links with multivariate random variables.\n Returns the edges for the graphs from the links array.\n '
edges = list(zip(links.iloc[(:, 0)], links.iloc[(:, 1)], links.iloc[(:, 2)]))
if filtered:
seen = set()
edges = [(a, b, c) for (a, b, c) in edges if (not (((a, b) in seen) or seen.add((a, b)) or seen.add((b, a))))]
if sort:
edges = sorted(edges, key=(lambda x: x[2]['corr_value']))
return edges
|
@staticmethod
def _get_edges(links, filtered=True, sort=True):
'\n TODO: add support for links with multivariate random variables.\n Returns the edges for the graphs from the links array.\n '
edges = list(zip(links.iloc[(:, 0)], links.iloc[(:, 1)], links.iloc[(:, 2)]))
if filtered:
seen = set()
edges = [(a, b, c) for (a, b, c) in edges if (not (((a, b) in seen) or seen.add((a, b)) or seen.add((b, a))))]
if sort:
edges = sorted(edges, key=(lambda x: x[2]['corr_value']))
return edges<|docstring|>TODO: add support for links with multivariate random variables.
Returns the edges for the graphs from the links array.<|endoftext|>
|
d60ec12087769548ff912e9ba232d1d65f31fb4a83a7245a0c07d339d6de22f3
|
def lancer(self, action_precdente, palifico=False) -> Action:
'To do'
self.annonce_challenge(action_precdente)
return self
|
To do
|
src/dudo.py
|
lancer
|
cmnemoi/Notre_Super_Perudo
| 0
|
python
|
def lancer(self, action_precdente, palifico=False) -> Action:
self.annonce_challenge(action_precdente)
return self
|
def lancer(self, action_precdente, palifico=False) -> Action:
self.annonce_challenge(action_precdente)
return self<|docstring|>To do<|endoftext|>
|
b701f53f03feef843a6dab849b340754965fadf47b5bcf71af0d7dd5c7160d26
|
def main():
'\n Call this function as an entrypoint.\n\n Uncaught exception will be caught here as a critical message. Since it may\n left the project in a broken middle state.\n '
try:
cli()
except Exception as e:
logger.critical('Uncaught exception!')
logger.critical(e, exc_info=True)
sys.exit(3)
|
Call this function as an entrypoint.
Uncaught exception will be caught here as a critical message. Since it may
left the project in a broken middle state.
|
cfpm/console/__init__.py
|
main
|
efueger/cfpm
| 1
|
python
|
def main():
'\n Call this function as an entrypoint.\n\n Uncaught exception will be caught here as a critical message. Since it may\n left the project in a broken middle state.\n '
try:
cli()
except Exception as e:
logger.critical('Uncaught exception!')
logger.critical(e, exc_info=True)
sys.exit(3)
|
def main():
'\n Call this function as an entrypoint.\n\n Uncaught exception will be caught here as a critical message. Since it may\n left the project in a broken middle state.\n '
try:
cli()
except Exception as e:
logger.critical('Uncaught exception!')
logger.critical(e, exc_info=True)
sys.exit(3)<|docstring|>Call this function as an entrypoint.
Uncaught exception will be caught here as a critical message. Since it may
left the project in a broken middle state.<|endoftext|>
|
2ceda2d5f15591dfeba94a5179b59c815ed4399c22009952d599b8c4aa5dc1ef
|
def decimate(factor):
'\n Patch to reduce number of time steps in simulation.\n\n Ideally instead there should be a config option to change the time step,\n and that supports time steps larger than the observation intervals.\n\n Instead, this works by downsampling as soon as a track is interpolated,\n ie. thinning out the timeseries that will be input for simulation.\n\n Incidentally, for large factors the output plot contains the aesthetic\n effect of superimposing a sequence of snapshots of the cyclone, revealing\n wind model internal structure that is not apparent in the full aggregate.\n '
raw_interpolate = Evaluate.interpolateTracks.interpolate
def wrapper(*args, **kwargs):
result = raw_interpolate(*args, **kwargs)
result.data = result.data[::factor]
return result
return patch('Evaluate.interpolateTracks.interpolate', wrapper)
|
Patch to reduce number of time steps in simulation.
Ideally instead there should be a config option to change the time step,
and that supports time steps larger than the observation intervals.
Instead, this works by downsampling as soon as a track is interpolated,
ie. thinning out the timeseries that will be input for simulation.
Incidentally, for large factors the output plot contains the aesthetic
effect of superimposing a sequence of snapshots of the cyclone, revealing
wind model internal structure that is not apparent in the full aggregate.
|
tests/test_system.py
|
decimate
|
metocean/tcrm
| 0
|
python
|
def decimate(factor):
'\n Patch to reduce number of time steps in simulation.\n\n Ideally instead there should be a config option to change the time step,\n and that supports time steps larger than the observation intervals.\n\n Instead, this works by downsampling as soon as a track is interpolated,\n ie. thinning out the timeseries that will be input for simulation.\n\n Incidentally, for large factors the output plot contains the aesthetic\n effect of superimposing a sequence of snapshots of the cyclone, revealing\n wind model internal structure that is not apparent in the full aggregate.\n '
raw_interpolate = Evaluate.interpolateTracks.interpolate
def wrapper(*args, **kwargs):
result = raw_interpolate(*args, **kwargs)
result.data = result.data[::factor]
return result
return patch('Evaluate.interpolateTracks.interpolate', wrapper)
|
def decimate(factor):
'\n Patch to reduce number of time steps in simulation.\n\n Ideally instead there should be a config option to change the time step,\n and that supports time steps larger than the observation intervals.\n\n Instead, this works by downsampling as soon as a track is interpolated,\n ie. thinning out the timeseries that will be input for simulation.\n\n Incidentally, for large factors the output plot contains the aesthetic\n effect of superimposing a sequence of snapshots of the cyclone, revealing\n wind model internal structure that is not apparent in the full aggregate.\n '
raw_interpolate = Evaluate.interpolateTracks.interpolate
def wrapper(*args, **kwargs):
result = raw_interpolate(*args, **kwargs)
result.data = result.data[::factor]
return result
return patch('Evaluate.interpolateTracks.interpolate', wrapper)<|docstring|>Patch to reduce number of time steps in simulation.
Ideally instead there should be a config option to change the time step,
and that supports time steps larger than the observation intervals.
Instead, this works by downsampling as soon as a track is interpolated,
ie. thinning out the timeseries that will be input for simulation.
Incidentally, for large factors the output plot contains the aesthetic
effect of superimposing a sequence of snapshots of the cyclone, revealing
wind model internal structure that is not apparent in the full aggregate.<|endoftext|>
|
503eb691f5aa157d666c340f12fb6b1b7c15a41cc02f0bcba9993802790176d8
|
def printSequenceStats(fileName, sequenceName, charOccurrenceMap, totalCharCount):
'\n Print details about a sequence to stdout.\n Called from inside parseFile().\n Keyword arguments:\n sequenceName: The name of the sequence to print\n charOccurrenceMap: A dict-like object that contains a char -->\n number of occurrences mapping\n totalCharCount: The overall character count of the sequence\n '
relativeFrequencies = []
for char in sorted(charOccurrenceMap.keys()):
charCount = charOccurrenceMap[char]
relativeFrequency = ((charCount * 1.0) / totalCharCount)
relativeFrequencies.append(relativeFrequency)
print('{}'.format(relativeFrequency))
|
Print details about a sequence to stdout.
Called from inside parseFile().
Keyword arguments:
sequenceName: The name of the sequence to print
charOccurrenceMap: A dict-like object that contains a char -->
number of occurrences mapping
totalCharCount: The overall character count of the sequence
|
bin/count_fasta_base.py
|
printSequenceStats
|
fuxialexander/marvel
| 8
|
python
|
def printSequenceStats(fileName, sequenceName, charOccurrenceMap, totalCharCount):
'\n Print details about a sequence to stdout.\n Called from inside parseFile().\n Keyword arguments:\n sequenceName: The name of the sequence to print\n charOccurrenceMap: A dict-like object that contains a char -->\n number of occurrences mapping\n totalCharCount: The overall character count of the sequence\n '
relativeFrequencies = []
for char in sorted(charOccurrenceMap.keys()):
charCount = charOccurrenceMap[char]
relativeFrequency = ((charCount * 1.0) / totalCharCount)
relativeFrequencies.append(relativeFrequency)
print('{}'.format(relativeFrequency))
|
def printSequenceStats(fileName, sequenceName, charOccurrenceMap, totalCharCount):
'\n Print details about a sequence to stdout.\n Called from inside parseFile().\n Keyword arguments:\n sequenceName: The name of the sequence to print\n charOccurrenceMap: A dict-like object that contains a char -->\n number of occurrences mapping\n totalCharCount: The overall character count of the sequence\n '
relativeFrequencies = []
for char in sorted(charOccurrenceMap.keys()):
charCount = charOccurrenceMap[char]
relativeFrequency = ((charCount * 1.0) / totalCharCount)
relativeFrequencies.append(relativeFrequency)
print('{}'.format(relativeFrequency))<|docstring|>Print details about a sequence to stdout.
Called from inside parseFile().
Keyword arguments:
sequenceName: The name of the sequence to print
charOccurrenceMap: A dict-like object that contains a char -->
number of occurrences mapping
totalCharCount: The overall character count of the sequence<|endoftext|>
|
1f4c6c1b5e90971b589eb3825200a4c76246735e57cc5282aad23c943661d6db
|
def parseFile(filename, caseSensitive=False, charWhitelist=None):
'\n Parse a FASTA fil and call printRe\n '
sequenceName = None
charOccurrenceMap = Counter()
charCount = 0
previousLineWasComment = False
openFunc = (gzip.open if filename.endswith('.gz') else open)
with openFunc(filename, 'r') as infile:
for line in infile:
line = line.strip()
if (line.startswith('>') or line.startswith(';')):
if (sequenceName is not None):
printSequenceStats(filename, sequenceName, charOccurrenceMap, charCount)
charOccurrenceMap = Counter()
charCount = 0
if previousLineWasComment:
sequenceName += (' ' + line[1:].strip())
else:
sequenceName = line[1:].strip()
previousLineWasComment = True
else:
previousLineWasComment = False
for char in line:
if ((charWhitelist is not None) and (not (char in charWhitelist))):
continue
charCount += 1
char = (char if caseSensitive else char.upper())
charOccurrenceMap[char] += 1
if (sequenceName is not None):
printSequenceStats(filename, sequenceName, charOccurrenceMap, charCount)
|
Parse a FASTA fil and call printRe
|
bin/count_fasta_base.py
|
parseFile
|
fuxialexander/marvel
| 8
|
python
|
def parseFile(filename, caseSensitive=False, charWhitelist=None):
'\n \n '
sequenceName = None
charOccurrenceMap = Counter()
charCount = 0
previousLineWasComment = False
openFunc = (gzip.open if filename.endswith('.gz') else open)
with openFunc(filename, 'r') as infile:
for line in infile:
line = line.strip()
if (line.startswith('>') or line.startswith(';')):
if (sequenceName is not None):
printSequenceStats(filename, sequenceName, charOccurrenceMap, charCount)
charOccurrenceMap = Counter()
charCount = 0
if previousLineWasComment:
sequenceName += (' ' + line[1:].strip())
else:
sequenceName = line[1:].strip()
previousLineWasComment = True
else:
previousLineWasComment = False
for char in line:
if ((charWhitelist is not None) and (not (char in charWhitelist))):
continue
charCount += 1
char = (char if caseSensitive else char.upper())
charOccurrenceMap[char] += 1
if (sequenceName is not None):
printSequenceStats(filename, sequenceName, charOccurrenceMap, charCount)
|
def parseFile(filename, caseSensitive=False, charWhitelist=None):
'\n \n '
sequenceName = None
charOccurrenceMap = Counter()
charCount = 0
previousLineWasComment = False
openFunc = (gzip.open if filename.endswith('.gz') else open)
with openFunc(filename, 'r') as infile:
for line in infile:
line = line.strip()
if (line.startswith('>') or line.startswith(';')):
if (sequenceName is not None):
printSequenceStats(filename, sequenceName, charOccurrenceMap, charCount)
charOccurrenceMap = Counter()
charCount = 0
if previousLineWasComment:
sequenceName += (' ' + line[1:].strip())
else:
sequenceName = line[1:].strip()
previousLineWasComment = True
else:
previousLineWasComment = False
for char in line:
if ((charWhitelist is not None) and (not (char in charWhitelist))):
continue
charCount += 1
char = (char if caseSensitive else char.upper())
charOccurrenceMap[char] += 1
if (sequenceName is not None):
printSequenceStats(filename, sequenceName, charOccurrenceMap, charCount)<|docstring|>Parse a FASTA fil and call printRe<|endoftext|>
|
cbc1a9ea53c5837a753ac513c3c2b1b37e1b58f6d31bcafbc3bcc4952fcc061f
|
@staticmethod
def find(serial_numbers=None):
'Find all the serial ports that are associated with debuggers.\n\n Parameters\n ----------\n serial_numbers: list of str, or None\n If provided, will only match the serial numbers that are contained\n in the provided list.\n\n Returns\n -------\n devices: list of serial devices\n List of serial devices\n\n Note\n ----\n If a list of serial numbers is not provided, then this function may\n match Teensy 3.1/3.2 microcontrollers that are connected to the\n computer but that may not be associated with the TeensyToAny boards.\n\n '
pairs = TeensyToAny._device_serial_number_pairs(serial_numbers=serial_numbers)
(devices, _) = zip(*pairs)
return devices
|
Find all the serial ports that are associated with debuggers.
Parameters
----------
serial_numbers: list of str, or None
If provided, will only match the serial numbers that are contained
in the provided list.
Returns
-------
devices: list of serial devices
List of serial devices
Note
----
If a list of serial numbers is not provided, then this function may
match Teensy 3.1/3.2 microcontrollers that are connected to the
computer but that may not be associated with the TeensyToAny boards.
|
teensytoany/teensytoany.py
|
find
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
@staticmethod
def find(serial_numbers=None):
'Find all the serial ports that are associated with debuggers.\n\n Parameters\n ----------\n serial_numbers: list of str, or None\n If provided, will only match the serial numbers that are contained\n in the provided list.\n\n Returns\n -------\n devices: list of serial devices\n List of serial devices\n\n Note\n ----\n If a list of serial numbers is not provided, then this function may\n match Teensy 3.1/3.2 microcontrollers that are connected to the\n computer but that may not be associated with the TeensyToAny boards.\n\n '
pairs = TeensyToAny._device_serial_number_pairs(serial_numbers=serial_numbers)
(devices, _) = zip(*pairs)
return devices
|
@staticmethod
def find(serial_numbers=None):
'Find all the serial ports that are associated with debuggers.\n\n Parameters\n ----------\n serial_numbers: list of str, or None\n If provided, will only match the serial numbers that are contained\n in the provided list.\n\n Returns\n -------\n devices: list of serial devices\n List of serial devices\n\n Note\n ----\n If a list of serial numbers is not provided, then this function may\n match Teensy 3.1/3.2 microcontrollers that are connected to the\n computer but that may not be associated with the TeensyToAny boards.\n\n '
pairs = TeensyToAny._device_serial_number_pairs(serial_numbers=serial_numbers)
(devices, _) = zip(*pairs)
return devices<|docstring|>Find all the serial ports that are associated with debuggers.
Parameters
----------
serial_numbers: list of str, or None
If provided, will only match the serial numbers that are contained
in the provided list.
Returns
-------
devices: list of serial devices
List of serial devices
Note
----
If a list of serial numbers is not provided, then this function may
match Teensy 3.1/3.2 microcontrollers that are connected to the
computer but that may not be associated with the TeensyToAny boards.<|endoftext|>
|
9718446c12cc855d49ccf0153b4e161d29db1102a81512fddc26f35f7f70f074
|
@staticmethod
def list_all_serial_numbers(serial_numbers=None):
'Find all the currently connected TeensyToAny serial numbers.\n\n Parameters\n ----------\n serial_numbers: list of str, or None\n If provided, will only match the serial numbers that are contained\n in the provided list.\n\n Returns\n -------\n serial_numbers: list of serial numbers\n List of connected serial numbers.\n\n Note\n ----\n If a list of serial numbers is not provided, then this function may\n match Teensy 3.1/3.2 microcontrollers that are connected to the\n computer but that may not be associated with the TeensyToAny boards.\n\n '
pairs = TeensyToAny._device_serial_number_pairs(serial_numbers=serial_numbers)
(_, serial_numbers) = zip(*pairs)
return serial_numbers
|
Find all the currently connected TeensyToAny serial numbers.
Parameters
----------
serial_numbers: list of str, or None
If provided, will only match the serial numbers that are contained
in the provided list.
Returns
-------
serial_numbers: list of serial numbers
List of connected serial numbers.
Note
----
If a list of serial numbers is not provided, then this function may
match Teensy 3.1/3.2 microcontrollers that are connected to the
computer but that may not be associated with the TeensyToAny boards.
|
teensytoany/teensytoany.py
|
list_all_serial_numbers
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
@staticmethod
def list_all_serial_numbers(serial_numbers=None):
'Find all the currently connected TeensyToAny serial numbers.\n\n Parameters\n ----------\n serial_numbers: list of str, or None\n If provided, will only match the serial numbers that are contained\n in the provided list.\n\n Returns\n -------\n serial_numbers: list of serial numbers\n List of connected serial numbers.\n\n Note\n ----\n If a list of serial numbers is not provided, then this function may\n match Teensy 3.1/3.2 microcontrollers that are connected to the\n computer but that may not be associated with the TeensyToAny boards.\n\n '
pairs = TeensyToAny._device_serial_number_pairs(serial_numbers=serial_numbers)
(_, serial_numbers) = zip(*pairs)
return serial_numbers
|
@staticmethod
def list_all_serial_numbers(serial_numbers=None):
'Find all the currently connected TeensyToAny serial numbers.\n\n Parameters\n ----------\n serial_numbers: list of str, or None\n If provided, will only match the serial numbers that are contained\n in the provided list.\n\n Returns\n -------\n serial_numbers: list of serial numbers\n List of connected serial numbers.\n\n Note\n ----\n If a list of serial numbers is not provided, then this function may\n match Teensy 3.1/3.2 microcontrollers that are connected to the\n computer but that may not be associated with the TeensyToAny boards.\n\n '
pairs = TeensyToAny._device_serial_number_pairs(serial_numbers=serial_numbers)
(_, serial_numbers) = zip(*pairs)
return serial_numbers<|docstring|>Find all the currently connected TeensyToAny serial numbers.
Parameters
----------
serial_numbers: list of str, or None
If provided, will only match the serial numbers that are contained
in the provided list.
Returns
-------
serial_numbers: list of serial numbers
List of connected serial numbers.
Note
----
If a list of serial numbers is not provided, then this function may
match Teensy 3.1/3.2 microcontrollers that are connected to the
computer but that may not be associated with the TeensyToAny boards.<|endoftext|>
|
789c4e72f3b8931f6668b90d01820e2b65d3ca5d188a6f4a55c95f545c18ff49
|
def __init__(self, serial_number=None, *, baudrate=115200, timeout=0.1, open=True):
'A class to control the TeensyToAny Debugger.\n\n Parameters\n ----------\n serial_number: optional\n If provided, will attempt to open the specified serial number\n\n '
self._requested_serial_number = serial_number
self._baudrate = baudrate
self._timeout = timeout
self._serial = None
if open:
self.open()
|
A class to control the TeensyToAny Debugger.
Parameters
----------
serial_number: optional
If provided, will attempt to open the specified serial number
|
teensytoany/teensytoany.py
|
__init__
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def __init__(self, serial_number=None, *, baudrate=115200, timeout=0.1, open=True):
'A class to control the TeensyToAny Debugger.\n\n Parameters\n ----------\n serial_number: optional\n If provided, will attempt to open the specified serial number\n\n '
self._requested_serial_number = serial_number
self._baudrate = baudrate
self._timeout = timeout
self._serial = None
if open:
self.open()
|
def __init__(self, serial_number=None, *, baudrate=115200, timeout=0.1, open=True):
'A class to control the TeensyToAny Debugger.\n\n Parameters\n ----------\n serial_number: optional\n If provided, will attempt to open the specified serial number\n\n '
self._requested_serial_number = serial_number
self._baudrate = baudrate
self._timeout = timeout
self._serial = None
if open:
self.open()<|docstring|>A class to control the TeensyToAny Debugger.
Parameters
----------
serial_number: optional
If provided, will attempt to open the specified serial number<|endoftext|>
|
3c774e3486c3440fae4dd4346475a522f2410d971e8fea7963c11b563038054c
|
def _write(self, data) -> None:
"Write data to the port.\n\n If it is a string, encode it as 'utf-8'.\n "
if (self._serial is None):
raise RuntimeError('Device must be opened first')
if isinstance(data, str):
data = (data + '\n').encode('utf-8')
self._serial.write(data)
|
Write data to the port.
If it is a string, encode it as 'utf-8'.
|
teensytoany/teensytoany.py
|
_write
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def _write(self, data) -> None:
"Write data to the port.\n\n If it is a string, encode it as 'utf-8'.\n "
if (self._serial is None):
raise RuntimeError('Device must be opened first')
if isinstance(data, str):
data = (data + '\n').encode('utf-8')
self._serial.write(data)
|
def _write(self, data) -> None:
"Write data to the port.\n\n If it is a string, encode it as 'utf-8'.\n "
if (self._serial is None):
raise RuntimeError('Device must be opened first')
if isinstance(data, str):
data = (data + '\n').encode('utf-8')
self._serial.write(data)<|docstring|>Write data to the port.
If it is a string, encode it as 'utf-8'.<|endoftext|>
|
55d42c947103e4c61b59f542a16421a726c33a26b3d40d89dea756c624604148
|
def _read(self, *, size=1024, decode=True) -> str:
'Read data from the serial port.\n\n Returns\n -------\n data: bytes or string\n string of data read.\n\n '
if (self._serial is None):
raise RuntimeError('Device must be opened first')
data = self._serial.read_until(LF, size=size)
if decode:
return data.decode()
else:
return data
|
Read data from the serial port.
Returns
-------
data: bytes or string
string of data read.
|
teensytoany/teensytoany.py
|
_read
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def _read(self, *, size=1024, decode=True) -> str:
'Read data from the serial port.\n\n Returns\n -------\n data: bytes or string\n string of data read.\n\n '
if (self._serial is None):
raise RuntimeError('Device must be opened first')
data = self._serial.read_until(LF, size=size)
if decode:
return data.decode()
else:
return data
|
def _read(self, *, size=1024, decode=True) -> str:
'Read data from the serial port.\n\n Returns\n -------\n data: bytes or string\n string of data read.\n\n '
if (self._serial is None):
raise RuntimeError('Device must be opened first')
data = self._serial.read_until(LF, size=size)
if decode:
return data.decode()
else:
return data<|docstring|>Read data from the serial port.
Returns
-------
data: bytes or string
string of data read.<|endoftext|>
|
b3b756b6407c8ae2e50d0b0ca7e35b9e539f448127c1eb4eb6864e1284174f9d
|
def gpio_digital_write(self, pin, value):
'Call the ardunio DigitalWrite function.\n\n\n Parameters\n ----------\n pin: int\n Pin number to control.\n value: 0, 1, "HIGH", "LOW"\n Value to assign to the pin\n\n '
self._ask(f'gpio_digital_write {pin} {value}')
|
Call the ardunio DigitalWrite function.
Parameters
----------
pin: int
Pin number to control.
value: 0, 1, "HIGH", "LOW"
Value to assign to the pin
|
teensytoany/teensytoany.py
|
gpio_digital_write
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def gpio_digital_write(self, pin, value):
'Call the ardunio DigitalWrite function.\n\n\n Parameters\n ----------\n pin: int\n Pin number to control.\n value: 0, 1, "HIGH", "LOW"\n Value to assign to the pin\n\n '
self._ask(f'gpio_digital_write {pin} {value}')
|
def gpio_digital_write(self, pin, value):
'Call the ardunio DigitalWrite function.\n\n\n Parameters\n ----------\n pin: int\n Pin number to control.\n value: 0, 1, "HIGH", "LOW"\n Value to assign to the pin\n\n '
self._ask(f'gpio_digital_write {pin} {value}')<|docstring|>Call the ardunio DigitalWrite function.
Parameters
----------
pin: int
Pin number to control.
value: 0, 1, "HIGH", "LOW"
Value to assign to the pin<|endoftext|>
|
a94f67f3492dccfa129bd5d99c102982e79bbc30f18d15a55a36c7eb9b6cc062
|
def gpio_pin_mode(self, pin, mode):
'Call the arduino PinMode function.\n\n Parameters\n ----------\n pin: int\n Pin number to control.\n mode: 0, 1, "INPUT", "OUTPUT"\n Mode which to set the pin to.\n '
self._ask(f'gpio_pin_mode {pin} {mode}')
|
Call the arduino PinMode function.
Parameters
----------
pin: int
Pin number to control.
mode: 0, 1, "INPUT", "OUTPUT"
Mode which to set the pin to.
|
teensytoany/teensytoany.py
|
gpio_pin_mode
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def gpio_pin_mode(self, pin, mode):
'Call the arduino PinMode function.\n\n Parameters\n ----------\n pin: int\n Pin number to control.\n mode: 0, 1, "INPUT", "OUTPUT"\n Mode which to set the pin to.\n '
self._ask(f'gpio_pin_mode {pin} {mode}')
|
def gpio_pin_mode(self, pin, mode):
'Call the arduino PinMode function.\n\n Parameters\n ----------\n pin: int\n Pin number to control.\n mode: 0, 1, "INPUT", "OUTPUT"\n Mode which to set the pin to.\n '
self._ask(f'gpio_pin_mode {pin} {mode}')<|docstring|>Call the arduino PinMode function.
Parameters
----------
pin: int
Pin number to control.
mode: 0, 1, "INPUT", "OUTPUT"
Mode which to set the pin to.<|endoftext|>
|
d90eb314ec15d2f0215a04c3a3b549229c601eea2e563c97b110b1ad2cc40f62
|
def gpio_digital_read(self, pin):
'Call the arduino DigitalRead function.\n\n Parameters\n ----------\n pin: int\n Pin number to read.\n\n Returns\n -------\n value: int, 0, 1\n Read value.\n\n '
returned = self._ask(f'gpio_digital_read {pin}')
return bool(int(returned, base=0))
|
Call the arduino DigitalRead function.
Parameters
----------
pin: int
Pin number to read.
Returns
-------
value: int, 0, 1
Read value.
|
teensytoany/teensytoany.py
|
gpio_digital_read
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def gpio_digital_read(self, pin):
'Call the arduino DigitalRead function.\n\n Parameters\n ----------\n pin: int\n Pin number to read.\n\n Returns\n -------\n value: int, 0, 1\n Read value.\n\n '
returned = self._ask(f'gpio_digital_read {pin}')
return bool(int(returned, base=0))
|
def gpio_digital_read(self, pin):
'Call the arduino DigitalRead function.\n\n Parameters\n ----------\n pin: int\n Pin number to read.\n\n Returns\n -------\n value: int, 0, 1\n Read value.\n\n '
returned = self._ask(f'gpio_digital_read {pin}')
return bool(int(returned, base=0))<|docstring|>Call the arduino DigitalRead function.
Parameters
----------
pin: int
Pin number to read.
Returns
-------
value: int, 0, 1
Read value.<|endoftext|>
|
1bf413e9882db9c6da667ff3846ef13d265564953f8937c46744026eb2d931b7
|
def spi_settings(self, frequency: int=1000000, bit_order: str='MSBFIRST', data_mode: str='SPI_MODE0'):
"\n\n Parameters\n ----------\n bit_order: 'MSBFIRST' or 'LSBFIRST'\n data_mode: 'SPI_MODE0', 'SPI_MODE1', 'SPI_MODE2', or 'SPI_MODE3'\n\n References\n ----------\n 1. https://www.pjrc.com/teensy/td_libs_SPI.html\n 2. https://www.arduino.cc/en/Reference/SPISetDataMode\n\n "
return self._ask(f'spi_settings {frequency} {bit_order} {data_mode}')
|
Parameters
----------
bit_order: 'MSBFIRST' or 'LSBFIRST'
data_mode: 'SPI_MODE0', 'SPI_MODE1', 'SPI_MODE2', or 'SPI_MODE3'
References
----------
1. https://www.pjrc.com/teensy/td_libs_SPI.html
2. https://www.arduino.cc/en/Reference/SPISetDataMode
|
teensytoany/teensytoany.py
|
spi_settings
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def spi_settings(self, frequency: int=1000000, bit_order: str='MSBFIRST', data_mode: str='SPI_MODE0'):
"\n\n Parameters\n ----------\n bit_order: 'MSBFIRST' or 'LSBFIRST'\n data_mode: 'SPI_MODE0', 'SPI_MODE1', 'SPI_MODE2', or 'SPI_MODE3'\n\n References\n ----------\n 1. https://www.pjrc.com/teensy/td_libs_SPI.html\n 2. https://www.arduino.cc/en/Reference/SPISetDataMode\n\n "
return self._ask(f'spi_settings {frequency} {bit_order} {data_mode}')
|
def spi_settings(self, frequency: int=1000000, bit_order: str='MSBFIRST', data_mode: str='SPI_MODE0'):
"\n\n Parameters\n ----------\n bit_order: 'MSBFIRST' or 'LSBFIRST'\n data_mode: 'SPI_MODE0', 'SPI_MODE1', 'SPI_MODE2', or 'SPI_MODE3'\n\n References\n ----------\n 1. https://www.pjrc.com/teensy/td_libs_SPI.html\n 2. https://www.arduino.cc/en/Reference/SPISetDataMode\n\n "
return self._ask(f'spi_settings {frequency} {bit_order} {data_mode}')<|docstring|>Parameters
----------
bit_order: 'MSBFIRST' or 'LSBFIRST'
data_mode: 'SPI_MODE0', 'SPI_MODE1', 'SPI_MODE2', or 'SPI_MODE3'
References
----------
1. https://www.pjrc.com/teensy/td_libs_SPI.html
2. https://www.arduino.cc/en/Reference/SPISetDataMode<|endoftext|>
|
fae602e0707e409ab086bb79835ca858bf3cfd0c02e9728d826a68c0dc9d0f4c
|
def spi_read_byte(self, data):
'Read a byte of data over SPI.\n\n Parameters\n ----------\n data: int\n Command or register address to send before reading.\n\n Returns\n -------\n value: int, (0-255)\n Read value.\n\n '
value = self._ask(f'spi_read_byte {data}')
return int(value, base=0)
|
Read a byte of data over SPI.
Parameters
----------
data: int
Command or register address to send before reading.
Returns
-------
value: int, (0-255)
Read value.
|
teensytoany/teensytoany.py
|
spi_read_byte
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def spi_read_byte(self, data):
'Read a byte of data over SPI.\n\n Parameters\n ----------\n data: int\n Command or register address to send before reading.\n\n Returns\n -------\n value: int, (0-255)\n Read value.\n\n '
value = self._ask(f'spi_read_byte {data}')
return int(value, base=0)
|
def spi_read_byte(self, data):
'Read a byte of data over SPI.\n\n Parameters\n ----------\n data: int\n Command or register address to send before reading.\n\n Returns\n -------\n value: int, (0-255)\n Read value.\n\n '
value = self._ask(f'spi_read_byte {data}')
return int(value, base=0)<|docstring|>Read a byte of data over SPI.
Parameters
----------
data: int
Command or register address to send before reading.
Returns
-------
value: int, (0-255)
Read value.<|endoftext|>
|
6d3eb80e6075d6c684bdeb05c7c0af2e4850037eec9f71458aec6e15febd9f0a
|
def analog_read(self, pin: int):
'Call the arduino analogRead function.\n\n Parameters\n ----------\n pin: int\n Pin number to read.\n\n Returns\n -------\n value: int, (0-255)\n Read value.\n\n '
returned = self._ask(f'analog_read {pin}')
return int(returned, base=0)
|
Call the arduino analogRead function.
Parameters
----------
pin: int
Pin number to read.
Returns
-------
value: int, (0-255)
Read value.
|
teensytoany/teensytoany.py
|
analog_read
|
vetonsaliu8/python-teensytoany
| 0
|
python
|
def analog_read(self, pin: int):
'Call the arduino analogRead function.\n\n Parameters\n ----------\n pin: int\n Pin number to read.\n\n Returns\n -------\n value: int, (0-255)\n Read value.\n\n '
returned = self._ask(f'analog_read {pin}')
return int(returned, base=0)
|
def analog_read(self, pin: int):
'Call the arduino analogRead function.\n\n Parameters\n ----------\n pin: int\n Pin number to read.\n\n Returns\n -------\n value: int, (0-255)\n Read value.\n\n '
returned = self._ask(f'analog_read {pin}')
return int(returned, base=0)<|docstring|>Call the arduino analogRead function.
Parameters
----------
pin: int
Pin number to read.
Returns
-------
value: int, (0-255)
Read value.<|endoftext|>
|
9bac837f1ea098ffbb8c35ae39dcdd6e4dfb3081dcb37b335c9b3ac7b190890b
|
def build_urls(dates, *, daily=False):
'Construct AirNow file URLs for `dates`.\n\n Returns\n -------\n urls, fnames : pandas.Series\n '
dates = pd.DatetimeIndex(dates)
if daily:
dates = dates.floor('D').unique()
else:
dates = dates.floor('H').unique()
urls = []
fnames = []
print('Building AIRNOW URLs...')
base_url = 'https://s3-us-west-1.amazonaws.com//files.airnowtech.org/airnow/'
for dt in dates:
if daily:
fname = 'daily_data.dat'
else:
fname = dt.strftime('HourlyData_%Y%m%d%H.dat')
url = ((base_url + dt.strftime('%Y/%Y%m%d/')) + fname)
urls.append(url)
fnames.append(fname)
urls = pd.Series(urls, index=None)
fnames = pd.Series(fnames, index=None)
return (urls, fnames)
|
Construct AirNow file URLs for `dates`.
Returns
-------
urls, fnames : pandas.Series
|
monetio/obs/airnow.py
|
build_urls
|
mlirenzhenmayi/monetio
| 1
|
python
|
def build_urls(dates, *, daily=False):
'Construct AirNow file URLs for `dates`.\n\n Returns\n -------\n urls, fnames : pandas.Series\n '
dates = pd.DatetimeIndex(dates)
if daily:
dates = dates.floor('D').unique()
else:
dates = dates.floor('H').unique()
urls = []
fnames = []
print('Building AIRNOW URLs...')
base_url = 'https://s3-us-west-1.amazonaws.com//files.airnowtech.org/airnow/'
for dt in dates:
if daily:
fname = 'daily_data.dat'
else:
fname = dt.strftime('HourlyData_%Y%m%d%H.dat')
url = ((base_url + dt.strftime('%Y/%Y%m%d/')) + fname)
urls.append(url)
fnames.append(fname)
urls = pd.Series(urls, index=None)
fnames = pd.Series(fnames, index=None)
return (urls, fnames)
|
def build_urls(dates, *, daily=False):
'Construct AirNow file URLs for `dates`.\n\n Returns\n -------\n urls, fnames : pandas.Series\n '
dates = pd.DatetimeIndex(dates)
if daily:
dates = dates.floor('D').unique()
else:
dates = dates.floor('H').unique()
urls = []
fnames = []
print('Building AIRNOW URLs...')
base_url = 'https://s3-us-west-1.amazonaws.com//files.airnowtech.org/airnow/'
for dt in dates:
if daily:
fname = 'daily_data.dat'
else:
fname = dt.strftime('HourlyData_%Y%m%d%H.dat')
url = ((base_url + dt.strftime('%Y/%Y%m%d/')) + fname)
urls.append(url)
fnames.append(fname)
urls = pd.Series(urls, index=None)
fnames = pd.Series(fnames, index=None)
return (urls, fnames)<|docstring|>Construct AirNow file URLs for `dates`.
Returns
-------
urls, fnames : pandas.Series<|endoftext|>
|
d36881f2bd12f4aa6ad6212b89bba764159a117a7af7beef630e5d13ba817013
|
def read_csv(fn):
'Short summary.\n\n Parameters\n ----------\n fn : string\n file name to read\n\n Returns\n -------\n type\n Description of returned object.\n\n '
hourly_cols = ['date', 'time', 'siteid', 'site', 'utcoffset', 'variable', 'units', 'obs', 'source']
daily_cols = ['date', 'siteid', 'site', 'variable', 'units', 'obs', 'hours', 'source']
try:
dft = pd.read_csv(fn, delimiter='|', header=None, error_bad_lines=False, warn_bad_lines=True, encoding='ISO-8859-1')
except Exception:
dft = pd.DataFrame(columns=hourly_cols)
ncols = dft.columns.size
daily = False
if (ncols == len(hourly_cols)):
dft.columns = hourly_cols
elif (ncols == (len(hourly_cols) - 1)):
daily = True
dft.columns = daily_cols
else:
raise Exception(f'unexpected number of columns: {ncols}')
dft['obs'] = dft.obs.astype(float)
dft['siteid'] = dft.siteid.str.zfill(9)
if (not daily):
dft['utcoffset'] = dft.utcoffset.astype(int)
return dft
|
Short summary.
Parameters
----------
fn : string
file name to read
Returns
-------
type
Description of returned object.
|
monetio/obs/airnow.py
|
read_csv
|
mlirenzhenmayi/monetio
| 1
|
python
|
def read_csv(fn):
'Short summary.\n\n Parameters\n ----------\n fn : string\n file name to read\n\n Returns\n -------\n type\n Description of returned object.\n\n '
hourly_cols = ['date', 'time', 'siteid', 'site', 'utcoffset', 'variable', 'units', 'obs', 'source']
daily_cols = ['date', 'siteid', 'site', 'variable', 'units', 'obs', 'hours', 'source']
try:
dft = pd.read_csv(fn, delimiter='|', header=None, error_bad_lines=False, warn_bad_lines=True, encoding='ISO-8859-1')
except Exception:
dft = pd.DataFrame(columns=hourly_cols)
ncols = dft.columns.size
daily = False
if (ncols == len(hourly_cols)):
dft.columns = hourly_cols
elif (ncols == (len(hourly_cols) - 1)):
daily = True
dft.columns = daily_cols
else:
raise Exception(f'unexpected number of columns: {ncols}')
dft['obs'] = dft.obs.astype(float)
dft['siteid'] = dft.siteid.str.zfill(9)
if (not daily):
dft['utcoffset'] = dft.utcoffset.astype(int)
return dft
|
def read_csv(fn):
'Short summary.\n\n Parameters\n ----------\n fn : string\n file name to read\n\n Returns\n -------\n type\n Description of returned object.\n\n '
hourly_cols = ['date', 'time', 'siteid', 'site', 'utcoffset', 'variable', 'units', 'obs', 'source']
daily_cols = ['date', 'siteid', 'site', 'variable', 'units', 'obs', 'hours', 'source']
try:
dft = pd.read_csv(fn, delimiter='|', header=None, error_bad_lines=False, warn_bad_lines=True, encoding='ISO-8859-1')
except Exception:
dft = pd.DataFrame(columns=hourly_cols)
ncols = dft.columns.size
daily = False
if (ncols == len(hourly_cols)):
dft.columns = hourly_cols
elif (ncols == (len(hourly_cols) - 1)):
daily = True
dft.columns = daily_cols
else:
raise Exception(f'unexpected number of columns: {ncols}')
dft['obs'] = dft.obs.astype(float)
dft['siteid'] = dft.siteid.str.zfill(9)
if (not daily):
dft['utcoffset'] = dft.utcoffset.astype(int)
return dft<|docstring|>Short summary.
Parameters
----------
fn : string
file name to read
Returns
-------
type
Description of returned object.<|endoftext|>
|
4eae4266fa945655636324cfe3335059d028b223a779e5b44293a2d23a60b503
|
def retrieve(url, fname):
'Download files from the airnowtech S3 server.\n\n Parameters\n ----------\n url : string\n Description of parameter `url`.\n fname : string\n Description of parameter `fname`.\n\n Returns\n -------\n None\n\n '
import requests
if (not os.path.isfile(fname)):
print(('\n Retrieving: ' + fname))
print(url)
print('\n')
r = requests.get(url)
r.raise_for_status()
with open(fname, 'wb') as f:
f.write(r.content)
else:
print(('\n File Exists: ' + fname))
|
Download files from the airnowtech S3 server.
Parameters
----------
url : string
Description of parameter `url`.
fname : string
Description of parameter `fname`.
Returns
-------
None
|
monetio/obs/airnow.py
|
retrieve
|
mlirenzhenmayi/monetio
| 1
|
python
|
def retrieve(url, fname):
'Download files from the airnowtech S3 server.\n\n Parameters\n ----------\n url : string\n Description of parameter `url`.\n fname : string\n Description of parameter `fname`.\n\n Returns\n -------\n None\n\n '
import requests
if (not os.path.isfile(fname)):
print(('\n Retrieving: ' + fname))
print(url)
print('\n')
r = requests.get(url)
r.raise_for_status()
with open(fname, 'wb') as f:
f.write(r.content)
else:
print(('\n File Exists: ' + fname))
|
def retrieve(url, fname):
'Download files from the airnowtech S3 server.\n\n Parameters\n ----------\n url : string\n Description of parameter `url`.\n fname : string\n Description of parameter `fname`.\n\n Returns\n -------\n None\n\n '
import requests
if (not os.path.isfile(fname)):
print(('\n Retrieving: ' + fname))
print(url)
print('\n')
r = requests.get(url)
r.raise_for_status()
with open(fname, 'wb') as f:
f.write(r.content)
else:
print(('\n File Exists: ' + fname))<|docstring|>Download files from the airnowtech S3 server.
Parameters
----------
url : string
Description of parameter `url`.
fname : string
Description of parameter `fname`.
Returns
-------
None<|endoftext|>
|
a4277e370930566bc189edc796b928b1d3197f6d52235ec92df3905d97c4a9ca
|
def aggregate_files(dates=dates, *, download=False, n_procs=1, daily=False):
'Short summary.\n\n Parameters\n ----------\n dates : array-like of datetime-like\n Passed to :func:`build_urls`.\n download : bool, optional\n Whether to first download the AirNow files to the local directory\n before loading.\n n_procs : int\n For Dask.\n\n Returns\n -------\n pandas.DataFrame\n Of the combined AirNow hourly files.\n '
import dask
import dask.dataframe as dd
print('Aggregating AIRNOW files...')
(urls, fnames) = build_urls(dates, daily=daily)
if download:
for (url, fname) in zip(urls, fnames):
retrieve(url, fname)
dfs = [dask.delayed(read_csv)(f) for f in fnames]
else:
dfs = [dask.delayed(read_csv)(f) for f in urls]
dff = dd.from_delayed(dfs)
df = dff.compute(num_workers=n_procs).reset_index()
if daily:
df['time'] = pd.to_datetime(df.date, format='%m/%d/%y', exact=True)
else:
df['time'] = pd.to_datetime(((df.date + ' ') + df.time), format='%m/%d/%y %H:%M', exact=True)
df['time_local'] = (df.time + pd.to_timedelta(df.utcoffset, unit='H'))
df.drop(['date'], axis=1, inplace=True)
print(' Adding in Meta-data')
df = get_station_locations(df)
if daily:
df = df[[col for col in savecols if (col not in {'time_local', 'utcoffset'})]]
else:
df = df[savecols]
df.drop_duplicates(inplace=True)
df = filter_bad_values(df)
return df.reset_index(drop=True)
|
Short summary.
Parameters
----------
dates : array-like of datetime-like
Passed to :func:`build_urls`.
download : bool, optional
Whether to first download the AirNow files to the local directory
before loading.
n_procs : int
For Dask.
Returns
-------
pandas.DataFrame
Of the combined AirNow hourly files.
|
monetio/obs/airnow.py
|
aggregate_files
|
mlirenzhenmayi/monetio
| 1
|
python
|
def aggregate_files(dates=dates, *, download=False, n_procs=1, daily=False):
'Short summary.\n\n Parameters\n ----------\n dates : array-like of datetime-like\n Passed to :func:`build_urls`.\n download : bool, optional\n Whether to first download the AirNow files to the local directory\n before loading.\n n_procs : int\n For Dask.\n\n Returns\n -------\n pandas.DataFrame\n Of the combined AirNow hourly files.\n '
import dask
import dask.dataframe as dd
print('Aggregating AIRNOW files...')
(urls, fnames) = build_urls(dates, daily=daily)
if download:
for (url, fname) in zip(urls, fnames):
retrieve(url, fname)
dfs = [dask.delayed(read_csv)(f) for f in fnames]
else:
dfs = [dask.delayed(read_csv)(f) for f in urls]
dff = dd.from_delayed(dfs)
df = dff.compute(num_workers=n_procs).reset_index()
if daily:
df['time'] = pd.to_datetime(df.date, format='%m/%d/%y', exact=True)
else:
df['time'] = pd.to_datetime(((df.date + ' ') + df.time), format='%m/%d/%y %H:%M', exact=True)
df['time_local'] = (df.time + pd.to_timedelta(df.utcoffset, unit='H'))
df.drop(['date'], axis=1, inplace=True)
print(' Adding in Meta-data')
df = get_station_locations(df)
if daily:
df = df[[col for col in savecols if (col not in {'time_local', 'utcoffset'})]]
else:
df = df[savecols]
df.drop_duplicates(inplace=True)
df = filter_bad_values(df)
return df.reset_index(drop=True)
|
def aggregate_files(dates=dates, *, download=False, n_procs=1, daily=False):
'Short summary.\n\n Parameters\n ----------\n dates : array-like of datetime-like\n Passed to :func:`build_urls`.\n download : bool, optional\n Whether to first download the AirNow files to the local directory\n before loading.\n n_procs : int\n For Dask.\n\n Returns\n -------\n pandas.DataFrame\n Of the combined AirNow hourly files.\n '
import dask
import dask.dataframe as dd
print('Aggregating AIRNOW files...')
(urls, fnames) = build_urls(dates, daily=daily)
if download:
for (url, fname) in zip(urls, fnames):
retrieve(url, fname)
dfs = [dask.delayed(read_csv)(f) for f in fnames]
else:
dfs = [dask.delayed(read_csv)(f) for f in urls]
dff = dd.from_delayed(dfs)
df = dff.compute(num_workers=n_procs).reset_index()
if daily:
df['time'] = pd.to_datetime(df.date, format='%m/%d/%y', exact=True)
else:
df['time'] = pd.to_datetime(((df.date + ' ') + df.time), format='%m/%d/%y %H:%M', exact=True)
df['time_local'] = (df.time + pd.to_timedelta(df.utcoffset, unit='H'))
df.drop(['date'], axis=1, inplace=True)
print(' Adding in Meta-data')
df = get_station_locations(df)
if daily:
df = df[[col for col in savecols if (col not in {'time_local', 'utcoffset'})]]
else:
df = df[savecols]
df.drop_duplicates(inplace=True)
df = filter_bad_values(df)
return df.reset_index(drop=True)<|docstring|>Short summary.
Parameters
----------
dates : array-like of datetime-like
Passed to :func:`build_urls`.
download : bool, optional
Whether to first download the AirNow files to the local directory
before loading.
n_procs : int
For Dask.
Returns
-------
pandas.DataFrame
Of the combined AirNow hourly files.<|endoftext|>
|
a31b6e37c310ca087868b9c8496bbdf302f398d5abb0694a85fcf34e9fd93bd5
|
def add_data(dates, *, download=False, wide_fmt=True, n_procs=1, daily=False):
'Retrieve and load AirNow data as a DataFrame.\n\n Note: to obtain full hourly data you must pass all desired hours\n in `dates`.\n\n Parameters\n ----------\n dates : array-like of datetime-like\n Passed to :func:`build_urls`.\n download : bool, optional\n Whether to first download the AirNow files to the local directory.\n wide_fmt : bool\n n_procs : int\n For Dask.\n daily : bool\n Whether to get daily data only\n (only unique days in `dates` will be used).\n\n Info: https://files.airnowtech.org/airnow/docs/DailyDataFactSheet.pdf\n\n Note: ``daily_data_v2.dat`` (includes AQI) is not available for all times,\n so we use ``daily_data.dat``.\n\n Returns\n -------\n pandas.DataFrame\n '
from ..util import long_to_wide
df = aggregate_files(dates=dates, download=download, n_procs=n_procs, daily=daily)
if wide_fmt:
df = long_to_wide(df).drop_duplicates(subset=['time', 'latitude', 'longitude', 'siteid']).reset_index(drop=True)
return df
|
Retrieve and load AirNow data as a DataFrame.
Note: to obtain full hourly data you must pass all desired hours
in `dates`.
Parameters
----------
dates : array-like of datetime-like
Passed to :func:`build_urls`.
download : bool, optional
Whether to first download the AirNow files to the local directory.
wide_fmt : bool
n_procs : int
For Dask.
daily : bool
Whether to get daily data only
(only unique days in `dates` will be used).
Info: https://files.airnowtech.org/airnow/docs/DailyDataFactSheet.pdf
Note: ``daily_data_v2.dat`` (includes AQI) is not available for all times,
so we use ``daily_data.dat``.
Returns
-------
pandas.DataFrame
|
monetio/obs/airnow.py
|
add_data
|
mlirenzhenmayi/monetio
| 1
|
python
|
def add_data(dates, *, download=False, wide_fmt=True, n_procs=1, daily=False):
'Retrieve and load AirNow data as a DataFrame.\n\n Note: to obtain full hourly data you must pass all desired hours\n in `dates`.\n\n Parameters\n ----------\n dates : array-like of datetime-like\n Passed to :func:`build_urls`.\n download : bool, optional\n Whether to first download the AirNow files to the local directory.\n wide_fmt : bool\n n_procs : int\n For Dask.\n daily : bool\n Whether to get daily data only\n (only unique days in `dates` will be used).\n\n Info: https://files.airnowtech.org/airnow/docs/DailyDataFactSheet.pdf\n\n Note: ``daily_data_v2.dat`` (includes AQI) is not available for all times,\n so we use ``daily_data.dat``.\n\n Returns\n -------\n pandas.DataFrame\n '
from ..util import long_to_wide
df = aggregate_files(dates=dates, download=download, n_procs=n_procs, daily=daily)
if wide_fmt:
df = long_to_wide(df).drop_duplicates(subset=['time', 'latitude', 'longitude', 'siteid']).reset_index(drop=True)
return df
|
def add_data(dates, *, download=False, wide_fmt=True, n_procs=1, daily=False):
'Retrieve and load AirNow data as a DataFrame.\n\n Note: to obtain full hourly data you must pass all desired hours\n in `dates`.\n\n Parameters\n ----------\n dates : array-like of datetime-like\n Passed to :func:`build_urls`.\n download : bool, optional\n Whether to first download the AirNow files to the local directory.\n wide_fmt : bool\n n_procs : int\n For Dask.\n daily : bool\n Whether to get daily data only\n (only unique days in `dates` will be used).\n\n Info: https://files.airnowtech.org/airnow/docs/DailyDataFactSheet.pdf\n\n Note: ``daily_data_v2.dat`` (includes AQI) is not available for all times,\n so we use ``daily_data.dat``.\n\n Returns\n -------\n pandas.DataFrame\n '
from ..util import long_to_wide
df = aggregate_files(dates=dates, download=download, n_procs=n_procs, daily=daily)
if wide_fmt:
df = long_to_wide(df).drop_duplicates(subset=['time', 'latitude', 'longitude', 'siteid']).reset_index(drop=True)
return df<|docstring|>Retrieve and load AirNow data as a DataFrame.
Note: to obtain full hourly data you must pass all desired hours
in `dates`.
Parameters
----------
dates : array-like of datetime-like
Passed to :func:`build_urls`.
download : bool, optional
Whether to first download the AirNow files to the local directory.
wide_fmt : bool
n_procs : int
For Dask.
daily : bool
Whether to get daily data only
(only unique days in `dates` will be used).
Info: https://files.airnowtech.org/airnow/docs/DailyDataFactSheet.pdf
Note: ``daily_data_v2.dat`` (includes AQI) is not available for all times,
so we use ``daily_data.dat``.
Returns
-------
pandas.DataFrame<|endoftext|>
|
c54990112e058759bcd9377211a8bc947217ea96eda70d82e8da1c3c7b45220c
|
def filter_bad_values(df, *, max=3000):
'Mark ``obs`` values less than 0 or greater than `max` as NaN.\n\n Parameters\n ----------\n max : int\n\n Returns\n -------\n pandas.DataFrame\n '
from numpy import NaN
df.loc[(((df.obs > max) | (df.obs < 0)), 'obs')] = NaN
return df
|
Mark ``obs`` values less than 0 or greater than `max` as NaN.
Parameters
----------
max : int
Returns
-------
pandas.DataFrame
|
monetio/obs/airnow.py
|
filter_bad_values
|
mlirenzhenmayi/monetio
| 1
|
python
|
def filter_bad_values(df, *, max=3000):
'Mark ``obs`` values less than 0 or greater than `max` as NaN.\n\n Parameters\n ----------\n max : int\n\n Returns\n -------\n pandas.DataFrame\n '
from numpy import NaN
df.loc[(((df.obs > max) | (df.obs < 0)), 'obs')] = NaN
return df
|
def filter_bad_values(df, *, max=3000):
'Mark ``obs`` values less than 0 or greater than `max` as NaN.\n\n Parameters\n ----------\n max : int\n\n Returns\n -------\n pandas.DataFrame\n '
from numpy import NaN
df.loc[(((df.obs > max) | (df.obs < 0)), 'obs')] = NaN
return df<|docstring|>Mark ``obs`` values less than 0 or greater than `max` as NaN.
Parameters
----------
max : int
Returns
-------
pandas.DataFrame<|endoftext|>
|
a3f97b79884312215a6257aea13d6436df969a8c4e9ec9833219c23d11327127
|
def daterange(**kwargs):
"Short summary.\n\n Parameters\n ----------\n begin : type\n Description of parameter `begin` (the default is '').\n end : type\n Description of parameter `end` (the default is '').\n\n Returns\n -------\n type\n Description of returned object.\n\n "
return pd.date_range(**kwargs)
|
Short summary.
Parameters
----------
begin : type
Description of parameter `begin` (the default is '').
end : type
Description of parameter `end` (the default is '').
Returns
-------
type
Description of returned object.
|
monetio/obs/airnow.py
|
daterange
|
mlirenzhenmayi/monetio
| 1
|
python
|
def daterange(**kwargs):
"Short summary.\n\n Parameters\n ----------\n begin : type\n Description of parameter `begin` (the default is ).\n end : type\n Description of parameter `end` (the default is ).\n\n Returns\n -------\n type\n Description of returned object.\n\n "
return pd.date_range(**kwargs)
|
def daterange(**kwargs):
"Short summary.\n\n Parameters\n ----------\n begin : type\n Description of parameter `begin` (the default is ).\n end : type\n Description of parameter `end` (the default is ).\n\n Returns\n -------\n type\n Description of returned object.\n\n "
return pd.date_range(**kwargs)<|docstring|>Short summary.
Parameters
----------
begin : type
Description of parameter `begin` (the default is '').
end : type
Description of parameter `end` (the default is '').
Returns
-------
type
Description of returned object.<|endoftext|>
|
98b1fb97e0ce8ed488238b0a54608585e5ef64c5b5287a678601dc7503f7e137
|
def get_station_locations(df):
'Short summary.\n\n Returns\n -------\n type\n Description of returned object.\n\n '
from .epa_util import read_monitor_file
monitor_df = read_monitor_file(airnow=True)
df = df.merge(monitor_df.drop_duplicates(), on='siteid', how='left', copy=False)
return df
|
Short summary.
Returns
-------
type
Description of returned object.
|
monetio/obs/airnow.py
|
get_station_locations
|
mlirenzhenmayi/monetio
| 1
|
python
|
def get_station_locations(df):
'Short summary.\n\n Returns\n -------\n type\n Description of returned object.\n\n '
from .epa_util import read_monitor_file
monitor_df = read_monitor_file(airnow=True)
df = df.merge(monitor_df.drop_duplicates(), on='siteid', how='left', copy=False)
return df
|
def get_station_locations(df):
'Short summary.\n\n Returns\n -------\n type\n Description of returned object.\n\n '
from .epa_util import read_monitor_file
monitor_df = read_monitor_file(airnow=True)
df = df.merge(monitor_df.drop_duplicates(), on='siteid', how='left', copy=False)
return df<|docstring|>Short summary.
Returns
-------
type
Description of returned object.<|endoftext|>
|
7aadcc7d0317b15b42fc49ab9c07496f2b8cb424b7097522696c7c7a5f4512e4
|
def get_station_locations_remerge(df):
'Short summary.\n\n Parameters\n ----------\n df : type\n Description of parameter `df`.\n\n Returns\n -------\n type\n Description of returned object.\n\n '
df = pd.merge(df, monitor_df.drop(['Latitude', 'Longitude'], axis=1), on='siteid')
return df
|
Short summary.
Parameters
----------
df : type
Description of parameter `df`.
Returns
-------
type
Description of returned object.
|
monetio/obs/airnow.py
|
get_station_locations_remerge
|
mlirenzhenmayi/monetio
| 1
|
python
|
def get_station_locations_remerge(df):
'Short summary.\n\n Parameters\n ----------\n df : type\n Description of parameter `df`.\n\n Returns\n -------\n type\n Description of returned object.\n\n '
df = pd.merge(df, monitor_df.drop(['Latitude', 'Longitude'], axis=1), on='siteid')
return df
|
def get_station_locations_remerge(df):
'Short summary.\n\n Parameters\n ----------\n df : type\n Description of parameter `df`.\n\n Returns\n -------\n type\n Description of returned object.\n\n '
df = pd.merge(df, monitor_df.drop(['Latitude', 'Longitude'], axis=1), on='siteid')
return df<|docstring|>Short summary.
Parameters
----------
df : type
Description of parameter `df`.
Returns
-------
type
Description of returned object.<|endoftext|>
|
d8c8d164d7d8d1159cfe73203f1accca9bea4cc2e338f54ce8d1731763e34b76
|
def init_logger(log_file_name='log', console=True, error=True, debug=False):
'Initialize logger.'
logger = logging.getLogger()
logger.setLevel('DEBUG')
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
file_out_info = logging.FileHandler((log_file_name + '.info'))
file_out_info.setFormatter(formatter)
file_out_info.setLevel('INFO')
logger.addHandler(file_out_info)
if console:
con_out = logging.StreamHandler()
con_out.setFormatter(formatter)
con_out.setLevel('INFO')
logger.addHandler(con_out)
if error:
file_out_error = logging.FileHandler((log_file_name + '.erro'))
file_out_error.setFormatter(formatter)
file_out_error.setLevel('ERROR')
logger.addHandler(file_out_error)
if debug:
file_out_debug = logging.FileHandler((log_file_name + '.debug'))
file_out_debug.setFormatter(formatter)
file_out_debug.setLevel('DEBUG')
logger.addHandler(file_out_debug)
print('Init logger sucussful.')
return logger
|
Initialize logger.
|
beta_rec/utils/logger.py
|
init_logger
|
TedSIWEILIU/beta-recsys
| 126
|
python
|
def init_logger(log_file_name='log', console=True, error=True, debug=False):
logger = logging.getLogger()
logger.setLevel('DEBUG')
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
file_out_info = logging.FileHandler((log_file_name + '.info'))
file_out_info.setFormatter(formatter)
file_out_info.setLevel('INFO')
logger.addHandler(file_out_info)
if console:
con_out = logging.StreamHandler()
con_out.setFormatter(formatter)
con_out.setLevel('INFO')
logger.addHandler(con_out)
if error:
file_out_error = logging.FileHandler((log_file_name + '.erro'))
file_out_error.setFormatter(formatter)
file_out_error.setLevel('ERROR')
logger.addHandler(file_out_error)
if debug:
file_out_debug = logging.FileHandler((log_file_name + '.debug'))
file_out_debug.setFormatter(formatter)
file_out_debug.setLevel('DEBUG')
logger.addHandler(file_out_debug)
print('Init logger sucussful.')
return logger
|
def init_logger(log_file_name='log', console=True, error=True, debug=False):
logger = logging.getLogger()
logger.setLevel('DEBUG')
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
file_out_info = logging.FileHandler((log_file_name + '.info'))
file_out_info.setFormatter(formatter)
file_out_info.setLevel('INFO')
logger.addHandler(file_out_info)
if console:
con_out = logging.StreamHandler()
con_out.setFormatter(formatter)
con_out.setLevel('INFO')
logger.addHandler(con_out)
if error:
file_out_error = logging.FileHandler((log_file_name + '.erro'))
file_out_error.setFormatter(formatter)
file_out_error.setLevel('ERROR')
logger.addHandler(file_out_error)
if debug:
file_out_debug = logging.FileHandler((log_file_name + '.debug'))
file_out_debug.setFormatter(formatter)
file_out_debug.setLevel('DEBUG')
logger.addHandler(file_out_debug)
print('Init logger sucussful.')
return logger<|docstring|>Initialize logger.<|endoftext|>
|
77b590d45787bd4eff469afc9ba47972aa556a6a208198643491da478e4ef738
|
def get_logger(filename='default', level='info'):
'Get logger.'
logger = logging.getLogger()
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
if (level == 'info'):
file_out_info = logging.FileHandler((filename + '.log'))
file_out_info.setFormatter(formatter)
file_out_info.setLevel('INFO')
logger.addHandler(file_out_info)
elif (level == 'error'):
file_out_error = logging.FileHandler((filename + '.log'))
file_out_error.setFormatter(formatter)
file_out_error.setLevel('ERROR')
logger.addHandler(file_out_error)
print('Init ', level, 'logger sucussful.')
return logger
|
Get logger.
|
beta_rec/utils/logger.py
|
get_logger
|
TedSIWEILIU/beta-recsys
| 126
|
python
|
def get_logger(filename='default', level='info'):
logger = logging.getLogger()
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
if (level == 'info'):
file_out_info = logging.FileHandler((filename + '.log'))
file_out_info.setFormatter(formatter)
file_out_info.setLevel('INFO')
logger.addHandler(file_out_info)
elif (level == 'error'):
file_out_error = logging.FileHandler((filename + '.log'))
file_out_error.setFormatter(formatter)
file_out_error.setLevel('ERROR')
logger.addHandler(file_out_error)
print('Init ', level, 'logger sucussful.')
return logger
|
def get_logger(filename='default', level='info'):
logger = logging.getLogger()
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
if (level == 'info'):
file_out_info = logging.FileHandler((filename + '.log'))
file_out_info.setFormatter(formatter)
file_out_info.setLevel('INFO')
logger.addHandler(file_out_info)
elif (level == 'error'):
file_out_error = logging.FileHandler((filename + '.log'))
file_out_error.setFormatter(formatter)
file_out_error.setLevel('ERROR')
logger.addHandler(file_out_error)
print('Init ', level, 'logger sucussful.')
return logger<|docstring|>Get logger.<|endoftext|>
|
d97cc24990fbedc2bb1869312ee3548939253d46ede2fc27a8402805c98e13c7
|
def init_std_logger(log_file='default'):
'Initialize std logger.'
print('logs will save in file:', log_file, '.stdout.log', '.stderr.log')
sys.stdout = Logger((log_file + '.stdout.log'), stdout=sys.stdout)
sys.stderr = Logger((log_file + '.stderr.log'), stderr=sys.stderr)
|
Initialize std logger.
|
beta_rec/utils/logger.py
|
init_std_logger
|
TedSIWEILIU/beta-recsys
| 126
|
python
|
def init_std_logger(log_file='default'):
print('logs will save in file:', log_file, '.stdout.log', '.stderr.log')
sys.stdout = Logger((log_file + '.stdout.log'), stdout=sys.stdout)
sys.stderr = Logger((log_file + '.stderr.log'), stderr=sys.stderr)
|
def init_std_logger(log_file='default'):
print('logs will save in file:', log_file, '.stdout.log', '.stderr.log')
sys.stdout = Logger((log_file + '.stdout.log'), stdout=sys.stdout)
sys.stderr = Logger((log_file + '.stderr.log'), stderr=sys.stderr)<|docstring|>Initialize std logger.<|endoftext|>
|
80c72f1e3f78172a13fd944618ef06e1c0a058f5e9b2e437c127586d294bf0a7
|
def __init__(self, filename='default', stdout=None, stderr=None):
'Initialize Logger Class.'
self.stdout = stdout
self.stderr = stderr
self.fileno = sys.stdout.fileno
self.filename = filename
self.message = ''
|
Initialize Logger Class.
|
beta_rec/utils/logger.py
|
__init__
|
TedSIWEILIU/beta-recsys
| 126
|
python
|
def __init__(self, filename='default', stdout=None, stderr=None):
self.stdout = stdout
self.stderr = stderr
self.fileno = sys.stdout.fileno
self.filename = filename
self.message =
|
def __init__(self, filename='default', stdout=None, stderr=None):
self.stdout = stdout
self.stderr = stderr
self.fileno = sys.stdout.fileno
self.filename = filename
self.message = <|docstring|>Initialize Logger Class.<|endoftext|>
|
4bdc9ddf2487325f1aa05242c71c133447ea7dbed43be38b32fc6f5e5cb55c4d
|
def write(self, message):
'Log out message.'
if ((message == '') or (message is None)):
return
elif ('\n' in message):
message = message[:(- 1)]
self.message += message
now = datetime.now()
date_time = now.strftime('%Y-%m-%d %H:%M:%S ')
if (self.stdout is not None):
if ('\n' in self.message):
self.message = (((date_time + '[INFO]-\n') + self.message) + '\n')
else:
self.message = (((date_time + '[INFO]-') + self.message) + '\n')
self.stdout.write(self.message)
self.stdout.flush()
if (self.stderr is not None):
if ('\n' in self.message):
self.message = (((date_time + '[ERROR]-\n') + self.message) + '\n')
else:
self.message = (((date_time + '[ERROR]-') + self.message) + '\n')
self.stderr.write(self.message)
self.stderr.flush()
with open(self.filename, 'a') as logger:
logger.write(self.message)
self.message = ''
else:
self.message += message
|
Log out message.
|
beta_rec/utils/logger.py
|
write
|
TedSIWEILIU/beta-recsys
| 126
|
python
|
def write(self, message):
if ((message == ) or (message is None)):
return
elif ('\n' in message):
message = message[:(- 1)]
self.message += message
now = datetime.now()
date_time = now.strftime('%Y-%m-%d %H:%M:%S ')
if (self.stdout is not None):
if ('\n' in self.message):
self.message = (((date_time + '[INFO]-\n') + self.message) + '\n')
else:
self.message = (((date_time + '[INFO]-') + self.message) + '\n')
self.stdout.write(self.message)
self.stdout.flush()
if (self.stderr is not None):
if ('\n' in self.message):
self.message = (((date_time + '[ERROR]-\n') + self.message) + '\n')
else:
self.message = (((date_time + '[ERROR]-') + self.message) + '\n')
self.stderr.write(self.message)
self.stderr.flush()
with open(self.filename, 'a') as logger:
logger.write(self.message)
self.message =
else:
self.message += message
|
def write(self, message):
if ((message == ) or (message is None)):
return
elif ('\n' in message):
message = message[:(- 1)]
self.message += message
now = datetime.now()
date_time = now.strftime('%Y-%m-%d %H:%M:%S ')
if (self.stdout is not None):
if ('\n' in self.message):
self.message = (((date_time + '[INFO]-\n') + self.message) + '\n')
else:
self.message = (((date_time + '[INFO]-') + self.message) + '\n')
self.stdout.write(self.message)
self.stdout.flush()
if (self.stderr is not None):
if ('\n' in self.message):
self.message = (((date_time + '[ERROR]-\n') + self.message) + '\n')
else:
self.message = (((date_time + '[ERROR]-') + self.message) + '\n')
self.stderr.write(self.message)
self.stderr.flush()
with open(self.filename, 'a') as logger:
logger.write(self.message)
self.message =
else:
self.message += message<|docstring|>Log out message.<|endoftext|>
|
cd9c7638391d3321af45001d3da5e70ffaada48716a23582371d641b12b921b3
|
def flush(self):
'Missing Doc.'
pass
|
Missing Doc.
|
beta_rec/utils/logger.py
|
flush
|
TedSIWEILIU/beta-recsys
| 126
|
python
|
def flush(self):
pass
|
def flush(self):
pass<|docstring|>Missing Doc.<|endoftext|>
|
5a4dff22e7f0f9e5cec306748ff4fd98dc23bbfca02324083d418abccc62e8d4
|
def __init__(__self__, resource_name, opts=None, autoscaling_policy=None, description=None, name=None, project=None, target=None, zone=None, __name__=None, __opts__=None):
'\n Represents an Autoscaler resource.\n \n Autoscalers allow you to automatically scale virtual machine instances in\n managed instance groups according to an autoscaling policy that you\n define.\n \n \n To get more information about Autoscaler, see:\n \n * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/autoscalers)\n * How-to Guides\n * [Autoscaling Groups of Instances](https://cloud.google.com/compute/docs/autoscaler/)\n \n <div class = "oics-button" style="float: right; margin: 0 0 -15px">\n <a href="https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fterraform-google-modules%2Fdocs-examples.git&cloudshell_working_dir=autoscaler_beta&cloudshell_image=gcr.io%2Fgraphite-cloud-shell-images%2Fterraform%3Alatest&open_in_editor=main.tf&cloudshell_print=.%2Fmotd&cloudshell_tutorial=.%2Ftutorial.md" target="_blank">\n <img alt="Open in Cloud Shell" src="//gstatic.com/cloudssh/images/open-btn.svg" style="max-height: 44px; margin: 32px auto; max-width: 100%;">\n </a>\n </div>\n \n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n '
if (__name__ is not None):
warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning)
resource_name = __name__
if (__opts__ is not None):
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if (not resource_name):
raise TypeError('Missing resource name argument (for URN creation)')
if (not isinstance(resource_name, str)):
raise TypeError('Expected resource name to be a string')
if (opts and (not isinstance(opts, pulumi.ResourceOptions))):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
if (autoscaling_policy is None):
raise TypeError('Missing required property autoscaling_policy')
__props__['autoscaling_policy'] = autoscaling_policy
__props__['description'] = description
__props__['name'] = name
__props__['project'] = project
if (target is None):
raise TypeError('Missing required property target')
__props__['target'] = target
__props__['zone'] = zone
__props__['creation_timestamp'] = None
__props__['self_link'] = None
super(Autoscalar, __self__).__init__('gcp:compute/autoscalar:Autoscalar', resource_name, __props__, opts)
|
Represents an Autoscaler resource.
Autoscalers allow you to automatically scale virtual machine instances in
managed instance groups according to an autoscaling policy that you
define.
To get more information about Autoscaler, see:
* [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/autoscalers)
* How-to Guides
* [Autoscaling Groups of Instances](https://cloud.google.com/compute/docs/autoscaler/)
<div class = "oics-button" style="float: right; margin: 0 0 -15px">
<a href="https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fterraform-google-modules%2Fdocs-examples.git&cloudshell_working_dir=autoscaler_beta&cloudshell_image=gcr.io%2Fgraphite-cloud-shell-images%2Fterraform%3Alatest&open_in_editor=main.tf&cloudshell_print=.%2Fmotd&cloudshell_tutorial=.%2Ftutorial.md" target="_blank">
<img alt="Open in Cloud Shell" src="//gstatic.com/cloudssh/images/open-btn.svg" style="max-height: 44px; margin: 32px auto; max-width: 100%;">
</a>
</div>
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
|
sdk/python/pulumi_gcp/compute/autoscalar.py
|
__init__
|
stack72/pulumi-gcp
| 0
|
python
|
def __init__(__self__, resource_name, opts=None, autoscaling_policy=None, description=None, name=None, project=None, target=None, zone=None, __name__=None, __opts__=None):
'\n Represents an Autoscaler resource.\n \n Autoscalers allow you to automatically scale virtual machine instances in\n managed instance groups according to an autoscaling policy that you\n define.\n \n \n To get more information about Autoscaler, see:\n \n * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/autoscalers)\n * How-to Guides\n * [Autoscaling Groups of Instances](https://cloud.google.com/compute/docs/autoscaler/)\n \n <div class = "oics-button" style="float: right; margin: 0 0 -15px">\n <a href="https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fterraform-google-modules%2Fdocs-examples.git&cloudshell_working_dir=autoscaler_beta&cloudshell_image=gcr.io%2Fgraphite-cloud-shell-images%2Fterraform%3Alatest&open_in_editor=main.tf&cloudshell_print=.%2Fmotd&cloudshell_tutorial=.%2Ftutorial.md" target="_blank">\n <img alt="Open in Cloud Shell" src="//gstatic.com/cloudssh/images/open-btn.svg" style="max-height: 44px; margin: 32px auto; max-width: 100%;">\n </a>\n </div>\n \n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n '
if (__name__ is not None):
warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning)
resource_name = __name__
if (__opts__ is not None):
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if (not resource_name):
raise TypeError('Missing resource name argument (for URN creation)')
if (not isinstance(resource_name, str)):
raise TypeError('Expected resource name to be a string')
if (opts and (not isinstance(opts, pulumi.ResourceOptions))):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
if (autoscaling_policy is None):
raise TypeError('Missing required property autoscaling_policy')
__props__['autoscaling_policy'] = autoscaling_policy
__props__['description'] = description
__props__['name'] = name
__props__['project'] = project
if (target is None):
raise TypeError('Missing required property target')
__props__['target'] = target
__props__['zone'] = zone
__props__['creation_timestamp'] = None
__props__['self_link'] = None
super(Autoscalar, __self__).__init__('gcp:compute/autoscalar:Autoscalar', resource_name, __props__, opts)
|
def __init__(__self__, resource_name, opts=None, autoscaling_policy=None, description=None, name=None, project=None, target=None, zone=None, __name__=None, __opts__=None):
'\n Represents an Autoscaler resource.\n \n Autoscalers allow you to automatically scale virtual machine instances in\n managed instance groups according to an autoscaling policy that you\n define.\n \n \n To get more information about Autoscaler, see:\n \n * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/autoscalers)\n * How-to Guides\n * [Autoscaling Groups of Instances](https://cloud.google.com/compute/docs/autoscaler/)\n \n <div class = "oics-button" style="float: right; margin: 0 0 -15px">\n <a href="https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fterraform-google-modules%2Fdocs-examples.git&cloudshell_working_dir=autoscaler_beta&cloudshell_image=gcr.io%2Fgraphite-cloud-shell-images%2Fterraform%3Alatest&open_in_editor=main.tf&cloudshell_print=.%2Fmotd&cloudshell_tutorial=.%2Ftutorial.md" target="_blank">\n <img alt="Open in Cloud Shell" src="//gstatic.com/cloudssh/images/open-btn.svg" style="max-height: 44px; margin: 32px auto; max-width: 100%;">\n </a>\n </div>\n \n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n '
if (__name__ is not None):
warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning)
resource_name = __name__
if (__opts__ is not None):
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if (not resource_name):
raise TypeError('Missing resource name argument (for URN creation)')
if (not isinstance(resource_name, str)):
raise TypeError('Expected resource name to be a string')
if (opts and (not isinstance(opts, pulumi.ResourceOptions))):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
if (autoscaling_policy is None):
raise TypeError('Missing required property autoscaling_policy')
__props__['autoscaling_policy'] = autoscaling_policy
__props__['description'] = description
__props__['name'] = name
__props__['project'] = project
if (target is None):
raise TypeError('Missing required property target')
__props__['target'] = target
__props__['zone'] = zone
__props__['creation_timestamp'] = None
__props__['self_link'] = None
super(Autoscalar, __self__).__init__('gcp:compute/autoscalar:Autoscalar', resource_name, __props__, opts)<|docstring|>Represents an Autoscaler resource.
Autoscalers allow you to automatically scale virtual machine instances in
managed instance groups according to an autoscaling policy that you
define.
To get more information about Autoscaler, see:
* [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/autoscalers)
* How-to Guides
* [Autoscaling Groups of Instances](https://cloud.google.com/compute/docs/autoscaler/)
<div class = "oics-button" style="float: right; margin: 0 0 -15px">
<a href="https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fterraform-google-modules%2Fdocs-examples.git&cloudshell_working_dir=autoscaler_beta&cloudshell_image=gcr.io%2Fgraphite-cloud-shell-images%2Fterraform%3Alatest&open_in_editor=main.tf&cloudshell_print=.%2Fmotd&cloudshell_tutorial=.%2Ftutorial.md" target="_blank">
<img alt="Open in Cloud Shell" src="//gstatic.com/cloudssh/images/open-btn.svg" style="max-height: 44px; margin: 32px auto; max-width: 100%;">
</a>
</div>
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.<|endoftext|>
|
e2202e683e437c881e5a8d8c654cdfa6e9357bc15b68e7a529b0b5db04a2e382
|
def is_ready(self) -> bool:
'\n :return: True if active and synced, False otherwise.\n '
with self._lock:
if self.is_active():
if self._distributed:
return self._is_synced
else:
return True
|
:return: True if active and synced, False otherwise.
|
bobocep/setup/bobo_setup.py
|
is_ready
|
r3w0p/bobocep
| 5
|
python
|
def is_ready(self) -> bool:
'\n \n '
with self._lock:
if self.is_active():
if self._distributed:
return self._is_synced
else:
return True
|
def is_ready(self) -> bool:
'\n \n '
with self._lock:
if self.is_active():
if self._distributed:
return self._is_synced
else:
return True<|docstring|>:return: True if active and synced, False otherwise.<|endoftext|>
|
67d197b48c24d48d1ed7b54a7ecc7a1ca4b612608a1f7f63d4906d9b23e293da
|
def is_active(self) -> bool:
'\n :return: True if running and not cancelled, False otherwise.\n '
with self._lock:
return (self._running and (not self._cancelled))
|
:return: True if running and not cancelled, False otherwise.
|
bobocep/setup/bobo_setup.py
|
is_active
|
r3w0p/bobocep
| 5
|
python
|
def is_active(self) -> bool:
'\n \n '
with self._lock:
return (self._running and (not self._cancelled))
|
def is_active(self) -> bool:
'\n \n '
with self._lock:
return (self._running and (not self._cancelled))<|docstring|>:return: True if running and not cancelled, False otherwise.<|endoftext|>
|
fa5a17db21ebf0b1e4bbb839fddb1b7f4d7f1867f56e2566742b8424f705790b
|
def is_inactive(self) -> bool:
'\n :return: True if not running and not cancelled, False otherwise.\n '
with self._lock:
return ((not self._running) and (not self._cancelled))
|
:return: True if not running and not cancelled, False otherwise.
|
bobocep/setup/bobo_setup.py
|
is_inactive
|
r3w0p/bobocep
| 5
|
python
|
def is_inactive(self) -> bool:
'\n \n '
with self._lock:
return ((not self._running) and (not self._cancelled))
|
def is_inactive(self) -> bool:
'\n \n '
with self._lock:
return ((not self._running) and (not self._cancelled))<|docstring|>:return: True if not running and not cancelled, False otherwise.<|endoftext|>
|
7c0915bb775246f3547e419a2d3835274de826c7a023f4671efb06ff63e8a72d
|
def is_cancelled(self) -> bool:
'\n :return: True if cancelled, False otherwise.\n '
with self._lock:
return self._cancelled
|
:return: True if cancelled, False otherwise.
|
bobocep/setup/bobo_setup.py
|
is_cancelled
|
r3w0p/bobocep
| 5
|
python
|
def is_cancelled(self) -> bool:
'\n \n '
with self._lock:
return self._cancelled
|
def is_cancelled(self) -> bool:
'\n \n '
with self._lock:
return self._cancelled<|docstring|>:return: True if cancelled, False otherwise.<|endoftext|>
|
b4a88ef5ed3b0d4a97e5a96b97c3775bcaed0e6d4bcd87b5a96c6fa9cf4811d3
|
def is_configured(self) -> bool:
'\n :return: True if configured, False otherwise.\n '
with self._lock:
return self._configured
|
:return: True if configured, False otherwise.
|
bobocep/setup/bobo_setup.py
|
is_configured
|
r3w0p/bobocep
| 5
|
python
|
def is_configured(self) -> bool:
'\n \n '
with self._lock:
return self._configured
|
def is_configured(self) -> bool:
'\n \n '
with self._lock:
return self._configured<|docstring|>:return: True if configured, False otherwise.<|endoftext|>
|
550f69605bd87d932f72301ce2a0924fcf5f9721b71935d24071808834920572
|
def get_receiver(self) -> BoboReceiver:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._receiver
|
:raises RuntimeError: Attempting access before configuration.
:return: The Receiver.
|
bobocep/setup/bobo_setup.py
|
get_receiver
|
r3w0p/bobocep
| 5
|
python
|
def get_receiver(self) -> BoboReceiver:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._receiver
|
def get_receiver(self) -> BoboReceiver:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._receiver<|docstring|>:raises RuntimeError: Attempting access before configuration.
:return: The Receiver.<|endoftext|>
|
3bf254ea828e82ffe595d2f31e06db01272b5bbec5a32aa5a6b0bd3fd5d7f56f
|
def get_decider(self) -> BoboDecider:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._decider
|
:raises RuntimeError: Attempting access before configuration.
:return: The Receiver.
|
bobocep/setup/bobo_setup.py
|
get_decider
|
r3w0p/bobocep
| 5
|
python
|
def get_decider(self) -> BoboDecider:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._decider
|
def get_decider(self) -> BoboDecider:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._decider<|docstring|>:raises RuntimeError: Attempting access before configuration.
:return: The Receiver.<|endoftext|>
|
abe84c282ab71c2b57ec7d3820252ca75f917f50f8a8a5cda84989cfc8793fd7
|
def get_producer(self) -> ActionProducer:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._producer
|
:raises RuntimeError: Attempting access before configuration.
:return: The Receiver.
|
bobocep/setup/bobo_setup.py
|
get_producer
|
r3w0p/bobocep
| 5
|
python
|
def get_producer(self) -> ActionProducer:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._producer
|
def get_producer(self) -> ActionProducer:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Receiver.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._producer<|docstring|>:raises RuntimeError: Attempting access before configuration.
:return: The Receiver.<|endoftext|>
|
308a166e9a4d9df3a9ef1d9475e873f0783caaab2faa3865e0c4106070bfb0be
|
def get_forwarder(self) -> ActionForwarder:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Forwarder.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._forwarder
|
:raises RuntimeError: Attempting access before configuration.
:return: The Forwarder.
|
bobocep/setup/bobo_setup.py
|
get_forwarder
|
r3w0p/bobocep
| 5
|
python
|
def get_forwarder(self) -> ActionForwarder:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Forwarder.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._forwarder
|
def get_forwarder(self) -> ActionForwarder:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The Forwarder.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._forwarder<|docstring|>:raises RuntimeError: Attempting access before configuration.
:return: The Forwarder.<|endoftext|>
|
df352bc2d07905667d7d3dfc5edb9c33f2072547738daa9fa0e1f5ac8cc2dd09
|
def get_distributed(self) -> BoboDistManager:
'\n :raises RuntimeError: Attempting access before configuration.\n :raises RuntimeError: Distributed was not configured.\n\n :return: The distrubted manager.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
elif (not self._distributed):
raise RuntimeError('Distributed was not configured.')
return self._manager
|
:raises RuntimeError: Attempting access before configuration.
:raises RuntimeError: Distributed was not configured.
:return: The distrubted manager.
|
bobocep/setup/bobo_setup.py
|
get_distributed
|
r3w0p/bobocep
| 5
|
python
|
def get_distributed(self) -> BoboDistManager:
'\n :raises RuntimeError: Attempting access before configuration.\n :raises RuntimeError: Distributed was not configured.\n\n :return: The distrubted manager.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
elif (not self._distributed):
raise RuntimeError('Distributed was not configured.')
return self._manager
|
def get_distributed(self) -> BoboDistManager:
'\n :raises RuntimeError: Attempting access before configuration.\n :raises RuntimeError: Distributed was not configured.\n\n :return: The distrubted manager.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
elif (not self._distributed):
raise RuntimeError('Distributed was not configured.')
return self._manager<|docstring|>:raises RuntimeError: Attempting access before configuration.
:raises RuntimeError: Distributed was not configured.
:return: The distrubted manager.<|endoftext|>
|
11d8ae614b85d34847d309d998f43e6c657140869ef64a835eee34b8a11c914b
|
def get_null_data_generator(self) -> BoboNullDataGenerator:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The null data generator, or None if one was not configured\n during setup.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._null_data_generator
|
:raises RuntimeError: Attempting access before configuration.
:return: The null data generator, or None if one was not configured
during setup.
|
bobocep/setup/bobo_setup.py
|
get_null_data_generator
|
r3w0p/bobocep
| 5
|
python
|
def get_null_data_generator(self) -> BoboNullDataGenerator:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The null data generator, or None if one was not configured\n during setup.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._null_data_generator
|
def get_null_data_generator(self) -> BoboNullDataGenerator:
'\n :raises RuntimeError: Attempting access before configuration.\n\n :return: The null data generator, or None if one was not configured\n during setup.\n '
with self._lock:
if (not self._configured):
raise RuntimeError('Setup must be configured first.')
return self._null_data_generator<|docstring|>:raises RuntimeError: Attempting access before configuration.
:return: The null data generator, or None if one was not configured
during setup.<|endoftext|>
|
5d839aafc33bff6482d62b6cc6dc4fda20d40f8e3fb626c868b58baee7e32fbb
|
def get_complex_events(self) -> List[BoboComplexEvent]:
'\n :return: A list of complex event definitions currently in setup.\n '
with self._lock:
if self.is_inactive():
return self._event_defs[:]
|
:return: A list of complex event definitions currently in setup.
|
bobocep/setup/bobo_setup.py
|
get_complex_events
|
r3w0p/bobocep
| 5
|
python
|
def get_complex_events(self) -> List[BoboComplexEvent]:
'\n \n '
with self._lock:
if self.is_inactive():
return self._event_defs[:]
|
def get_complex_events(self) -> List[BoboComplexEvent]:
'\n \n '
with self._lock:
if self.is_inactive():
return self._event_defs[:]<|docstring|>:return: A list of complex event definitions currently in setup.<|endoftext|>
|
16e28b16f73eb40ca333dac131dbcce90a83293d63240b29066ad978e184b7ec
|
def add_complex_event(self, event_def: BoboComplexEvent) -> None:
'\n Adds a complex event definition to the setup.\n\n :param event_def: The complex event definition.\n :type event_def: BoboComplexEvent\n '
with self._lock:
if self.is_inactive():
self._event_defs.append(event_def)
|
Adds a complex event definition to the setup.
:param event_def: The complex event definition.
:type event_def: BoboComplexEvent
|
bobocep/setup/bobo_setup.py
|
add_complex_event
|
r3w0p/bobocep
| 5
|
python
|
def add_complex_event(self, event_def: BoboComplexEvent) -> None:
'\n Adds a complex event definition to the setup.\n\n :param event_def: The complex event definition.\n :type event_def: BoboComplexEvent\n '
with self._lock:
if self.is_inactive():
self._event_defs.append(event_def)
|
def add_complex_event(self, event_def: BoboComplexEvent) -> None:
'\n Adds a complex event definition to the setup.\n\n :param event_def: The complex event definition.\n :type event_def: BoboComplexEvent\n '
with self._lock:
if self.is_inactive():
self._event_defs.append(event_def)<|docstring|>Adds a complex event definition to the setup.
:param event_def: The complex event definition.
:type event_def: BoboComplexEvent<|endoftext|>
|
fafdcb5dd7ecb1b37d8065e671dd5fcb2c1848374d9f7a48d94ccdd589fe3327
|
def config_receiver(self, validator: BoboValidator) -> None:
'\n Configure the Receiver.\n\n :param validator: The validator to use in the Receiver.\n :type validator: BoboValidator\n '
with self._lock:
if self.is_inactive():
self._validator = validator
|
Configure the Receiver.
:param validator: The validator to use in the Receiver.
:type validator: BoboValidator
|
bobocep/setup/bobo_setup.py
|
config_receiver
|
r3w0p/bobocep
| 5
|
python
|
def config_receiver(self, validator: BoboValidator) -> None:
'\n Configure the Receiver.\n\n :param validator: The validator to use in the Receiver.\n :type validator: BoboValidator\n '
with self._lock:
if self.is_inactive():
self._validator = validator
|
def config_receiver(self, validator: BoboValidator) -> None:
'\n Configure the Receiver.\n\n :param validator: The validator to use in the Receiver.\n :type validator: BoboValidator\n '
with self._lock:
if self.is_inactive():
self._validator = validator<|docstring|>Configure the Receiver.
:param validator: The validator to use in the Receiver.
:type validator: BoboValidator<|endoftext|>
|
8da6dfc45641c0fce3859b21ad38baf1372f0658f517bde3b9679dba689ee969
|
def config_producer(self, action: BoboAction) -> None:
'\n Configure the Producer.\n\n :param action: The action to execute in the Producer on CompositeEvent\n generation. If this action returns True, the\n CompositeEvent is passed to the Forwarder. Otherwise,\n it is dropped.\n :type action: BoboAction\n '
with self._lock:
if self.is_inactive():
self._action_producer = action
|
Configure the Producer.
:param action: The action to execute in the Producer on CompositeEvent
generation. If this action returns True, the
CompositeEvent is passed to the Forwarder. Otherwise,
it is dropped.
:type action: BoboAction
|
bobocep/setup/bobo_setup.py
|
config_producer
|
r3w0p/bobocep
| 5
|
python
|
def config_producer(self, action: BoboAction) -> None:
'\n Configure the Producer.\n\n :param action: The action to execute in the Producer on CompositeEvent\n generation. If this action returns True, the\n CompositeEvent is passed to the Forwarder. Otherwise,\n it is dropped.\n :type action: BoboAction\n '
with self._lock:
if self.is_inactive():
self._action_producer = action
|
def config_producer(self, action: BoboAction) -> None:
'\n Configure the Producer.\n\n :param action: The action to execute in the Producer on CompositeEvent\n generation. If this action returns True, the\n CompositeEvent is passed to the Forwarder. Otherwise,\n it is dropped.\n :type action: BoboAction\n '
with self._lock:
if self.is_inactive():
self._action_producer = action<|docstring|>Configure the Producer.
:param action: The action to execute in the Producer on CompositeEvent
generation. If this action returns True, the
CompositeEvent is passed to the Forwarder. Otherwise,
it is dropped.
:type action: BoboAction<|endoftext|>
|
a11b0a14a268f373f6c4e66e24f1dcdd0b024db86ee2c5d1049094bdd30d4383
|
def config_forwarder(self, action: BoboAction) -> None:
"\n Configure the Forwarder.\n\n :param action: The action to execute in the Forwarder. If this action\n returns True, the CompositeEvent is passed to the\n Forwarder's subscribers. Otherwise, it is dropped.\n :type action: BoboAction\n "
with self._lock:
if self.is_inactive():
self._action_forwarder = action
|
Configure the Forwarder.
:param action: The action to execute in the Forwarder. If this action
returns True, the CompositeEvent is passed to the
Forwarder's subscribers. Otherwise, it is dropped.
:type action: BoboAction
|
bobocep/setup/bobo_setup.py
|
config_forwarder
|
r3w0p/bobocep
| 5
|
python
|
def config_forwarder(self, action: BoboAction) -> None:
"\n Configure the Forwarder.\n\n :param action: The action to execute in the Forwarder. If this action\n returns True, the CompositeEvent is passed to the\n Forwarder's subscribers. Otherwise, it is dropped.\n :type action: BoboAction\n "
with self._lock:
if self.is_inactive():
self._action_forwarder = action
|
def config_forwarder(self, action: BoboAction) -> None:
"\n Configure the Forwarder.\n\n :param action: The action to execute in the Forwarder. If this action\n returns True, the CompositeEvent is passed to the\n Forwarder's subscribers. Otherwise, it is dropped.\n :type action: BoboAction\n "
with self._lock:
if self.is_inactive():
self._action_forwarder = action<|docstring|>Configure the Forwarder.
:param action: The action to execute in the Forwarder. If this action
returns True, the CompositeEvent is passed to the
Forwarder's subscribers. Otherwise, it is dropped.
:type action: BoboAction<|endoftext|>
|
1be415537953a091154fb4bbdc8e98397a049fc0c27c2be4e3658029193a3776
|
def config_distributed(self, exchange_name: str, user_name: str, parameters: ConnectionParameters) -> None:
'\n Configure the connection to the external message broker.\n\n :param exchange_name: The exchange name.\n :type exchange_name: str\n\n :param user_name: The user name.\n :type user_name: str\n\n :param parameters: Parameters to connect to a message broker.\n :type parameters: ConnectionParameters\n '
with self._lock:
if self.is_inactive():
self._distributed = True
self._exchange_name = exchange_name
self._user_name = user_name
self._parameters = parameters
|
Configure the connection to the external message broker.
:param exchange_name: The exchange name.
:type exchange_name: str
:param user_name: The user name.
:type user_name: str
:param parameters: Parameters to connect to a message broker.
:type parameters: ConnectionParameters
|
bobocep/setup/bobo_setup.py
|
config_distributed
|
r3w0p/bobocep
| 5
|
python
|
def config_distributed(self, exchange_name: str, user_name: str, parameters: ConnectionParameters) -> None:
'\n Configure the connection to the external message broker.\n\n :param exchange_name: The exchange name.\n :type exchange_name: str\n\n :param user_name: The user name.\n :type user_name: str\n\n :param parameters: Parameters to connect to a message broker.\n :type parameters: ConnectionParameters\n '
with self._lock:
if self.is_inactive():
self._distributed = True
self._exchange_name = exchange_name
self._user_name = user_name
self._parameters = parameters
|
def config_distributed(self, exchange_name: str, user_name: str, parameters: ConnectionParameters) -> None:
'\n Configure the connection to the external message broker.\n\n :param exchange_name: The exchange name.\n :type exchange_name: str\n\n :param user_name: The user name.\n :type user_name: str\n\n :param parameters: Parameters to connect to a message broker.\n :type parameters: ConnectionParameters\n '
with self._lock:
if self.is_inactive():
self._distributed = True
self._exchange_name = exchange_name
self._user_name = user_name
self._parameters = parameters<|docstring|>Configure the connection to the external message broker.
:param exchange_name: The exchange name.
:type exchange_name: str
:param user_name: The user name.
:type user_name: str
:param parameters: Parameters to connect to a message broker.
:type parameters: ConnectionParameters<|endoftext|>
|
5d7e6a7244654b9be00574fdd4a6cd0e3f875bc91593982af2f66349c8619969
|
def config_null_data(self, delay_sec: float, null_data: BoboNullData) -> None:
"\n Configure static data to be input periodically into the Receiver.\n\n :param delay_sec: The rate at which to send data. Minimum of 0.1\n seconds.\n :type delay_sec: float\n\n :param null_data: The data to send. Ensure that it is able to pass the\n Receiver's validation criteria. Otherwise, the null\n data will not enter the system.\n :type null_data: BoboNullData\n "
with self._lock:
if self.is_inactive():
self._req_null_data = True
self._null_data_delay = max(0.1, delay_sec)
self._null_data_obj = null_data
|
Configure static data to be input periodically into the Receiver.
:param delay_sec: The rate at which to send data. Minimum of 0.1
seconds.
:type delay_sec: float
:param null_data: The data to send. Ensure that it is able to pass the
Receiver's validation criteria. Otherwise, the null
data will not enter the system.
:type null_data: BoboNullData
|
bobocep/setup/bobo_setup.py
|
config_null_data
|
r3w0p/bobocep
| 5
|
python
|
def config_null_data(self, delay_sec: float, null_data: BoboNullData) -> None:
"\n Configure static data to be input periodically into the Receiver.\n\n :param delay_sec: The rate at which to send data. Minimum of 0.1\n seconds.\n :type delay_sec: float\n\n :param null_data: The data to send. Ensure that it is able to pass the\n Receiver's validation criteria. Otherwise, the null\n data will not enter the system.\n :type null_data: BoboNullData\n "
with self._lock:
if self.is_inactive():
self._req_null_data = True
self._null_data_delay = max(0.1, delay_sec)
self._null_data_obj = null_data
|
def config_null_data(self, delay_sec: float, null_data: BoboNullData) -> None:
"\n Configure static data to be input periodically into the Receiver.\n\n :param delay_sec: The rate at which to send data. Minimum of 0.1\n seconds.\n :type delay_sec: float\n\n :param null_data: The data to send. Ensure that it is able to pass the\n Receiver's validation criteria. Otherwise, the null\n data will not enter the system.\n :type null_data: BoboNullData\n "
with self._lock:
if self.is_inactive():
self._req_null_data = True
self._null_data_delay = max(0.1, delay_sec)
self._null_data_obj = null_data<|docstring|>Configure static data to be input periodically into the Receiver.
:param delay_sec: The rate at which to send data. Minimum of 0.1
seconds.
:type delay_sec: float
:param null_data: The data to send. Ensure that it is able to pass the
Receiver's validation criteria. Otherwise, the null
data will not enter the system.
:type null_data: BoboNullData<|endoftext|>
|
3920d87b2f324f53dfaa389b5d0c5904a8608d83d80ed4a519fd98dc9b2a4ecd
|
def start(self) -> None:
'Start the setup.\n\n :raises RuntimeError: Running setup when it is already active.\n :raises RuntimeError: No complex event definitions found.\n '
with self._lock:
if self.is_active():
raise RuntimeError('Setup is already active.')
if (not self._configured):
self.configure()
self._start_threads()
self._running = True
if (not self._distributed):
self._is_synced = True
|
Start the setup.
:raises RuntimeError: Running setup when it is already active.
:raises RuntimeError: No complex event definitions found.
|
bobocep/setup/bobo_setup.py
|
start
|
r3w0p/bobocep
| 5
|
python
|
def start(self) -> None:
'Start the setup.\n\n :raises RuntimeError: Running setup when it is already active.\n :raises RuntimeError: No complex event definitions found.\n '
with self._lock:
if self.is_active():
raise RuntimeError('Setup is already active.')
if (not self._configured):
self.configure()
self._start_threads()
self._running = True
if (not self._distributed):
self._is_synced = True
|
def start(self) -> None:
'Start the setup.\n\n :raises RuntimeError: Running setup when it is already active.\n :raises RuntimeError: No complex event definitions found.\n '
with self._lock:
if self.is_active():
raise RuntimeError('Setup is already active.')
if (not self._configured):
self.configure()
self._start_threads()
self._running = True
if (not self._distributed):
self._is_synced = True<|docstring|>Start the setup.
:raises RuntimeError: Running setup when it is already active.
:raises RuntimeError: No complex event definitions found.<|endoftext|>
|
15a536c414249f7428b53b7a25e8ab1bb5e106addb0f1d95afcd89f3dc8c211c
|
def cancel(self) -> None:
'Cancel the setup.'
with self._lock:
if (not self._cancelled):
self._cancelled = True
if self._running:
self._running = False
self._deactivate_tasks()
self._stop_threads()
|
Cancel the setup.
|
bobocep/setup/bobo_setup.py
|
cancel
|
r3w0p/bobocep
| 5
|
python
|
def cancel(self) -> None:
with self._lock:
if (not self._cancelled):
self._cancelled = True
if self._running:
self._running = False
self._deactivate_tasks()
self._stop_threads()
|
def cancel(self) -> None:
with self._lock:
if (not self._cancelled):
self._cancelled = True
if self._running:
self._running = False
self._deactivate_tasks()
self._stop_threads()<|docstring|>Cancel the setup.<|endoftext|>
|
927674a3a7b02b6e534b19db564b3242691e6347ded25b083fc93f5a9dbed178
|
def __init__(self):
'\n Set matplotlib style preferences\n\n Returns\n -------\n None.\n '
font_size = 14
label_size = 18
tick_size = 12
plt.style.use('seaborn')
mpl.rc('lines', linewidth=3.0)
mpl.rc('axes', titlesize=label_size, labelsize=label_size, linewidth=0.8, edgecolor='0.25')
mpl.rc('xtick', labelsize=tick_size)
mpl.rc('ytick', labelsize=tick_size)
mpl.rc('xtick.major', size=3.0)
mpl.rc('ytick.major', size=3.0)
font_style = {'family': 'sans-serif', 'sans-serif': ['CMU Sans Serif'], 'size': font_size}
mpl.rc('font', **font_style)
mpl.rc('mathtext', fontset='cm')
|
Set matplotlib style preferences
Returns
-------
None.
|
plotting_utils.py
|
__init__
|
abishek85/plotting_tools
| 0
|
python
|
def __init__(self):
'\n Set matplotlib style preferences\n\n Returns\n -------\n None.\n '
font_size = 14
label_size = 18
tick_size = 12
plt.style.use('seaborn')
mpl.rc('lines', linewidth=3.0)
mpl.rc('axes', titlesize=label_size, labelsize=label_size, linewidth=0.8, edgecolor='0.25')
mpl.rc('xtick', labelsize=tick_size)
mpl.rc('ytick', labelsize=tick_size)
mpl.rc('xtick.major', size=3.0)
mpl.rc('ytick.major', size=3.0)
font_style = {'family': 'sans-serif', 'sans-serif': ['CMU Sans Serif'], 'size': font_size}
mpl.rc('font', **font_style)
mpl.rc('mathtext', fontset='cm')
|
def __init__(self):
'\n Set matplotlib style preferences\n\n Returns\n -------\n None.\n '
font_size = 14
label_size = 18
tick_size = 12
plt.style.use('seaborn')
mpl.rc('lines', linewidth=3.0)
mpl.rc('axes', titlesize=label_size, labelsize=label_size, linewidth=0.8, edgecolor='0.25')
mpl.rc('xtick', labelsize=tick_size)
mpl.rc('ytick', labelsize=tick_size)
mpl.rc('xtick.major', size=3.0)
mpl.rc('ytick.major', size=3.0)
font_style = {'family': 'sans-serif', 'sans-serif': ['CMU Sans Serif'], 'size': font_size}
mpl.rc('font', **font_style)
mpl.rc('mathtext', fontset='cm')<|docstring|>Set matplotlib style preferences
Returns
-------
None.<|endoftext|>
|
1f2ad86d8d88658d4122cd597ae42108128bd403b2a434f9786472c784fec90b
|
def plot_colored_sinusoidal_lines(self):
'\n Plot sinusoidal lines with colors following the style color cycle.\n Use: visualize formatting\n '
L = (2 * np.pi)
x = np.linspace(0, L)
nb_colors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, nb_colors, endpoint=False)
for s in shift:
plt.plot(x, np.sin((x + s)), '-')
plt.xlim([x[0], x[(- 1)]])
plt.xlabel('$x$')
plt.ylabel('$\\sin(x)$')
plt.title('Shifted sine plots')
plt.show()
|
Plot sinusoidal lines with colors following the style color cycle.
Use: visualize formatting
|
plotting_utils.py
|
plot_colored_sinusoidal_lines
|
abishek85/plotting_tools
| 0
|
python
|
def plot_colored_sinusoidal_lines(self):
'\n Plot sinusoidal lines with colors following the style color cycle.\n Use: visualize formatting\n '
L = (2 * np.pi)
x = np.linspace(0, L)
nb_colors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, nb_colors, endpoint=False)
for s in shift:
plt.plot(x, np.sin((x + s)), '-')
plt.xlim([x[0], x[(- 1)]])
plt.xlabel('$x$')
plt.ylabel('$\\sin(x)$')
plt.title('Shifted sine plots')
plt.show()
|
def plot_colored_sinusoidal_lines(self):
'\n Plot sinusoidal lines with colors following the style color cycle.\n Use: visualize formatting\n '
L = (2 * np.pi)
x = np.linspace(0, L)
nb_colors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, nb_colors, endpoint=False)
for s in shift:
plt.plot(x, np.sin((x + s)), '-')
plt.xlim([x[0], x[(- 1)]])
plt.xlabel('$x$')
plt.ylabel('$\\sin(x)$')
plt.title('Shifted sine plots')
plt.show()<|docstring|>Plot sinusoidal lines with colors following the style color cycle.
Use: visualize formatting<|endoftext|>
|
3f0c887bcf7b46fd3ff859e2f5d4602b487b365b8734571c32f3c0ae8b764087
|
def pandas_histogram(self, dataframe, fig_size=(20, 20)):
'\n histogram from pandas dataframe or series\n\n Parameters\n ----------\n dataframe : Pandas dataframe\n fig_size: tuple, width x height\n\n Returns\n -------\n None.\n\n '
dataframe.hist(bins=50, figsize=fig_size)
plt.show()
|
histogram from pandas dataframe or series
Parameters
----------
dataframe : Pandas dataframe
fig_size: tuple, width x height
Returns
-------
None.
|
plotting_utils.py
|
pandas_histogram
|
abishek85/plotting_tools
| 0
|
python
|
def pandas_histogram(self, dataframe, fig_size=(20, 20)):
'\n histogram from pandas dataframe or series\n\n Parameters\n ----------\n dataframe : Pandas dataframe\n fig_size: tuple, width x height\n\n Returns\n -------\n None.\n\n '
dataframe.hist(bins=50, figsize=fig_size)
plt.show()
|
def pandas_histogram(self, dataframe, fig_size=(20, 20)):
'\n histogram from pandas dataframe or series\n\n Parameters\n ----------\n dataframe : Pandas dataframe\n fig_size: tuple, width x height\n\n Returns\n -------\n None.\n\n '
dataframe.hist(bins=50, figsize=fig_size)
plt.show()<|docstring|>histogram from pandas dataframe or series
Parameters
----------
dataframe : Pandas dataframe
fig_size: tuple, width x height
Returns
-------
None.<|endoftext|>
|
4e4a00e69ce74c32c0ceea15bb214bf1ea7349f006424be3a5e534650bacf2cf
|
def pandas_scatter_plot(self, dataframe, x_series, y_series, size, size_label, color):
"\n \n\n Parameters\n ----------\n dataframe : pandas dataframe\n x_series : str, series for x\n y_series : str, series for y\n size : series, determines size of scatter dot\n size_label: str, defines legend string\n color : str, determines color of scatter dot from series\n \n Returns\n -------\n None.\n\n eg.\n myplot.pandas_scatter_plot(housing_data,'latitude','longitude',\n housing_data['population']/100., 'population', 'median_house_value')\n\n "
dataframe.plot(kind='scatter', x=x_series, y=y_series, alpha=0.4, s=size, label=size_label, c=color, cmap=plt.get_cmap('viridis'), colorbar=True)
plt.show()
|
Parameters
----------
dataframe : pandas dataframe
x_series : str, series for x
y_series : str, series for y
size : series, determines size of scatter dot
size_label: str, defines legend string
color : str, determines color of scatter dot from series
Returns
-------
None.
eg.
myplot.pandas_scatter_plot(housing_data,'latitude','longitude',
housing_data['population']/100., 'population', 'median_house_value')
|
plotting_utils.py
|
pandas_scatter_plot
|
abishek85/plotting_tools
| 0
|
python
|
def pandas_scatter_plot(self, dataframe, x_series, y_series, size, size_label, color):
"\n \n\n Parameters\n ----------\n dataframe : pandas dataframe\n x_series : str, series for x\n y_series : str, series for y\n size : series, determines size of scatter dot\n size_label: str, defines legend string\n color : str, determines color of scatter dot from series\n \n Returns\n -------\n None.\n\n eg.\n myplot.pandas_scatter_plot(housing_data,'latitude','longitude',\n housing_data['population']/100., 'population', 'median_house_value')\n\n "
dataframe.plot(kind='scatter', x=x_series, y=y_series, alpha=0.4, s=size, label=size_label, c=color, cmap=plt.get_cmap('viridis'), colorbar=True)
plt.show()
|
def pandas_scatter_plot(self, dataframe, x_series, y_series, size, size_label, color):
"\n \n\n Parameters\n ----------\n dataframe : pandas dataframe\n x_series : str, series for x\n y_series : str, series for y\n size : series, determines size of scatter dot\n size_label: str, defines legend string\n color : str, determines color of scatter dot from series\n \n Returns\n -------\n None.\n\n eg.\n myplot.pandas_scatter_plot(housing_data,'latitude','longitude',\n housing_data['population']/100., 'population', 'median_house_value')\n\n "
dataframe.plot(kind='scatter', x=x_series, y=y_series, alpha=0.4, s=size, label=size_label, c=color, cmap=plt.get_cmap('viridis'), colorbar=True)
plt.show()<|docstring|>Parameters
----------
dataframe : pandas dataframe
x_series : str, series for x
y_series : str, series for y
size : series, determines size of scatter dot
size_label: str, defines legend string
color : str, determines color of scatter dot from series
Returns
-------
None.
eg.
myplot.pandas_scatter_plot(housing_data,'latitude','longitude',
housing_data['population']/100., 'population', 'median_house_value')<|endoftext|>
|
517554807a55b9d76cf4daa605fec515cf94dedb7ca691ef67469dd17607a114
|
def pandas_scatter_matrix(self, dataframe, fig_size=(12, 12)):
'\n Tool for data exploration, observing correlations\n\n Parameters\n ----------\n dataframe : pandas dataframe\n fig_size: tuple, width x height\n \n Returns\n -------\n None.\n\n eg.\n attributes = ["median_house_value","median_income","total_rooms"]\n myplot.pandas_scatter_matrix(housing_data[attributes])\n '
pd.plotting.scatter_matrix(dataframe, figsize=fig_size, diagonal='kde')
plt.show()
|
Tool for data exploration, observing correlations
Parameters
----------
dataframe : pandas dataframe
fig_size: tuple, width x height
Returns
-------
None.
eg.
attributes = ["median_house_value","median_income","total_rooms"]
myplot.pandas_scatter_matrix(housing_data[attributes])
|
plotting_utils.py
|
pandas_scatter_matrix
|
abishek85/plotting_tools
| 0
|
python
|
def pandas_scatter_matrix(self, dataframe, fig_size=(12, 12)):
'\n Tool for data exploration, observing correlations\n\n Parameters\n ----------\n dataframe : pandas dataframe\n fig_size: tuple, width x height\n \n Returns\n -------\n None.\n\n eg.\n attributes = ["median_house_value","median_income","total_rooms"]\n myplot.pandas_scatter_matrix(housing_data[attributes])\n '
pd.plotting.scatter_matrix(dataframe, figsize=fig_size, diagonal='kde')
plt.show()
|
def pandas_scatter_matrix(self, dataframe, fig_size=(12, 12)):
'\n Tool for data exploration, observing correlations\n\n Parameters\n ----------\n dataframe : pandas dataframe\n fig_size: tuple, width x height\n \n Returns\n -------\n None.\n\n eg.\n attributes = ["median_house_value","median_income","total_rooms"]\n myplot.pandas_scatter_matrix(housing_data[attributes])\n '
pd.plotting.scatter_matrix(dataframe, figsize=fig_size, diagonal='kde')
plt.show()<|docstring|>Tool for data exploration, observing correlations
Parameters
----------
dataframe : pandas dataframe
fig_size: tuple, width x height
Returns
-------
None.
eg.
attributes = ["median_house_value","median_income","total_rooms"]
myplot.pandas_scatter_matrix(housing_data[attributes])<|endoftext|>
|
9c610772444da1f1ccd36032f27db3657d186b96108d0a3343ca3a166add0b10
|
def sns_scatter_matrix(self, dataframe, hue_str=None, diag_plt='kde'):
"\n Pair-wise scatter plot between variables in data. Plots on diagonal\n can be histogram or kde.\n\n Parameters\n ----------\n dataframe : pandas dataframe\n hue_str : str, optional\n Column name in dataframe to use for color. Default is None\n diag_plt : str, optional\n Type of plot on diagonal('hist','kde'). The default is 'kde'.\n\n Returns\n -------\n None.\n \n \n eg.\n iris = sns.load_dataset('iris')\n myplot.sns_scatter_matrix(iris,'species')\n "
sns.pairplot(dataframe, hue=hue_str, palette='viridis', kind='scatter', diag_kind=diag_plt, height=2.5)
plt.show()
|
Pair-wise scatter plot between variables in data. Plots on diagonal
can be histogram or kde.
Parameters
----------
dataframe : pandas dataframe
hue_str : str, optional
Column name in dataframe to use for color. Default is None
diag_plt : str, optional
Type of plot on diagonal('hist','kde'). The default is 'kde'.
Returns
-------
None.
eg.
iris = sns.load_dataset('iris')
myplot.sns_scatter_matrix(iris,'species')
|
plotting_utils.py
|
sns_scatter_matrix
|
abishek85/plotting_tools
| 0
|
python
|
def sns_scatter_matrix(self, dataframe, hue_str=None, diag_plt='kde'):
"\n Pair-wise scatter plot between variables in data. Plots on diagonal\n can be histogram or kde.\n\n Parameters\n ----------\n dataframe : pandas dataframe\n hue_str : str, optional\n Column name in dataframe to use for color. Default is None\n diag_plt : str, optional\n Type of plot on diagonal('hist','kde'). The default is 'kde'.\n\n Returns\n -------\n None.\n \n \n eg.\n iris = sns.load_dataset('iris')\n myplot.sns_scatter_matrix(iris,'species')\n "
sns.pairplot(dataframe, hue=hue_str, palette='viridis', kind='scatter', diag_kind=diag_plt, height=2.5)
plt.show()
|
def sns_scatter_matrix(self, dataframe, hue_str=None, diag_plt='kde'):
"\n Pair-wise scatter plot between variables in data. Plots on diagonal\n can be histogram or kde.\n\n Parameters\n ----------\n dataframe : pandas dataframe\n hue_str : str, optional\n Column name in dataframe to use for color. Default is None\n diag_plt : str, optional\n Type of plot on diagonal('hist','kde'). The default is 'kde'.\n\n Returns\n -------\n None.\n \n \n eg.\n iris = sns.load_dataset('iris')\n myplot.sns_scatter_matrix(iris,'species')\n "
sns.pairplot(dataframe, hue=hue_str, palette='viridis', kind='scatter', diag_kind=diag_plt, height=2.5)
plt.show()<|docstring|>Pair-wise scatter plot between variables in data. Plots on diagonal
can be histogram or kde.
Parameters
----------
dataframe : pandas dataframe
hue_str : str, optional
Column name in dataframe to use for color. Default is None
diag_plt : str, optional
Type of plot on diagonal('hist','kde'). The default is 'kde'.
Returns
-------
None.
eg.
iris = sns.load_dataset('iris')
myplot.sns_scatter_matrix(iris,'species')<|endoftext|>
|
5d59ece747a69ab6750cab1063145c063b8c438fc0acd6479c9bbb7cabbd2d82
|
def sns_lineplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Line plot\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n df = pd.DataFrame(dict(time=np.arange(500),\n value=np.random.randn(500).cumsum()))\n myplot.sns_lineplot(df,'time','value')\n "
sns.lineplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()
|
Line plot
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
df = pd.DataFrame(dict(time=np.arange(500),
value=np.random.randn(500).cumsum()))
myplot.sns_lineplot(df,'time','value')
|
plotting_utils.py
|
sns_lineplot
|
abishek85/plotting_tools
| 0
|
python
|
def sns_lineplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Line plot\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n df = pd.DataFrame(dict(time=np.arange(500),\n value=np.random.randn(500).cumsum()))\n myplot.sns_lineplot(df,'time','value')\n "
sns.lineplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()
|
def sns_lineplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Line plot\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n df = pd.DataFrame(dict(time=np.arange(500),\n value=np.random.randn(500).cumsum()))\n myplot.sns_lineplot(df,'time','value')\n "
sns.lineplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()<|docstring|>Line plot
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
df = pd.DataFrame(dict(time=np.arange(500),
value=np.random.randn(500).cumsum()))
myplot.sns_lineplot(df,'time','value')<|endoftext|>
|
4d924f9550df71e719ca3086c60d39ff000bb53197c9ec13c686732100d5f528
|
def sns_boxenplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Boxenplot - similar to box plots but provides more information about\n the distribution as it plots more quantiles. Useful for large datasets\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n diamonds = sns.load_dataset('diamonds').sort_values('color')\n myplot.sns_boxenplot(diamonds,'color','price')\n "
sns.boxenplot(data=dataframe, x=x_name, y=y_name, hue=hue_str, palette='deep')
plt.show()
|
Boxenplot - similar to box plots but provides more information about
the distribution as it plots more quantiles. Useful for large datasets
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
diamonds = sns.load_dataset('diamonds').sort_values('color')
myplot.sns_boxenplot(diamonds,'color','price')
|
plotting_utils.py
|
sns_boxenplot
|
abishek85/plotting_tools
| 0
|
python
|
def sns_boxenplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Boxenplot - similar to box plots but provides more information about\n the distribution as it plots more quantiles. Useful for large datasets\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n diamonds = sns.load_dataset('diamonds').sort_values('color')\n myplot.sns_boxenplot(diamonds,'color','price')\n "
sns.boxenplot(data=dataframe, x=x_name, y=y_name, hue=hue_str, palette='deep')
plt.show()
|
def sns_boxenplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Boxenplot - similar to box plots but provides more information about\n the distribution as it plots more quantiles. Useful for large datasets\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n diamonds = sns.load_dataset('diamonds').sort_values('color')\n myplot.sns_boxenplot(diamonds,'color','price')\n "
sns.boxenplot(data=dataframe, x=x_name, y=y_name, hue=hue_str, palette='deep')
plt.show()<|docstring|>Boxenplot - similar to box plots but provides more information about
the distribution as it plots more quantiles. Useful for large datasets
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
diamonds = sns.load_dataset('diamonds').sort_values('color')
myplot.sns_boxenplot(diamonds,'color','price')<|endoftext|>
|
67d3db749d8780504dca6752547b0298c84855eecdd87f37b5aeda981262572f
|
def sns_barplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Barplot - categorical estimatation\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n titanic = sns.load_dataset('titanic')\n myplot.sns_barplot(titanic,'sex','survived','class')\n "
sns.barplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()
|
Barplot - categorical estimatation
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
titanic = sns.load_dataset('titanic')
myplot.sns_barplot(titanic,'sex','survived','class')
|
plotting_utils.py
|
sns_barplot
|
abishek85/plotting_tools
| 0
|
python
|
def sns_barplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Barplot - categorical estimatation\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n titanic = sns.load_dataset('titanic')\n myplot.sns_barplot(titanic,'sex','survived','class')\n "
sns.barplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()
|
def sns_barplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"\n Barplot - categorical estimatation\n\n Parameters\n ----------\n dataframe : dataframe\n data container\n x_name : str, optional\n column name for the x-axis. The default is None.\n y_name : str, optional\n column name for the y-axis. The default is None.\n hue_str : str, optional\n name of categorical data to color by. The default is None.\n\n Returns\n -------\n None.\n \n eg. \n titanic = sns.load_dataset('titanic')\n myplot.sns_barplot(titanic,'sex','survived','class')\n "
sns.barplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()<|docstring|>Barplot - categorical estimatation
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
titanic = sns.load_dataset('titanic')
myplot.sns_barplot(titanic,'sex','survived','class')<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.