body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
def setOrientation(self, ort):
"Set the orientation of the widget. May be one of 'bottom', 'top', \n 'left', or 'right'."
self.item.setOrientation(ort)
self.orientation = ort
self.setMaxDim() | 5,583,583,484,988,916,000 | Set the orientation of the widget. May be one of 'bottom', 'top',
'left', or 'right'. | scripts/pyqtgraph-develop/pyqtgraph/widgets/GradientWidget.py | setOrientation | kuldeepaman/tf-pose | python | def setOrientation(self, ort):
"Set the orientation of the widget. May be one of 'bottom', 'top', \n 'left', or 'right'."
self.item.setOrientation(ort)
self.orientation = ort
self.setMaxDim() |
@property
async def nodes(self) -> Set[neo4j.graph.Node]:
'This property is a Coroutine, which is weird, but better matches the neo4j interface.\n\n When awaited this property will execute the query and return you a Set[neo4j.graph.Node]\n containing all of the nodes which the query matched.\n '
return (await self._execute((lambda tx: set(self._func(tx).nodes)))) | -565,947,653,248,917,440 | This property is a Coroutine, which is weird, but better matches the neo4j interface.
When awaited this property will execute the query and return you a Set[neo4j.graph.Node]
containing all of the nodes which the query matched. | aiocypher/aioneo4j/graph.py | nodes | bbc/rd-cloudfit-python-aiocypher | python | @property
async def nodes(self) -> Set[neo4j.graph.Node]:
'This property is a Coroutine, which is weird, but better matches the neo4j interface.\n\n When awaited this property will execute the query and return you a Set[neo4j.graph.Node]\n containing all of the nodes which the query matched.\n '
return (await self._execute((lambda tx: set(self._func(tx).nodes)))) |
@property
async def relationships(self) -> Set[neo4j.graph.Relationship]:
'This property is a Coroutine, which is weird, but better matches the neo4j interface.\n\n When awaited this property will execute the query and return you a Set[neo4j.graph.Relationship]\n containing all of the relationships which the query matched.\n '
return (await self._execute((lambda tx: set(self._func(tx).relationships)))) | -364,903,653,325,718,100 | This property is a Coroutine, which is weird, but better matches the neo4j interface.
When awaited this property will execute the query and return you a Set[neo4j.graph.Relationship]
containing all of the relationships which the query matched. | aiocypher/aioneo4j/graph.py | relationships | bbc/rd-cloudfit-python-aiocypher | python | @property
async def relationships(self) -> Set[neo4j.graph.Relationship]:
'This property is a Coroutine, which is weird, but better matches the neo4j interface.\n\n When awaited this property will execute the query and return you a Set[neo4j.graph.Relationship]\n containing all of the relationships which the query matched.\n '
return (await self._execute((lambda tx: set(self._func(tx).relationships)))) |
def get_business_invoice_financings(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_business_invoice_financings(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponseBusinessInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_business_invoice_financings_with_http_info(**kwargs)
else:
data = self.get_business_invoice_financings_with_http_info(**kwargs)
return data | 1,579,009,774,282,378,000 | Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501
Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_business_invoice_financings(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).
:param int page_size: Quantidade total de registros por páginas.
:return: ResponseBusinessInvoiceFinancings
If the method is called asynchronously,
returns the request thread. | products_and_services_client/api/invoice_financings_api.py | get_business_invoice_financings | pitzer42/opbk-br-quickstart | python | def get_business_invoice_financings(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_business_invoice_financings(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponseBusinessInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_business_invoice_financings_with_http_info(**kwargs)
else:
data = self.get_business_invoice_financings_with_http_info(**kwargs)
return data |
def get_business_invoice_financings_with_http_info(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_business_invoice_financings_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponseBusinessInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
all_params = ['page', 'page_size']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for (key, val) in six.iteritems(params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method get_business_invoice_financings" % key))
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if ('page' in params):
query_params.append(('page', params['page']))
if ('page_size' in params):
query_params.append(('page-size', params['page_size']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = []
return self.api_client.call_api('/business-invoice-financings', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResponseBusinessInvoiceFinancings', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) | 592,169,061,374,179,800 | Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501
Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_business_invoice_financings_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).
:param int page_size: Quantidade total de registros por páginas.
:return: ResponseBusinessInvoiceFinancings
If the method is called asynchronously,
returns the request thread. | products_and_services_client/api/invoice_financings_api.py | get_business_invoice_financings_with_http_info | pitzer42/opbk-br-quickstart | python | def get_business_invoice_financings_with_http_info(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_business_invoice_financings_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponseBusinessInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
all_params = ['page', 'page_size']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for (key, val) in six.iteritems(params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method get_business_invoice_financings" % key))
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if ('page' in params):
query_params.append(('page', params['page']))
if ('page_size' in params):
query_params.append(('page-size', params['page_size']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = []
return self.api_client.call_api('/business-invoice-financings', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResponseBusinessInvoiceFinancings', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) |
def get_personal_invoice_financings(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_personal_invoice_financings(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponsePersonalInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_personal_invoice_financings_with_http_info(**kwargs)
else:
data = self.get_personal_invoice_financings_with_http_info(**kwargs)
return data | -6,094,684,954,823,276,000 | Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501
Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_personal_invoice_financings(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).
:param int page_size: Quantidade total de registros por páginas.
:return: ResponsePersonalInvoiceFinancings
If the method is called asynchronously,
returns the request thread. | products_and_services_client/api/invoice_financings_api.py | get_personal_invoice_financings | pitzer42/opbk-br-quickstart | python | def get_personal_invoice_financings(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_personal_invoice_financings(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponsePersonalInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_personal_invoice_financings_with_http_info(**kwargs)
else:
data = self.get_personal_invoice_financings_with_http_info(**kwargs)
return data |
def get_personal_invoice_financings_with_http_info(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_personal_invoice_financings_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponsePersonalInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
all_params = ['page', 'page_size']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for (key, val) in six.iteritems(params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method get_personal_invoice_financings" % key))
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if ('page' in params):
query_params.append(('page', params['page']))
if ('page_size' in params):
query_params.append(('page-size', params['page_size']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = []
return self.api_client.call_api('/personal-invoice-financings', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResponsePersonalInvoiceFinancings', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) | 280,250,529,202,642,340 | Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501
Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_personal_invoice_financings_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).
:param int page_size: Quantidade total de registros por páginas.
:return: ResponsePersonalInvoiceFinancings
If the method is called asynchronously,
returns the request thread. | products_and_services_client/api/invoice_financings_api.py | get_personal_invoice_financings_with_http_info | pitzer42/opbk-br-quickstart | python | def get_personal_invoice_financings_with_http_info(self, **kwargs):
'Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n\n Obtém a lista de Adiantamento de Recebíveis de Pessoa Natural. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_personal_invoice_financings_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param int page: Número da página que está sendo requisitada (o valor da primeira página é 1).\n :param int page_size: Quantidade total de registros por páginas.\n :return: ResponsePersonalInvoiceFinancings\n If the method is called asynchronously,\n returns the request thread.\n '
all_params = ['page', 'page_size']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for (key, val) in six.iteritems(params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method get_personal_invoice_financings" % key))
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if ('page' in params):
query_params.append(('page', params['page']))
if ('page_size' in params):
query_params.append(('page-size', params['page_size']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = []
return self.api_client.call_api('/personal-invoice-financings', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResponsePersonalInvoiceFinancings', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) |
def add_callback(self, start_cursor: int, callback: Callable[([EventLogEntry], None)]):
'Observer has started watching this run.\n Add a callback to execute on new EventLogEntrys st. id >= start_cursor\n\n Args:\n start_cursor (int): minimum event_id for the callback to execute\n callback (Callable[[EventLogEntry], None]): callback to update the Dagster UI\n '
start_cursor = check.int_param(start_cursor, 'start_cursor')
callback = check.callable_param(callback, 'callback')
with self._callback_fn_list_lock:
self._callback_fn_list.append(CallbackAfterCursor(start_cursor, callback)) | 8,486,249,283,612,698,000 | Observer has started watching this run.
Add a callback to execute on new EventLogEntrys st. id >= start_cursor
Args:
start_cursor (int): minimum event_id for the callback to execute
callback (Callable[[EventLogEntry], None]): callback to update the Dagster UI | python_modules/dagster/dagster/core/storage/event_log/polling_event_watcher.py | add_callback | AndreaGiardini/dagster | python | def add_callback(self, start_cursor: int, callback: Callable[([EventLogEntry], None)]):
'Observer has started watching this run.\n Add a callback to execute on new EventLogEntrys st. id >= start_cursor\n\n Args:\n start_cursor (int): minimum event_id for the callback to execute\n callback (Callable[[EventLogEntry], None]): callback to update the Dagster UI\n '
start_cursor = check.int_param(start_cursor, 'start_cursor')
callback = check.callable_param(callback, 'callback')
with self._callback_fn_list_lock:
self._callback_fn_list.append(CallbackAfterCursor(start_cursor, callback)) |
def remove_callback(self, callback: Callable[([EventLogEntry], None)]):
'Observer has stopped watching this run;\n Remove a callback from the list of callbacks to execute on new EventLogEntrys\n\n Also kill thread if no callbacks remaining (i.e. no Observers are watching this run_id)\n\n Args:\n callback (Callable[[EventLogEntry], None]): callback to remove from list of callbacks\n '
callback = check.callable_param(callback, 'callback')
with self._callback_fn_list_lock:
self._callback_fn_list = [callback_with_cursor for callback_with_cursor in self._callback_fn_list if (callback_with_cursor.callback != callback)]
if (not self._callback_fn_list):
self._should_thread_exit.set() | -1,103,090,747,135,853,200 | Observer has stopped watching this run;
Remove a callback from the list of callbacks to execute on new EventLogEntrys
Also kill thread if no callbacks remaining (i.e. no Observers are watching this run_id)
Args:
callback (Callable[[EventLogEntry], None]): callback to remove from list of callbacks | python_modules/dagster/dagster/core/storage/event_log/polling_event_watcher.py | remove_callback | AndreaGiardini/dagster | python | def remove_callback(self, callback: Callable[([EventLogEntry], None)]):
'Observer has stopped watching this run;\n Remove a callback from the list of callbacks to execute on new EventLogEntrys\n\n Also kill thread if no callbacks remaining (i.e. no Observers are watching this run_id)\n\n Args:\n callback (Callable[[EventLogEntry], None]): callback to remove from list of callbacks\n '
callback = check.callable_param(callback, 'callback')
with self._callback_fn_list_lock:
self._callback_fn_list = [callback_with_cursor for callback_with_cursor in self._callback_fn_list if (callback_with_cursor.callback != callback)]
if (not self._callback_fn_list):
self._should_thread_exit.set() |
def run(self):
'Polling function to update Observers with EventLogEntrys from Event Log DB.\n Wakes every POLLING_CADENCE &\n 1. executes a SELECT query to get new EventLogEntrys\n 2. fires each callback (taking into account the callback.cursor) on the new EventLogEntrys\n Uses max_index_so_far as a cursor in the DB to make sure that only new records are retrieved\n '
cursor = (- 1)
while (not self._should_thread_exit.wait(POLLING_CADENCE)):
events = self._event_log_storage.get_logs_for_run(self._run_id, cursor=cursor)
for event_record in events:
cursor += 1
with self._callback_fn_list_lock:
for callback_with_cursor in self._callback_fn_list:
if (callback_with_cursor.start_cursor < cursor):
callback_with_cursor.callback(event_record) | 6,395,378,902,785,917,000 | Polling function to update Observers with EventLogEntrys from Event Log DB.
Wakes every POLLING_CADENCE &
1. executes a SELECT query to get new EventLogEntrys
2. fires each callback (taking into account the callback.cursor) on the new EventLogEntrys
Uses max_index_so_far as a cursor in the DB to make sure that only new records are retrieved | python_modules/dagster/dagster/core/storage/event_log/polling_event_watcher.py | run | AndreaGiardini/dagster | python | def run(self):
'Polling function to update Observers with EventLogEntrys from Event Log DB.\n Wakes every POLLING_CADENCE &\n 1. executes a SELECT query to get new EventLogEntrys\n 2. fires each callback (taking into account the callback.cursor) on the new EventLogEntrys\n Uses max_index_so_far as a cursor in the DB to make sure that only new records are retrieved\n '
cursor = (- 1)
while (not self._should_thread_exit.wait(POLLING_CADENCE)):
events = self._event_log_storage.get_logs_for_run(self._run_id, cursor=cursor)
for event_record in events:
cursor += 1
with self._callback_fn_list_lock:
for callback_with_cursor in self._callback_fn_list:
if (callback_with_cursor.start_cursor < cursor):
callback_with_cursor.callback(event_record) |
def generate_device_uuid() -> int:
'\n Get unique identifier for device\n :return: Unique identifier\n '
return getnode() | -6,184,631,668,975,892,000 | Get unique identifier for device
:return: Unique identifier | src/electionguard/encrypt.py | generate_device_uuid | john-s-morgan/electionguard-python | python | def generate_device_uuid() -> int:
'\n Get unique identifier for device\n :return: Unique identifier\n '
return getnode() |
def selection_from(description: SelectionDescription, is_placeholder: bool=False, is_affirmative: bool=False) -> PlaintextBallotSelection:
'\n Construct a `BallotSelection` from a specific `SelectionDescription`.\n This function is useful for filling selections when a voter undervotes a ballot.\n It is also used to create placeholder representations when generating the `ConstantChaumPedersenProof`\n\n :param description: The `SelectionDescription` which provides the relevant `object_id`\n :param is_placeholder: Mark this selection as a placeholder value\n :param is_affirmative: Mark this selection as `yes`\n :return: A BallotSelection\n '
return PlaintextBallotSelection(description.object_id, vote=(1 if is_affirmative else 0), is_placeholder_selection=is_placeholder) | -181,945,839,889,832,260 | Construct a `BallotSelection` from a specific `SelectionDescription`.
This function is useful for filling selections when a voter undervotes a ballot.
It is also used to create placeholder representations when generating the `ConstantChaumPedersenProof`
:param description: The `SelectionDescription` which provides the relevant `object_id`
:param is_placeholder: Mark this selection as a placeholder value
:param is_affirmative: Mark this selection as `yes`
:return: A BallotSelection | src/electionguard/encrypt.py | selection_from | john-s-morgan/electionguard-python | python | def selection_from(description: SelectionDescription, is_placeholder: bool=False, is_affirmative: bool=False) -> PlaintextBallotSelection:
'\n Construct a `BallotSelection` from a specific `SelectionDescription`.\n This function is useful for filling selections when a voter undervotes a ballot.\n It is also used to create placeholder representations when generating the `ConstantChaumPedersenProof`\n\n :param description: The `SelectionDescription` which provides the relevant `object_id`\n :param is_placeholder: Mark this selection as a placeholder value\n :param is_affirmative: Mark this selection as `yes`\n :return: A BallotSelection\n '
return PlaintextBallotSelection(description.object_id, vote=(1 if is_affirmative else 0), is_placeholder_selection=is_placeholder) |
def contest_from(description: ContestDescription) -> PlaintextBallotContest:
'\n Construct a `BallotContest` from a specific `ContestDescription` with all false fields.\n This function is useful for filling contests and selections when a voter undervotes a ballot.\n\n :param description: The `ContestDescription` used to derive the well-formed `BallotContest`\n :return: a `BallotContest`\n '
selections: List[PlaintextBallotSelection] = list()
for selection_description in description.ballot_selections:
selections.append(selection_from(selection_description))
return PlaintextBallotContest(description.object_id, selections) | 511,095,952,070,037,440 | Construct a `BallotContest` from a specific `ContestDescription` with all false fields.
This function is useful for filling contests and selections when a voter undervotes a ballot.
:param description: The `ContestDescription` used to derive the well-formed `BallotContest`
:return: a `BallotContest` | src/electionguard/encrypt.py | contest_from | john-s-morgan/electionguard-python | python | def contest_from(description: ContestDescription) -> PlaintextBallotContest:
'\n Construct a `BallotContest` from a specific `ContestDescription` with all false fields.\n This function is useful for filling contests and selections when a voter undervotes a ballot.\n\n :param description: The `ContestDescription` used to derive the well-formed `BallotContest`\n :return: a `BallotContest`\n '
selections: List[PlaintextBallotSelection] = list()
for selection_description in description.ballot_selections:
selections.append(selection_from(selection_description))
return PlaintextBallotContest(description.object_id, selections) |
def encrypt_selection(selection: PlaintextBallotSelection, selection_description: SelectionDescription, elgamal_public_key: ElementModP, crypto_extended_base_hash: ElementModQ, nonce_seed: ElementModQ, is_placeholder: bool=False, should_verify_proofs: bool=True) -> Optional[CiphertextBallotSelection]:
"\n Encrypt a specific `BallotSelection` in the context of a specific `BallotContest`\n\n :param selection: the selection in the valid input form\n :param selection_description: the `SelectionDescription` from the\n `ContestDescription` which defines this selection's structure\n :param elgamal_public_key: the public key (K) used to encrypt the ballot\n :param crypto_extended_base_hash: the extended base hash of the election\n :param nonce_seed: an `ElementModQ` used as a header to seed the `Nonce` generated for this selection.\n this value can be (or derived from) the BallotContest nonce, but no relationship is required\n :param is_placeholder: specifies if this is a placeholder selection\n :param should_verify_proofs: specify if the proofs should be verified prior to returning (default True)\n "
if (not selection.is_valid(selection_description.object_id)):
log_warning(f'malformed input selection: {selection}')
return None
selection_description_hash = selection_description.crypto_hash()
nonce_sequence = Nonces(selection_description_hash, nonce_seed)
selection_nonce = nonce_sequence[selection_description.sequence_order]
disjunctive_chaum_pedersen_nonce = next(iter(nonce_sequence))
log_info(f': encrypt_selection: for {selection_description.object_id} hash: {selection_description_hash.to_hex()}')
selection_representation = selection.vote
elgamal_encryption = elgamal_encrypt(selection_representation, selection_nonce, elgamal_public_key)
if (elgamal_encryption is None):
return None
encrypted_selection = make_ciphertext_ballot_selection(object_id=selection.object_id, description_hash=selection_description_hash, ciphertext=get_optional(elgamal_encryption), elgamal_public_key=elgamal_public_key, crypto_extended_base_hash=crypto_extended_base_hash, proof_seed=disjunctive_chaum_pedersen_nonce, selection_representation=selection_representation, is_placeholder_selection=is_placeholder, nonce=selection_nonce)
if (encrypted_selection.proof is None):
return None
if (not should_verify_proofs):
return encrypted_selection
if encrypted_selection.is_valid_encryption(selection_description_hash, elgamal_public_key, crypto_extended_base_hash):
return encrypted_selection
log_warning(f'mismatching selection proof for selection {encrypted_selection.object_id}')
return None | -3,978,470,818,273,879,000 | Encrypt a specific `BallotSelection` in the context of a specific `BallotContest`
:param selection: the selection in the valid input form
:param selection_description: the `SelectionDescription` from the
`ContestDescription` which defines this selection's structure
:param elgamal_public_key: the public key (K) used to encrypt the ballot
:param crypto_extended_base_hash: the extended base hash of the election
:param nonce_seed: an `ElementModQ` used as a header to seed the `Nonce` generated for this selection.
this value can be (or derived from) the BallotContest nonce, but no relationship is required
:param is_placeholder: specifies if this is a placeholder selection
:param should_verify_proofs: specify if the proofs should be verified prior to returning (default True) | src/electionguard/encrypt.py | encrypt_selection | john-s-morgan/electionguard-python | python | def encrypt_selection(selection: PlaintextBallotSelection, selection_description: SelectionDescription, elgamal_public_key: ElementModP, crypto_extended_base_hash: ElementModQ, nonce_seed: ElementModQ, is_placeholder: bool=False, should_verify_proofs: bool=True) -> Optional[CiphertextBallotSelection]:
"\n Encrypt a specific `BallotSelection` in the context of a specific `BallotContest`\n\n :param selection: the selection in the valid input form\n :param selection_description: the `SelectionDescription` from the\n `ContestDescription` which defines this selection's structure\n :param elgamal_public_key: the public key (K) used to encrypt the ballot\n :param crypto_extended_base_hash: the extended base hash of the election\n :param nonce_seed: an `ElementModQ` used as a header to seed the `Nonce` generated for this selection.\n this value can be (or derived from) the BallotContest nonce, but no relationship is required\n :param is_placeholder: specifies if this is a placeholder selection\n :param should_verify_proofs: specify if the proofs should be verified prior to returning (default True)\n "
if (not selection.is_valid(selection_description.object_id)):
log_warning(f'malformed input selection: {selection}')
return None
selection_description_hash = selection_description.crypto_hash()
nonce_sequence = Nonces(selection_description_hash, nonce_seed)
selection_nonce = nonce_sequence[selection_description.sequence_order]
disjunctive_chaum_pedersen_nonce = next(iter(nonce_sequence))
log_info(f': encrypt_selection: for {selection_description.object_id} hash: {selection_description_hash.to_hex()}')
selection_representation = selection.vote
elgamal_encryption = elgamal_encrypt(selection_representation, selection_nonce, elgamal_public_key)
if (elgamal_encryption is None):
return None
encrypted_selection = make_ciphertext_ballot_selection(object_id=selection.object_id, description_hash=selection_description_hash, ciphertext=get_optional(elgamal_encryption), elgamal_public_key=elgamal_public_key, crypto_extended_base_hash=crypto_extended_base_hash, proof_seed=disjunctive_chaum_pedersen_nonce, selection_representation=selection_representation, is_placeholder_selection=is_placeholder, nonce=selection_nonce)
if (encrypted_selection.proof is None):
return None
if (not should_verify_proofs):
return encrypted_selection
if encrypted_selection.is_valid_encryption(selection_description_hash, elgamal_public_key, crypto_extended_base_hash):
return encrypted_selection
log_warning(f'mismatching selection proof for selection {encrypted_selection.object_id}')
return None |
def encrypt_contest(contest: PlaintextBallotContest, contest_description: ContestDescriptionWithPlaceholders, elgamal_public_key: ElementModP, crypto_extended_base_hash: ElementModQ, nonce_seed: ElementModQ, should_verify_proofs: bool=True) -> Optional[CiphertextBallotContest]:
"\n Encrypt a specific `BallotContest` in the context of a specific `Ballot`.\n\n This method accepts a contest representation that only includes `True` selections.\n It will fill missing selections for a contest with `False` values, and generate `placeholder`\n selections to represent the number of seats available for a given contest. By adding `placeholder`\n votes\n\n :param contest: the contest in the valid input form\n :param contest_description: the `ContestDescriptionWithPlaceholders`\n from the `ContestDescription` which defines this contest's structure\n :param elgamal_public_key: the public key (k) used to encrypt the ballot\n :param crypto_extended_base_hash: the extended base hash of the election\n :param nonce_seed: an `ElementModQ` used as a header to seed the `Nonce` generated for this contest.\n this value can be (or derived from) the Ballot nonce, but no relationship is required\n :param should_verify_proofs: specify if the proofs should be verified prior to returning (default True)\n "
if (not contest.is_valid(contest_description.object_id, len(contest_description.ballot_selections), contest_description.number_elected, contest_description.votes_allowed)):
log_warning(f'malformed input contest: {contest}')
return None
if (not contest_description.is_valid()):
log_warning(f'malformed contest description: {contest_description}')
return None
contest_description_hash = contest_description.crypto_hash()
nonce_sequence = Nonces(contest_description_hash, nonce_seed)
contest_nonce = nonce_sequence[contest_description.sequence_order]
chaum_pedersen_nonce = next(iter(nonce_sequence))
encrypted_selections: List[CiphertextBallotSelection] = list()
selection_count = 0
for description in contest_description.ballot_selections:
has_selection = False
encrypted_selection = None
for selection in contest.ballot_selections:
if (selection.object_id == description.object_id):
has_selection = True
selection_count += selection.vote
encrypted_selection = encrypt_selection(selection, description, elgamal_public_key, crypto_extended_base_hash, contest_nonce)
break
if (not has_selection):
encrypted_selection = encrypt_selection(selection_from(description), description, elgamal_public_key, crypto_extended_base_hash, contest_nonce)
if (encrypted_selection is None):
return None
encrypted_selections.append(get_optional(encrypted_selection))
for placeholder in contest_description.placeholder_selections:
select_placeholder = False
if (selection_count < contest_description.number_elected):
select_placeholder = True
selection_count += 1
encrypted_selection = encrypt_selection(selection=selection_from(description=placeholder, is_placeholder=True, is_affirmative=select_placeholder), selection_description=placeholder, elgamal_public_key=elgamal_public_key, crypto_extended_base_hash=crypto_extended_base_hash, nonce_seed=contest_nonce, is_placeholder=True, should_verify_proofs=True)
if (encrypted_selection is None):
return None
encrypted_selections.append(get_optional(encrypted_selection))
if ((contest_description.votes_allowed is not None) and (selection_count < contest_description.votes_allowed)):
log_warning('mismatching selection count: only n-of-m style elections are currently supported')
encrypted_contest = make_ciphertext_ballot_contest(object_id=contest.object_id, description_hash=contest_description_hash, ballot_selections=encrypted_selections, elgamal_public_key=elgamal_public_key, crypto_extended_base_hash=crypto_extended_base_hash, proof_seed=chaum_pedersen_nonce, number_elected=contest_description.number_elected, nonce=contest_nonce)
if ((encrypted_contest is None) or (encrypted_contest.proof is None)):
return None
if (not should_verify_proofs):
return encrypted_contest
if encrypted_contest.is_valid_encryption(contest_description_hash, elgamal_public_key, crypto_extended_base_hash):
return encrypted_contest
log_warning(f'mismatching contest proof for contest {encrypted_contest.object_id}')
return None | 8,492,002,618,950,993,000 | Encrypt a specific `BallotContest` in the context of a specific `Ballot`.
This method accepts a contest representation that only includes `True` selections.
It will fill missing selections for a contest with `False` values, and generate `placeholder`
selections to represent the number of seats available for a given contest. By adding `placeholder`
votes
:param contest: the contest in the valid input form
:param contest_description: the `ContestDescriptionWithPlaceholders`
from the `ContestDescription` which defines this contest's structure
:param elgamal_public_key: the public key (k) used to encrypt the ballot
:param crypto_extended_base_hash: the extended base hash of the election
:param nonce_seed: an `ElementModQ` used as a header to seed the `Nonce` generated for this contest.
this value can be (or derived from) the Ballot nonce, but no relationship is required
:param should_verify_proofs: specify if the proofs should be verified prior to returning (default True) | src/electionguard/encrypt.py | encrypt_contest | john-s-morgan/electionguard-python | python | def encrypt_contest(contest: PlaintextBallotContest, contest_description: ContestDescriptionWithPlaceholders, elgamal_public_key: ElementModP, crypto_extended_base_hash: ElementModQ, nonce_seed: ElementModQ, should_verify_proofs: bool=True) -> Optional[CiphertextBallotContest]:
"\n Encrypt a specific `BallotContest` in the context of a specific `Ballot`.\n\n This method accepts a contest representation that only includes `True` selections.\n It will fill missing selections for a contest with `False` values, and generate `placeholder`\n selections to represent the number of seats available for a given contest. By adding `placeholder`\n votes\n\n :param contest: the contest in the valid input form\n :param contest_description: the `ContestDescriptionWithPlaceholders`\n from the `ContestDescription` which defines this contest's structure\n :param elgamal_public_key: the public key (k) used to encrypt the ballot\n :param crypto_extended_base_hash: the extended base hash of the election\n :param nonce_seed: an `ElementModQ` used as a header to seed the `Nonce` generated for this contest.\n this value can be (or derived from) the Ballot nonce, but no relationship is required\n :param should_verify_proofs: specify if the proofs should be verified prior to returning (default True)\n "
if (not contest.is_valid(contest_description.object_id, len(contest_description.ballot_selections), contest_description.number_elected, contest_description.votes_allowed)):
log_warning(f'malformed input contest: {contest}')
return None
if (not contest_description.is_valid()):
log_warning(f'malformed contest description: {contest_description}')
return None
contest_description_hash = contest_description.crypto_hash()
nonce_sequence = Nonces(contest_description_hash, nonce_seed)
contest_nonce = nonce_sequence[contest_description.sequence_order]
chaum_pedersen_nonce = next(iter(nonce_sequence))
encrypted_selections: List[CiphertextBallotSelection] = list()
selection_count = 0
for description in contest_description.ballot_selections:
has_selection = False
encrypted_selection = None
for selection in contest.ballot_selections:
if (selection.object_id == description.object_id):
has_selection = True
selection_count += selection.vote
encrypted_selection = encrypt_selection(selection, description, elgamal_public_key, crypto_extended_base_hash, contest_nonce)
break
if (not has_selection):
encrypted_selection = encrypt_selection(selection_from(description), description, elgamal_public_key, crypto_extended_base_hash, contest_nonce)
if (encrypted_selection is None):
return None
encrypted_selections.append(get_optional(encrypted_selection))
for placeholder in contest_description.placeholder_selections:
select_placeholder = False
if (selection_count < contest_description.number_elected):
select_placeholder = True
selection_count += 1
encrypted_selection = encrypt_selection(selection=selection_from(description=placeholder, is_placeholder=True, is_affirmative=select_placeholder), selection_description=placeholder, elgamal_public_key=elgamal_public_key, crypto_extended_base_hash=crypto_extended_base_hash, nonce_seed=contest_nonce, is_placeholder=True, should_verify_proofs=True)
if (encrypted_selection is None):
return None
encrypted_selections.append(get_optional(encrypted_selection))
if ((contest_description.votes_allowed is not None) and (selection_count < contest_description.votes_allowed)):
log_warning('mismatching selection count: only n-of-m style elections are currently supported')
encrypted_contest = make_ciphertext_ballot_contest(object_id=contest.object_id, description_hash=contest_description_hash, ballot_selections=encrypted_selections, elgamal_public_key=elgamal_public_key, crypto_extended_base_hash=crypto_extended_base_hash, proof_seed=chaum_pedersen_nonce, number_elected=contest_description.number_elected, nonce=contest_nonce)
if ((encrypted_contest is None) or (encrypted_contest.proof is None)):
return None
if (not should_verify_proofs):
return encrypted_contest
if encrypted_contest.is_valid_encryption(contest_description_hash, elgamal_public_key, crypto_extended_base_hash):
return encrypted_contest
log_warning(f'mismatching contest proof for contest {encrypted_contest.object_id}')
return None |
def encrypt_ballot(ballot: PlaintextBallot, internal_manifest: InternalManifest, context: CiphertextElectionContext, encryption_seed: ElementModQ, nonce: Optional[ElementModQ]=None, should_verify_proofs: bool=True) -> Optional[CiphertextBallot]:
"\n Encrypt a specific `Ballot` in the context of a specific `CiphertextElectionContext`.\n\n This method accepts a ballot representation that only includes `True` selections.\n It will fill missing selections for a contest with `False` values, and generate `placeholder`\n selections to represent the number of seats available for a given contest.\n\n This method also allows for ballots to exclude passing contests for which the voter made no selections.\n It will fill missing contests with `False` selections and generate `placeholder` selections that are marked `True`.\n\n :param ballot: the ballot in the valid input form\n :param internal_manifest: the `InternalManifest` which defines this ballot's structure\n :param context: all the cryptographic context for the election\n :param encryption_seed: Hash from previous ballot or starting hash from device\n :param nonce: an optional `int` used to seed the `Nonce` generated for this contest\n if this value is not provided, the secret generating mechanism of the OS provides its own\n :param should_verify_proofs: specify if the proofs should be verified prior to returning (default True)\n "
style = internal_manifest.get_ballot_style(ballot.style_id)
if (not ballot.is_valid(style.object_id)):
log_warning(f'malformed input ballot: {ballot}')
return None
random_master_nonce = get_or_else_optional_func(nonce, (lambda : rand_q()))
nonce_seed = CiphertextBallot.nonce_seed(internal_manifest.manifest_hash, ballot.object_id, random_master_nonce)
log_info(f': manifest_hash : {internal_manifest.manifest_hash.to_hex()}')
log_info(f': encryption_seed : {encryption_seed.to_hex()}')
encrypted_contests = encrypt_ballot_contests(ballot, internal_manifest, context, nonce_seed)
if (encrypted_contests is None):
return None
encrypted_ballot = make_ciphertext_ballot(ballot.object_id, ballot.style_id, internal_manifest.manifest_hash, encryption_seed, encrypted_contests, random_master_nonce)
if (not encrypted_ballot.code):
return None
if (not should_verify_proofs):
return encrypted_ballot
if encrypted_ballot.is_valid_encryption(internal_manifest.manifest_hash, context.elgamal_public_key, context.crypto_extended_base_hash):
return encrypted_ballot
return None | -711,263,883,848,211,600 | Encrypt a specific `Ballot` in the context of a specific `CiphertextElectionContext`.
This method accepts a ballot representation that only includes `True` selections.
It will fill missing selections for a contest with `False` values, and generate `placeholder`
selections to represent the number of seats available for a given contest.
This method also allows for ballots to exclude passing contests for which the voter made no selections.
It will fill missing contests with `False` selections and generate `placeholder` selections that are marked `True`.
:param ballot: the ballot in the valid input form
:param internal_manifest: the `InternalManifest` which defines this ballot's structure
:param context: all the cryptographic context for the election
:param encryption_seed: Hash from previous ballot or starting hash from device
:param nonce: an optional `int` used to seed the `Nonce` generated for this contest
if this value is not provided, the secret generating mechanism of the OS provides its own
:param should_verify_proofs: specify if the proofs should be verified prior to returning (default True) | src/electionguard/encrypt.py | encrypt_ballot | john-s-morgan/electionguard-python | python | def encrypt_ballot(ballot: PlaintextBallot, internal_manifest: InternalManifest, context: CiphertextElectionContext, encryption_seed: ElementModQ, nonce: Optional[ElementModQ]=None, should_verify_proofs: bool=True) -> Optional[CiphertextBallot]:
"\n Encrypt a specific `Ballot` in the context of a specific `CiphertextElectionContext`.\n\n This method accepts a ballot representation that only includes `True` selections.\n It will fill missing selections for a contest with `False` values, and generate `placeholder`\n selections to represent the number of seats available for a given contest.\n\n This method also allows for ballots to exclude passing contests for which the voter made no selections.\n It will fill missing contests with `False` selections and generate `placeholder` selections that are marked `True`.\n\n :param ballot: the ballot in the valid input form\n :param internal_manifest: the `InternalManifest` which defines this ballot's structure\n :param context: all the cryptographic context for the election\n :param encryption_seed: Hash from previous ballot or starting hash from device\n :param nonce: an optional `int` used to seed the `Nonce` generated for this contest\n if this value is not provided, the secret generating mechanism of the OS provides its own\n :param should_verify_proofs: specify if the proofs should be verified prior to returning (default True)\n "
style = internal_manifest.get_ballot_style(ballot.style_id)
if (not ballot.is_valid(style.object_id)):
log_warning(f'malformed input ballot: {ballot}')
return None
random_master_nonce = get_or_else_optional_func(nonce, (lambda : rand_q()))
nonce_seed = CiphertextBallot.nonce_seed(internal_manifest.manifest_hash, ballot.object_id, random_master_nonce)
log_info(f': manifest_hash : {internal_manifest.manifest_hash.to_hex()}')
log_info(f': encryption_seed : {encryption_seed.to_hex()}')
encrypted_contests = encrypt_ballot_contests(ballot, internal_manifest, context, nonce_seed)
if (encrypted_contests is None):
return None
encrypted_ballot = make_ciphertext_ballot(ballot.object_id, ballot.style_id, internal_manifest.manifest_hash, encryption_seed, encrypted_contests, random_master_nonce)
if (not encrypted_ballot.code):
return None
if (not should_verify_proofs):
return encrypted_ballot
if encrypted_ballot.is_valid_encryption(internal_manifest.manifest_hash, context.elgamal_public_key, context.crypto_extended_base_hash):
return encrypted_ballot
return None |
def encrypt_ballot_contests(ballot: PlaintextBallot, description: InternalManifest, context: CiphertextElectionContext, nonce_seed: ElementModQ) -> Optional[List[CiphertextBallotContest]]:
'Encrypt contests from a plaintext ballot with a specific style'
encrypted_contests: List[CiphertextBallotContest] = []
for ballot_style_contest in description.get_contests_for(ballot.style_id):
use_contest = None
for contest in ballot.contests:
if (contest.object_id == ballot_style_contest.object_id):
use_contest = contest
break
if (not use_contest):
use_contest = contest_from(ballot_style_contest)
encrypted_contest = encrypt_contest(use_contest, ballot_style_contest, context.elgamal_public_key, context.crypto_extended_base_hash, nonce_seed)
if (encrypted_contest is None):
return None
encrypted_contests.append(get_optional(encrypted_contest))
return encrypted_contests | -1,018,229,742,560,874,900 | Encrypt contests from a plaintext ballot with a specific style | src/electionguard/encrypt.py | encrypt_ballot_contests | john-s-morgan/electionguard-python | python | def encrypt_ballot_contests(ballot: PlaintextBallot, description: InternalManifest, context: CiphertextElectionContext, nonce_seed: ElementModQ) -> Optional[List[CiphertextBallotContest]]:
encrypted_contests: List[CiphertextBallotContest] = []
for ballot_style_contest in description.get_contests_for(ballot.style_id):
use_contest = None
for contest in ballot.contests:
if (contest.object_id == ballot_style_contest.object_id):
use_contest = contest
break
if (not use_contest):
use_contest = contest_from(ballot_style_contest)
encrypted_contest = encrypt_contest(use_contest, ballot_style_contest, context.elgamal_public_key, context.crypto_extended_base_hash, nonce_seed)
if (encrypted_contest is None):
return None
encrypted_contests.append(get_optional(encrypted_contest))
return encrypted_contests |
def get_hash(self) -> ElementModQ:
'\n Get hash for encryption device\n :return: Starting hash\n '
return get_hash_for_device(self.device_id, self.session_id, self.launch_code, self.location) | -6,686,709,131,770,202,000 | Get hash for encryption device
:return: Starting hash | src/electionguard/encrypt.py | get_hash | john-s-morgan/electionguard-python | python | def get_hash(self) -> ElementModQ:
'\n Get hash for encryption device\n :return: Starting hash\n '
return get_hash_for_device(self.device_id, self.session_id, self.launch_code, self.location) |
def get_timestamp(self) -> int:
'\n Get the current timestamp in utc\n '
return int(datetime.utcnow().timestamp()) | 2,224,961,735,383,121,000 | Get the current timestamp in utc | src/electionguard/encrypt.py | get_timestamp | john-s-morgan/electionguard-python | python | def get_timestamp(self) -> int:
'\n \n '
return int(datetime.utcnow().timestamp()) |
def encrypt(self, ballot: PlaintextBallot) -> Optional[CiphertextBallot]:
'\n Encrypt the specified ballot using the cached election context.\n '
log_info(f' encrypt: objectId: {ballot.object_id}')
encrypted_ballot = encrypt_ballot(ballot, self._internal_manifest, self._context, self._encryption_seed)
if ((encrypted_ballot is not None) and (encrypted_ballot.code is not None)):
self._encryption_seed = encrypted_ballot.code
return encrypted_ballot | 4,068,697,592,877,654,500 | Encrypt the specified ballot using the cached election context. | src/electionguard/encrypt.py | encrypt | john-s-morgan/electionguard-python | python | def encrypt(self, ballot: PlaintextBallot) -> Optional[CiphertextBallot]:
'\n \n '
log_info(f' encrypt: objectId: {ballot.object_id}')
encrypted_ballot = encrypt_ballot(ballot, self._internal_manifest, self._context, self._encryption_seed)
if ((encrypted_ballot is not None) and (encrypted_ballot.code is not None)):
self._encryption_seed = encrypted_ballot.code
return encrypted_ballot |
def parse_arguments():
'\n Simple argument parser for the command line\n :return: The text to be edited\n '
parser = argparse.ArgumentParser(description='Receive text to be edited')
parser.add_argument('text', metavar='input text', type=str)
args = parser.parse_args()
return args.text | 3,160,303,962,437,517,300 | Simple argument parser for the command line
:return: The text to be edited | ml_editor/ml_editor.py | parse_arguments | 0105rahulk/ml-powered-applications | python | def parse_arguments():
'\n Simple argument parser for the command line\n :return: The text to be edited\n '
parser = argparse.ArgumentParser(description='Receive text to be edited')
parser.add_argument('text', metavar='input text', type=str)
args = parser.parse_args()
return args.text |
def clean_input(text):
'\n Text sanitization function\n :param text: User input text\n :return: Sanitized text, without non ascii characters\n '
return str(text.encode().decode('ascii', errors='ignore')) | 7,846,739,265,640,172,000 | Text sanitization function
:param text: User input text
:return: Sanitized text, without non ascii characters | ml_editor/ml_editor.py | clean_input | 0105rahulk/ml-powered-applications | python | def clean_input(text):
'\n Text sanitization function\n :param text: User input text\n :return: Sanitized text, without non ascii characters\n '
return str(text.encode().decode('ascii', errors='ignore')) |
def preprocess_input(text):
'\n Tokenizes text that has been sainitized\n :param text: Sanitized text\n :return: Text ready to be fed to analysis, by having sentences and words tokenized\n '
sentences = nltk.sent_tokenize(text)
tokens = [nltk.word_tokenize(sentence) for sentence in sentences]
return tokens | 1,946,638,053,518,465,300 | Tokenizes text that has been sainitized
:param text: Sanitized text
:return: Text ready to be fed to analysis, by having sentences and words tokenized | ml_editor/ml_editor.py | preprocess_input | 0105rahulk/ml-powered-applications | python | def preprocess_input(text):
'\n Tokenizes text that has been sainitized\n :param text: Sanitized text\n :return: Text ready to be fed to analysis, by having sentences and words tokenized\n '
sentences = nltk.sent_tokenize(text)
tokens = [nltk.word_tokenize(sentence) for sentence in sentences]
return tokens |
def compute_flesch_reading_ease(total_syllables, total_words, total_sentences):
'\n Computes readability score from summary statistics\n :param total_syllables: number of syllables in input text\n :param total_words: number of words in input text\n :param total_sentences: number of sentences in input text\n :return: A readability score: the lower the score, the more complex the text is deemed to be\n '
return ((206.85 - (1.015 * (total_words / total_sentences))) - (84.6 * (total_syllables / total_words))) | -7,876,112,017,044,023,000 | Computes readability score from summary statistics
:param total_syllables: number of syllables in input text
:param total_words: number of words in input text
:param total_sentences: number of sentences in input text
:return: A readability score: the lower the score, the more complex the text is deemed to be | ml_editor/ml_editor.py | compute_flesch_reading_ease | 0105rahulk/ml-powered-applications | python | def compute_flesch_reading_ease(total_syllables, total_words, total_sentences):
'\n Computes readability score from summary statistics\n :param total_syllables: number of syllables in input text\n :param total_words: number of words in input text\n :param total_sentences: number of sentences in input text\n :return: A readability score: the lower the score, the more complex the text is deemed to be\n '
return ((206.85 - (1.015 * (total_words / total_sentences))) - (84.6 * (total_syllables / total_words))) |
def get_reading_level_from_flesch(flesch_score):
'\n Thresholds taken from https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests\n :param flesch_score:\n :return: A reading level and difficulty for a given flesch score\n '
if (flesch_score < 30):
return 'Very difficult to read'
elif (flesch_score < 50):
return 'Difficult to read'
elif (flesch_score < 60):
return 'Fairly difficult to read'
elif (flesch_score < 70):
return 'Plain English'
elif (flesch_score < 80):
return 'Fairly easy to read'
elif (flesch_score < 90):
return 'Easy to read'
else:
return 'Very easy to read' | 8,117,084,314,785,368,000 | Thresholds taken from https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
:param flesch_score:
:return: A reading level and difficulty for a given flesch score | ml_editor/ml_editor.py | get_reading_level_from_flesch | 0105rahulk/ml-powered-applications | python | def get_reading_level_from_flesch(flesch_score):
'\n Thresholds taken from https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests\n :param flesch_score:\n :return: A reading level and difficulty for a given flesch score\n '
if (flesch_score < 30):
return 'Very difficult to read'
elif (flesch_score < 50):
return 'Difficult to read'
elif (flesch_score < 60):
return 'Fairly difficult to read'
elif (flesch_score < 70):
return 'Plain English'
elif (flesch_score < 80):
return 'Fairly easy to read'
elif (flesch_score < 90):
return 'Easy to read'
else:
return 'Very easy to read' |
def compute_average_word_length(tokens):
'\n Calculate word length for a sentence\n :param tokens: a list of words\n :return: The average length of words in this list\n '
word_lengths = [len(word) for word in tokens]
return (sum(word_lengths) / len(word_lengths)) | 4,506,613,735,038,787,000 | Calculate word length for a sentence
:param tokens: a list of words
:return: The average length of words in this list | ml_editor/ml_editor.py | compute_average_word_length | 0105rahulk/ml-powered-applications | python | def compute_average_word_length(tokens):
'\n Calculate word length for a sentence\n :param tokens: a list of words\n :return: The average length of words in this list\n '
word_lengths = [len(word) for word in tokens]
return (sum(word_lengths) / len(word_lengths)) |
def compute_total_average_word_length(sentence_list):
'\n Calculate average word length for multiple sentences\n :param sentence_list: a list of sentences, each being a list of words\n :return: The average length of words in this list of sentences\n '
lengths = [compute_average_word_length(tokens) for tokens in sentence_list]
return (sum(lengths) / len(lengths)) | -3,756,731,325,639,814,700 | Calculate average word length for multiple sentences
:param sentence_list: a list of sentences, each being a list of words
:return: The average length of words in this list of sentences | ml_editor/ml_editor.py | compute_total_average_word_length | 0105rahulk/ml-powered-applications | python | def compute_total_average_word_length(sentence_list):
'\n Calculate average word length for multiple sentences\n :param sentence_list: a list of sentences, each being a list of words\n :return: The average length of words in this list of sentences\n '
lengths = [compute_average_word_length(tokens) for tokens in sentence_list]
return (sum(lengths) / len(lengths)) |
def compute_total_unique_words_fraction(sentence_list):
'\n Compute fraction os unique words\n :param sentence_list: a list of sentences, each being a list of words\n :return: the fraction of unique words in the sentences\n '
all_words = [word for word_list in sentence_list for word in word_list]
unique_words = set(all_words)
return (len(unique_words) / len(all_words)) | -4,128,156,532,980,299,300 | Compute fraction os unique words
:param sentence_list: a list of sentences, each being a list of words
:return: the fraction of unique words in the sentences | ml_editor/ml_editor.py | compute_total_unique_words_fraction | 0105rahulk/ml-powered-applications | python | def compute_total_unique_words_fraction(sentence_list):
'\n Compute fraction os unique words\n :param sentence_list: a list of sentences, each being a list of words\n :return: the fraction of unique words in the sentences\n '
all_words = [word for word_list in sentence_list for word in word_list]
unique_words = set(all_words)
return (len(unique_words) / len(all_words)) |
def count_word_usage(tokens, word_list):
'\n Counts occurrences of a given list of words\n :param tokens: a list of tokens for one sentence\n :param word_list: a list of words to search for\n :return: the number of times the words appear in the list\n '
return len([word for word in tokens if (word.lower() in word_list)]) | 6,031,960,145,593,758,000 | Counts occurrences of a given list of words
:param tokens: a list of tokens for one sentence
:param word_list: a list of words to search for
:return: the number of times the words appear in the list | ml_editor/ml_editor.py | count_word_usage | 0105rahulk/ml-powered-applications | python | def count_word_usage(tokens, word_list):
'\n Counts occurrences of a given list of words\n :param tokens: a list of tokens for one sentence\n :param word_list: a list of words to search for\n :return: the number of times the words appear in the list\n '
return len([word for word in tokens if (word.lower() in word_list)]) |
def count_word_syllables(word):
'\n Count syllables in a word\n :param word: a one word string\n :return: the number of syllables according to pyphen\n '
dic = pyphen.Pyphen(lang='en_US')
hyphenated = dic.inserted(word)
return len(hyphenated.split('-')) | -6,612,760,813,597,651,000 | Count syllables in a word
:param word: a one word string
:return: the number of syllables according to pyphen | ml_editor/ml_editor.py | count_word_syllables | 0105rahulk/ml-powered-applications | python | def count_word_syllables(word):
'\n Count syllables in a word\n :param word: a one word string\n :return: the number of syllables according to pyphen\n '
dic = pyphen.Pyphen(lang='en_US')
hyphenated = dic.inserted(word)
return len(hyphenated.split('-')) |
def count_sentence_syllables(tokens):
'\n Count syllables in a sentence\n :param tokens: a list of words and potentially punctuation\n :return: the number of syllables in the sentence\n '
punctuation = '.,!?/'
return sum([count_word_syllables(word) for word in tokens if (word not in punctuation)]) | 4,886,695,117,006,768,000 | Count syllables in a sentence
:param tokens: a list of words and potentially punctuation
:return: the number of syllables in the sentence | ml_editor/ml_editor.py | count_sentence_syllables | 0105rahulk/ml-powered-applications | python | def count_sentence_syllables(tokens):
'\n Count syllables in a sentence\n :param tokens: a list of words and potentially punctuation\n :return: the number of syllables in the sentence\n '
punctuation = '.,!?/'
return sum([count_word_syllables(word) for word in tokens if (word not in punctuation)]) |
def count_total_syllables(sentence_list):
'\n Count syllables in a list of sentences\n :param sentence_list: a list of sentences, each being a list of words\n :return: the number of syllables in the sentences\n '
return sum([count_sentence_syllables(sentence) for sentence in sentence_list]) | 8,547,849,217,713,090,000 | Count syllables in a list of sentences
:param sentence_list: a list of sentences, each being a list of words
:return: the number of syllables in the sentences | ml_editor/ml_editor.py | count_total_syllables | 0105rahulk/ml-powered-applications | python | def count_total_syllables(sentence_list):
'\n Count syllables in a list of sentences\n :param sentence_list: a list of sentences, each being a list of words\n :return: the number of syllables in the sentences\n '
return sum([count_sentence_syllables(sentence) for sentence in sentence_list]) |
def count_words_per_sentence(sentence_tokens):
'\n Count words in a sentence\n :param sentence_tokens: a list of words and potentially punctuation\n :return: the number of words in the sentence\n '
punctuation = '.,!?/'
return len([word for word in sentence_tokens if (word not in punctuation)]) | -7,815,204,490,811,529,000 | Count words in a sentence
:param sentence_tokens: a list of words and potentially punctuation
:return: the number of words in the sentence | ml_editor/ml_editor.py | count_words_per_sentence | 0105rahulk/ml-powered-applications | python | def count_words_per_sentence(sentence_tokens):
'\n Count words in a sentence\n :param sentence_tokens: a list of words and potentially punctuation\n :return: the number of words in the sentence\n '
punctuation = '.,!?/'
return len([word for word in sentence_tokens if (word not in punctuation)]) |
def count_total_words(sentence_list):
'\n Count words in a list of sentences\n :param sentence_list: a list of sentences, each being a list of words\n :return: the number of words in the sentences\n '
return sum([count_words_per_sentence(sentence) for sentence in sentence_list]) | -590,611,117,762,690,600 | Count words in a list of sentences
:param sentence_list: a list of sentences, each being a list of words
:return: the number of words in the sentences | ml_editor/ml_editor.py | count_total_words | 0105rahulk/ml-powered-applications | python | def count_total_words(sentence_list):
'\n Count words in a list of sentences\n :param sentence_list: a list of sentences, each being a list of words\n :return: the number of words in the sentences\n '
return sum([count_words_per_sentence(sentence) for sentence in sentence_list]) |
def get_suggestions(sentence_list):
'\n Returns a string containing our suggestions\n :param sentence_list: a list of sentences, each being a list of words\n :return: suggestions to improve the input\n '
told_said_usage = sum((count_word_usage(tokens, ['told', 'said']) for tokens in sentence_list))
but_and_usage = sum((count_word_usage(tokens, ['but', 'and']) for tokens in sentence_list))
wh_adverbs_usage = sum((count_word_usage(tokens, ['when', 'where', 'why', 'whence', 'whereby', 'wherein', 'whereupon']) for tokens in sentence_list))
result_str = ''
adverb_usage = ('Adverb usage: %s told/said, %s but/and, %s wh adverbs' % (told_said_usage, but_and_usage, wh_adverbs_usage))
result_str += adverb_usage
average_word_length = compute_total_average_word_length(sentence_list)
unique_words_fraction = compute_total_unique_words_fraction(sentence_list)
word_stats = ('Average word length %.2f, fraction of unique words %.2f' % (average_word_length, unique_words_fraction))
result_str += '<br/>'
result_str += word_stats
number_of_syllables = count_total_syllables(sentence_list)
number_of_words = count_total_words(sentence_list)
number_of_sentences = len(sentence_list)
syllable_counts = ('%d syllables, %d words, %d sentences' % (number_of_syllables, number_of_words, number_of_sentences))
result_str += '<br/>'
result_str += syllable_counts
flesch_score = compute_flesch_reading_ease(number_of_syllables, number_of_words, number_of_sentences)
flesch = ('%d syllables, %.2f flesch score: %s' % (number_of_syllables, flesch_score, get_reading_level_from_flesch(flesch_score)))
result_str += '<br/>'
result_str += flesch
return result_str | -7,753,332,045,319,814,000 | Returns a string containing our suggestions
:param sentence_list: a list of sentences, each being a list of words
:return: suggestions to improve the input | ml_editor/ml_editor.py | get_suggestions | 0105rahulk/ml-powered-applications | python | def get_suggestions(sentence_list):
'\n Returns a string containing our suggestions\n :param sentence_list: a list of sentences, each being a list of words\n :return: suggestions to improve the input\n '
told_said_usage = sum((count_word_usage(tokens, ['told', 'said']) for tokens in sentence_list))
but_and_usage = sum((count_word_usage(tokens, ['but', 'and']) for tokens in sentence_list))
wh_adverbs_usage = sum((count_word_usage(tokens, ['when', 'where', 'why', 'whence', 'whereby', 'wherein', 'whereupon']) for tokens in sentence_list))
result_str =
adverb_usage = ('Adverb usage: %s told/said, %s but/and, %s wh adverbs' % (told_said_usage, but_and_usage, wh_adverbs_usage))
result_str += adverb_usage
average_word_length = compute_total_average_word_length(sentence_list)
unique_words_fraction = compute_total_unique_words_fraction(sentence_list)
word_stats = ('Average word length %.2f, fraction of unique words %.2f' % (average_word_length, unique_words_fraction))
result_str += '<br/>'
result_str += word_stats
number_of_syllables = count_total_syllables(sentence_list)
number_of_words = count_total_words(sentence_list)
number_of_sentences = len(sentence_list)
syllable_counts = ('%d syllables, %d words, %d sentences' % (number_of_syllables, number_of_words, number_of_sentences))
result_str += '<br/>'
result_str += syllable_counts
flesch_score = compute_flesch_reading_ease(number_of_syllables, number_of_words, number_of_sentences)
flesch = ('%d syllables, %.2f flesch score: %s' % (number_of_syllables, flesch_score, get_reading_level_from_flesch(flesch_score)))
result_str += '<br/>'
result_str += flesch
return result_str |
def get_recommendations_from_input(txt):
'\n Cleans, preprocesses, and generates heuristic suggestion for input string\n :param txt: Input text\n :return: Suggestions for a given text input\n '
processed = clean_input(txt)
tokenized_sentences = preprocess_input(processed)
suggestions = get_suggestions(tokenized_sentences)
return suggestions | -3,809,558,853,786,648,000 | Cleans, preprocesses, and generates heuristic suggestion for input string
:param txt: Input text
:return: Suggestions for a given text input | ml_editor/ml_editor.py | get_recommendations_from_input | 0105rahulk/ml-powered-applications | python | def get_recommendations_from_input(txt):
'\n Cleans, preprocesses, and generates heuristic suggestion for input string\n :param txt: Input text\n :return: Suggestions for a given text input\n '
processed = clean_input(txt)
tokenized_sentences = preprocess_input(processed)
suggestions = get_suggestions(tokenized_sentences)
return suggestions |
@api_bp.route('/all')
def all_storage():
'Get all storage in JSON.'
trees = current_app.trees
mounts = MountTree()
for (prefix, tree) in six.iteritems(trees):
for (path, storage) in tree.iter_storage():
mounts.mount(((prefix + '/') + path), storage)
def dfs(node):
children = node.children
if children:
ret = []
for name in sorted(six.iterkeys(children)):
child = children[name]
child_ret = dfs(child)
if child_ret:
ret.append((name, child_ret))
if ret:
return ret
data = node.data
if data:
return data.to_dict()
return jsonify((dfs(mounts.root) or [])) | 3,075,368,538,526,878,000 | Get all storage in JSON. | mlcomp/board/views/api.py | all_storage | korepwx/mlcomp | python | @api_bp.route('/all')
def all_storage():
trees = current_app.trees
mounts = MountTree()
for (prefix, tree) in six.iteritems(trees):
for (path, storage) in tree.iter_storage():
mounts.mount(((prefix + '/') + path), storage)
def dfs(node):
children = node.children
if children:
ret = []
for name in sorted(six.iterkeys(children)):
child = children[name]
child_ret = dfs(child)
if child_ret:
ret.append((name, child_ret))
if ret:
return ret
data = node.data
if data:
return data.to_dict()
return jsonify((dfs(mounts.root) or [])) |
def __call__(self, original_image):
'\n Args:\n original_image (np.ndarray): an image of shape (H, W, C) (in BGR order).\n\n Returns:\n predictions (dict):\n the output of the model for one image only.\n See :doc:`/tutorials/models` for details about the format.\n '
with torch.no_grad():
if (self.input_format == 'RGB'):
original_image = original_image[:, :, ::(- 1)]
(height, width) = original_image.shape[:2]
image = original_image
for tfm_gen in self.transform_gen:
image = tfm_gen.get_transform(image).apply_image(image)
image = torch.as_tensor(image.astype('float32').transpose(2, 0, 1))
inputs = {'image': image, 'height': height, 'width': width}
predictions = self.model([inputs])[0]
return predictions | -5,284,906,396,777,502,000 | Args:
original_image (np.ndarray): an image of shape (H, W, C) (in BGR order).
Returns:
predictions (dict):
the output of the model for one image only.
See :doc:`/tutorials/models` for details about the format. | cvpods/engine/predictor.py | __call__ | reinforcementdriving/cvpods | python | def __call__(self, original_image):
'\n Args:\n original_image (np.ndarray): an image of shape (H, W, C) (in BGR order).\n\n Returns:\n predictions (dict):\n the output of the model for one image only.\n See :doc:`/tutorials/models` for details about the format.\n '
with torch.no_grad():
if (self.input_format == 'RGB'):
original_image = original_image[:, :, ::(- 1)]
(height, width) = original_image.shape[:2]
image = original_image
for tfm_gen in self.transform_gen:
image = tfm_gen.get_transform(image).apply_image(image)
image = torch.as_tensor(image.astype('float32').transpose(2, 0, 1))
inputs = {'image': image, 'height': height, 'width': width}
predictions = self.model([inputs])[0]
return predictions |
def checkResponseCorrectnessFromNodes(receivedMsgs: Iterable, reqId: int, fValue: int) -> bool:
'\n the client must get at least :math:`f+1` responses\n '
msgs = [(msg[f.RESULT.nm][f.REQ_ID.nm], msg[f.RESULT.nm][f.IDENTIFIER.nm]) for msg in getRepliesFromClientInbox(receivedMsgs, reqId)]
groupedMsgs = {}
for tpl in msgs:
groupedMsgs[tpl] = (groupedMsgs.get(tpl, 0) + 1)
assert (max(groupedMsgs.values()) >= (fValue + 1)) | 3,340,106,731,286,783,500 | the client must get at least :math:`f+1` responses | plenum/test/helper.py | checkResponseCorrectnessFromNodes | AYCH-Inc/aych.hyper.tolerant | python | def checkResponseCorrectnessFromNodes(receivedMsgs: Iterable, reqId: int, fValue: int) -> bool:
'\n \n '
msgs = [(msg[f.RESULT.nm][f.REQ_ID.nm], msg[f.RESULT.nm][f.IDENTIFIER.nm]) for msg in getRepliesFromClientInbox(receivedMsgs, reqId)]
groupedMsgs = {}
for tpl in msgs:
groupedMsgs[tpl] = (groupedMsgs.get(tpl, 0) + 1)
assert (max(groupedMsgs.values()) >= (fValue + 1)) |
def sendMessage(sender: Node, reciever: Node, msg: Optional[Tuple]=None):
'\n Sends message from one node to another\n\n :param nodes:\n :param sender: sender\n :param reciever: recepient\n :param msg: optional message - by default random one generated\n :return:\n '
logger.debug('Sending msg from {} to {}'.format(sender.name, reciever.name))
msg = (msg if msg else randomMsg())
rid = sender.nodestack.getRemote(reciever.name).uid
sender.nodestack.send(msg, rid) | 6,135,663,388,558,338,000 | Sends message from one node to another
:param nodes:
:param sender: sender
:param reciever: recepient
:param msg: optional message - by default random one generated
:return: | plenum/test/helper.py | sendMessage | AYCH-Inc/aych.hyper.tolerant | python | def sendMessage(sender: Node, reciever: Node, msg: Optional[Tuple]=None):
'\n Sends message from one node to another\n\n :param nodes:\n :param sender: sender\n :param reciever: recepient\n :param msg: optional message - by default random one generated\n :return:\n '
logger.debug('Sending msg from {} to {}'.format(sender.name, reciever.name))
msg = (msg if msg else randomMsg())
rid = sender.nodestack.getRemote(reciever.name).uid
sender.nodestack.send(msg, rid) |
async def sendMessageAndCheckDelivery(sender: Node, reciever: Node, msg: Optional[Tuple]=None, method=None, customTimeout=None):
'\n Sends message from one node to another and checks that it was delivered\n\n :param sender: sender\n :param reciever: recepient\n :param msg: optional message - by default random one generated\n :param customTimeout:\n :return:\n '
logger.debug('Sending msg from {} to {}'.format(sender.name, reciever.name))
msg = (msg if msg else randomMsg())
rid = sender.nodestack.getRemote(reciever.name).uid
sender.nodestack.send(msg, rid)
timeout = (customTimeout or waits.expectedNodeToNodeMessageDeliveryTime())
(await eventually(checkMessageReceived, msg, reciever, method, retryWait=0.1, timeout=timeout, ratchetSteps=10)) | -8,746,987,848,750,174,000 | Sends message from one node to another and checks that it was delivered
:param sender: sender
:param reciever: recepient
:param msg: optional message - by default random one generated
:param customTimeout:
:return: | plenum/test/helper.py | sendMessageAndCheckDelivery | AYCH-Inc/aych.hyper.tolerant | python | async def sendMessageAndCheckDelivery(sender: Node, reciever: Node, msg: Optional[Tuple]=None, method=None, customTimeout=None):
'\n Sends message from one node to another and checks that it was delivered\n\n :param sender: sender\n :param reciever: recepient\n :param msg: optional message - by default random one generated\n :param customTimeout:\n :return:\n '
logger.debug('Sending msg from {} to {}'.format(sender.name, reciever.name))
msg = (msg if msg else randomMsg())
rid = sender.nodestack.getRemote(reciever.name).uid
sender.nodestack.send(msg, rid)
timeout = (customTimeout or waits.expectedNodeToNodeMessageDeliveryTime())
(await eventually(checkMessageReceived, msg, reciever, method, retryWait=0.1, timeout=timeout, ratchetSteps=10)) |
def sendMessageToAll(nodes, sender: Node, msg: Optional[Tuple]=None):
'\n Sends message from one node to all others\n\n :param nodes:\n :param sender: sender\n :param msg: optional message - by default random one generated\n :return:\n '
for node in nodes:
if (node != sender):
sendMessage(sender, node, msg) | -5,977,631,795,381,608,000 | Sends message from one node to all others
:param nodes:
:param sender: sender
:param msg: optional message - by default random one generated
:return: | plenum/test/helper.py | sendMessageToAll | AYCH-Inc/aych.hyper.tolerant | python | def sendMessageToAll(nodes, sender: Node, msg: Optional[Tuple]=None):
'\n Sends message from one node to all others\n\n :param nodes:\n :param sender: sender\n :param msg: optional message - by default random one generated\n :return:\n '
for node in nodes:
if (node != sender):
sendMessage(sender, node, msg) |
async def sendMessageAndCheckDeliveryToAll(nodes, sender: Node, msg: Optional[Tuple]=None, method=None, customTimeout=None):
'\n Sends message from one node to all other and checks that it was delivered\n\n :param nodes:\n :param sender: sender\n :param msg: optional message - by default random one generated\n :param customTimeout:\n :return:\n '
customTimeout = (customTimeout or waits.expectedNodeToAllNodesMessageDeliveryTime(len(nodes)))
for node in nodes:
if (node != sender):
(await sendMessageAndCheckDelivery(sender, node, msg, method, customTimeout))
break | -4,503,784,033,855,764,500 | Sends message from one node to all other and checks that it was delivered
:param nodes:
:param sender: sender
:param msg: optional message - by default random one generated
:param customTimeout:
:return: | plenum/test/helper.py | sendMessageAndCheckDeliveryToAll | AYCH-Inc/aych.hyper.tolerant | python | async def sendMessageAndCheckDeliveryToAll(nodes, sender: Node, msg: Optional[Tuple]=None, method=None, customTimeout=None):
'\n Sends message from one node to all other and checks that it was delivered\n\n :param nodes:\n :param sender: sender\n :param msg: optional message - by default random one generated\n :param customTimeout:\n :return:\n '
customTimeout = (customTimeout or waits.expectedNodeToAllNodesMessageDeliveryTime(len(nodes)))
for node in nodes:
if (node != sender):
(await sendMessageAndCheckDelivery(sender, node, msg, method, customTimeout))
break |
def checkViewNoForNodes(nodes: Iterable[TestNode], expectedViewNo: int=None):
'\n Checks if all the given nodes have the expected view no\n\n :param nodes: The nodes to check for\n :param expectedViewNo: the view no that the nodes are expected to have\n :return:\n '
viewNos = set()
for node in nodes:
logger.debug("{}'s view no is {}".format(node, node.master_replica.viewNo))
viewNos.add(node.master_replica.viewNo)
assert (len(viewNos) == 1), 'Expected 1, but got {}. ViewNos: {}'.format(len(viewNos), [(n.name, n.master_replica.viewNo) for n in nodes])
(vNo,) = viewNos
if (expectedViewNo is not None):
assert (vNo >= expectedViewNo), 'Expected at least {}, but got {}'.format(expectedViewNo, vNo)
return vNo | 4,019,316,257,189,537,300 | Checks if all the given nodes have the expected view no
:param nodes: The nodes to check for
:param expectedViewNo: the view no that the nodes are expected to have
:return: | plenum/test/helper.py | checkViewNoForNodes | AYCH-Inc/aych.hyper.tolerant | python | def checkViewNoForNodes(nodes: Iterable[TestNode], expectedViewNo: int=None):
'\n Checks if all the given nodes have the expected view no\n\n :param nodes: The nodes to check for\n :param expectedViewNo: the view no that the nodes are expected to have\n :return:\n '
viewNos = set()
for node in nodes:
logger.debug("{}'s view no is {}".format(node, node.master_replica.viewNo))
viewNos.add(node.master_replica.viewNo)
assert (len(viewNos) == 1), 'Expected 1, but got {}. ViewNos: {}'.format(len(viewNos), [(n.name, n.master_replica.viewNo) for n in nodes])
(vNo,) = viewNos
if (expectedViewNo is not None):
assert (vNo >= expectedViewNo), 'Expected at least {}, but got {}'.format(expectedViewNo, vNo)
return vNo |
def waitForViewChange(looper, txnPoolNodeSet, expectedViewNo=None, customTimeout=None):
'\n Waits for nodes to come to same view.\n Raises exception when time is out\n '
timeout = (customTimeout or waits.expectedPoolElectionTimeout(len(txnPoolNodeSet)))
return looper.run(eventually(checkViewNoForNodes, txnPoolNodeSet, expectedViewNo, timeout=timeout)) | 6,331,853,845,034,578,000 | Waits for nodes to come to same view.
Raises exception when time is out | plenum/test/helper.py | waitForViewChange | AYCH-Inc/aych.hyper.tolerant | python | def waitForViewChange(looper, txnPoolNodeSet, expectedViewNo=None, customTimeout=None):
'\n Waits for nodes to come to same view.\n Raises exception when time is out\n '
timeout = (customTimeout or waits.expectedPoolElectionTimeout(len(txnPoolNodeSet)))
return looper.run(eventually(checkViewNoForNodes, txnPoolNodeSet, expectedViewNo, timeout=timeout)) |
def filterNodeSet(nodeSet, exclude: List[Union[(str, Node)]]):
'\n Return a set of nodes with the nodes in exclude removed.\n\n :param nodeSet: the set of nodes\n :param exclude: the list of nodes or node names to exclude\n :return: the filtered nodeSet\n '
return [n for n in nodeSet if (n not in [(nodeSet[x] if isinstance(x, str) else x) for x in exclude])] | 4,421,575,545,505,831,000 | Return a set of nodes with the nodes in exclude removed.
:param nodeSet: the set of nodes
:param exclude: the list of nodes or node names to exclude
:return: the filtered nodeSet | plenum/test/helper.py | filterNodeSet | AYCH-Inc/aych.hyper.tolerant | python | def filterNodeSet(nodeSet, exclude: List[Union[(str, Node)]]):
'\n Return a set of nodes with the nodes in exclude removed.\n\n :param nodeSet: the set of nodes\n :param exclude: the list of nodes or node names to exclude\n :return: the filtered nodeSet\n '
return [n for n in nodeSet if (n not in [(nodeSet[x] if isinstance(x, str) else x) for x in exclude])] |
def init_discarded(value=None):
'init discarded field with value and return message like representation'
discarded = []
if value:
discarded.append(value)
return invalid_index_serializer.serialize(discarded, toBytes=False) | -3,476,248,819,505,986,600 | init discarded field with value and return message like representation | plenum/test/helper.py | init_discarded | AYCH-Inc/aych.hyper.tolerant | python | def init_discarded(value=None):
discarded = []
if value:
discarded.append(value)
return invalid_index_serializer.serialize(discarded, toBytes=False) |
def set_time(self, value):
'\n Update time and run scheduled callbacks afterwards\n '
self._ts.value = value
self._log_time()
self.service() | 4,053,135,774,855,907,000 | Update time and run scheduled callbacks afterwards | plenum/test/helper.py | set_time | AYCH-Inc/aych.hyper.tolerant | python | def set_time(self, value):
'\n \n '
self._ts.value = value
self._log_time()
self.service() |
def sleep(self, seconds):
'\n Simulate sleeping for given amount of seconds, and run scheduled callbacks afterwards\n '
self.set_time((self._ts.value + seconds)) | 3,932,969,567,631,461,000 | Simulate sleeping for given amount of seconds, and run scheduled callbacks afterwards | plenum/test/helper.py | sleep | AYCH-Inc/aych.hyper.tolerant | python | def sleep(self, seconds):
'\n \n '
self.set_time((self._ts.value + seconds)) |
def advance(self):
'\n Advance time to next scheduled callback and run that callback\n '
if (not self._events):
return
event = self._pop_event()
self._ts.value = event.timestamp
self._log_time()
event.callback() | -4,289,426,136,981,135,400 | Advance time to next scheduled callback and run that callback | plenum/test/helper.py | advance | AYCH-Inc/aych.hyper.tolerant | python | def advance(self):
'\n \n '
if (not self._events):
return
event = self._pop_event()
self._ts.value = event.timestamp
self._log_time()
event.callback() |
def advance_until(self, value):
'\n Advance time in steps until required value running scheduled callbacks in process\n '
while (self._events and (self._next_timestamp() <= value)):
self.advance()
self._ts.value = value | 2,968,606,903,881,629,000 | Advance time in steps until required value running scheduled callbacks in process | plenum/test/helper.py | advance_until | AYCH-Inc/aych.hyper.tolerant | python | def advance_until(self, value):
'\n \n '
while (self._events and (self._next_timestamp() <= value)):
self.advance()
self._ts.value = value |
def run_for(self, seconds):
'\n Simulate running for given amount of seconds, running scheduled callbacks at required timestamps\n '
self.advance_until((self._ts.value + seconds)) | 8,928,512,877,692,073,000 | Simulate running for given amount of seconds, running scheduled callbacks at required timestamps | plenum/test/helper.py | run_for | AYCH-Inc/aych.hyper.tolerant | python | def run_for(self, seconds):
'\n \n '
self.advance_until((self._ts.value + seconds)) |
def wait_for(self, condition: Callable[([], bool)], timeout: Optional=None, max_iterations: int=10000):
'\n Advance time in steps until condition is reached, running scheduled callbacks in process\n Throws TimeoutError if fail to reach condition (under required timeout if defined)\n '
counter = 0
deadline = ((self._ts.value + timeout) if timeout else None)
while (self._events and (not condition()) and (counter < max_iterations)):
if (deadline and (self._next_timestamp() > deadline)):
raise TimeoutError('Failed to reach condition in required time, {} iterations passed'.format(counter))
self.advance()
counter += 1
if (not condition()):
if (not self._events):
raise TimeoutError('Condition will be never reached, {} iterations passed'.format(counter))
else:
raise TimeoutError('Failed to reach condition in {} iterations'.format(max_iterations)) | -6,568,998,434,249,261,000 | Advance time in steps until condition is reached, running scheduled callbacks in process
Throws TimeoutError if fail to reach condition (under required timeout if defined) | plenum/test/helper.py | wait_for | AYCH-Inc/aych.hyper.tolerant | python | def wait_for(self, condition: Callable[([], bool)], timeout: Optional=None, max_iterations: int=10000):
'\n Advance time in steps until condition is reached, running scheduled callbacks in process\n Throws TimeoutError if fail to reach condition (under required timeout if defined)\n '
counter = 0
deadline = ((self._ts.value + timeout) if timeout else None)
while (self._events and (not condition()) and (counter < max_iterations)):
if (deadline and (self._next_timestamp() > deadline)):
raise TimeoutError('Failed to reach condition in required time, {} iterations passed'.format(counter))
self.advance()
counter += 1
if (not condition()):
if (not self._events):
raise TimeoutError('Condition will be never reached, {} iterations passed'.format(counter))
else:
raise TimeoutError('Failed to reach condition in {} iterations'.format(max_iterations)) |
def run_to_completion(self, max_iterations: int=10000):
'\n Advance time in steps until nothing is scheduled\n '
counter = 0
while (self._events and (counter < max_iterations)):
self.advance()
counter += 1
if self._events:
raise TimeoutError('Failed to complete in {} iterations'.format(max_iterations)) | 9,019,108,820,477,262,000 | Advance time in steps until nothing is scheduled | plenum/test/helper.py | run_to_completion | AYCH-Inc/aych.hyper.tolerant | python | def run_to_completion(self, max_iterations: int=10000):
'\n \n '
counter = 0
while (self._events and (counter < max_iterations)):
self.advance()
counter += 1
if self._events:
raise TimeoutError('Failed to complete in {} iterations'.format(max_iterations)) |
def __init__(self, venv: vec_env.VecEnv, expert_data: Union[(Iterable[Mapping], types.Transitions)], expert_batch_size: int, gen_algo: on_policy_algorithm.OnPolicyAlgorithm, discrim=None, *, discrim_kwargs: Optional[Mapping]=None, **kwargs):
'Generative Adversarial Imitation Learning that accepts Image Obs\n\n Most parameters are described in and passed to `AdversarialTrainer.__init__`.\n Additional parameters that `CNNGAIL` adds on top of its superclass initializer are\n as follows:\n\n Args:\n discrim_kwargs: Optional keyword arguments to use while constructing the\n DiscrimNetGAIL.\n\n '
discrim_kwargs = (discrim_kwargs or {})
if (discrim == None):
discrim = discrim_nets.DiscrimNetGAIL(venv.observation_space, venv.action_space, discrim_net=ActObsCNN, **discrim_kwargs)
logging.info('using CNN GAIL')
super().__init__(venv, gen_algo, discrim, expert_data, expert_batch_size, **kwargs) | 5,730,144,747,703,004,000 | Generative Adversarial Imitation Learning that accepts Image Obs
Most parameters are described in and passed to `AdversarialTrainer.__init__`.
Additional parameters that `CNNGAIL` adds on top of its superclass initializer are
as follows:
Args:
discrim_kwargs: Optional keyword arguments to use while constructing the
DiscrimNetGAIL. | cnn_modules/cnn_gail.py | __init__ | aj96/InfoGAIL | python | def __init__(self, venv: vec_env.VecEnv, expert_data: Union[(Iterable[Mapping], types.Transitions)], expert_batch_size: int, gen_algo: on_policy_algorithm.OnPolicyAlgorithm, discrim=None, *, discrim_kwargs: Optional[Mapping]=None, **kwargs):
'Generative Adversarial Imitation Learning that accepts Image Obs\n\n Most parameters are described in and passed to `AdversarialTrainer.__init__`.\n Additional parameters that `CNNGAIL` adds on top of its superclass initializer are\n as follows:\n\n Args:\n discrim_kwargs: Optional keyword arguments to use while constructing the\n DiscrimNetGAIL.\n\n '
discrim_kwargs = (discrim_kwargs or {})
if (discrim == None):
discrim = discrim_nets.DiscrimNetGAIL(venv.observation_space, venv.action_space, discrim_net=ActObsCNN, **discrim_kwargs)
logging.info('using CNN GAIL')
super().__init__(venv, gen_algo, discrim, expert_data, expert_batch_size, **kwargs) |
@pytest.fixture(scope='session')
def workspace(request) -> Workspace:
' Workspace Factory Fixture.\n\n Yields:\n directory(Workspace): Workspace Created.\n\n '
logger.debug('Setup of test structure.')
if request.config.getoption('workspace'):
result_dir = request.config.getoption('workspace')
else:
if (not os.path.exists('result')):
logger.debug('Creating results folder to store results')
os.mkdir('result')
result_dir = os.path.join(os.getcwd(), 'result')
logger.debug('Created folder %s', result_dir)
(yield Workspace(result_dir)) | -6,039,812,711,887,906,000 | Workspace Factory Fixture.
Yields:
directory(Workspace): Workspace Created. | orlov/libs/workspace/fixture.py | workspace | coppelia517/orlov | python | @pytest.fixture(scope='session')
def workspace(request) -> Workspace:
' Workspace Factory Fixture.\n\n Yields:\n directory(Workspace): Workspace Created.\n\n '
logger.debug('Setup of test structure.')
if request.config.getoption('workspace'):
result_dir = request.config.getoption('workspace')
else:
if (not os.path.exists('result')):
logger.debug('Creating results folder to store results')
os.mkdir('result')
result_dir = os.path.join(os.getcwd(), 'result')
logger.debug('Created folder %s', result_dir)
(yield Workspace(result_dir)) |
def kSmallestPairs(self, nums1, nums2, k):
'\n :type nums1: List[int]\n :type nums2: List[int]\n :type k: int\n :rtype: List[List[int]]\n '
pairs = []
if (len(nums1) > len(nums2)):
tmp = self.kSmallestPairs(nums2, nums1, k)
for pair in tmp:
pairs.append([pair[1], pair[0]])
return pairs
min_heap = []
def push(i, j):
if ((i < len(nums1)) and (j < len(nums2))):
heappush(min_heap, [(nums1[i] + nums2[j]), i, j])
push(0, 0)
while (min_heap and (len(pairs) < k)):
(_, i, j) = heappop(min_heap)
pairs.append([nums1[i], nums2[j]])
push(i, (j + 1))
if (j == 0):
push((i + 1), 0)
return pairs | 7,945,354,221,419,558,000 | :type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]] | Python/find-k-pairs-with-smallest-sums.py | kSmallestPairs | RideGreg/LeetCode | python | def kSmallestPairs(self, nums1, nums2, k):
'\n :type nums1: List[int]\n :type nums2: List[int]\n :type k: int\n :rtype: List[List[int]]\n '
pairs = []
if (len(nums1) > len(nums2)):
tmp = self.kSmallestPairs(nums2, nums1, k)
for pair in tmp:
pairs.append([pair[1], pair[0]])
return pairs
min_heap = []
def push(i, j):
if ((i < len(nums1)) and (j < len(nums2))):
heappush(min_heap, [(nums1[i] + nums2[j]), i, j])
push(0, 0)
while (min_heap and (len(pairs) < k)):
(_, i, j) = heappop(min_heap)
pairs.append([nums1[i], nums2[j]])
push(i, (j + 1))
if (j == 0):
push((i + 1), 0)
return pairs |
def kSmallestPairs(self, nums1, nums2, k):
'\n :type nums1: List[int]\n :type nums2: List[int]\n :type k: int\n :rtype: List[List[int]]\n '
return nsmallest(k, product(nums1, nums2), key=sum) | -7,592,175,396,215,650,000 | :type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]] | Python/find-k-pairs-with-smallest-sums.py | kSmallestPairs | RideGreg/LeetCode | python | def kSmallestPairs(self, nums1, nums2, k):
'\n :type nums1: List[int]\n :type nums2: List[int]\n :type k: int\n :rtype: List[List[int]]\n '
return nsmallest(k, product(nums1, nums2), key=sum) |
def do_query(archives, config_file=None, logger=None, context=None):
'\n Gets concordance for keywords and groups by word.\n\n config_file must be the path to a configuration file with a list\n of the keywords to search for, one per line.\n\n Both keywords and words in documents are normalized, by removing\n all non-\'a-z|A-Z\' characters.\n\n Returns result of form:\n\n {\n <WORD>:\n [\n {\n "title": <TITLE>,\n "place": <PLACE>,\n "publisher": <PUBLISHER>,\n "page_number": <PAGE_NUMBER>,\n "content": <PAGE_CONTENT>,\n "year": <YEAR>,\n "document_id": <DOCUMENT_ID>,\n "filename": <FILENAME>\n },\n ...\n ],\n <WORD>:\n ...\n }\n\n :param archives: RDD of defoe.alto.archive.Archive\n :type archives: pyspark.rdd.PipelinedRDD\n :param config_file: query configuration file\n :type config_file: str or unicode\n :param logger: logger (unused)\n :type logger: py4j.java_gateway.JavaObject\n :return: information on documents in which keywords occur grouped\n by word\n :rtype: dict\n '
keywords = query_utils.get_normalized_keywords(config_file)
documents = archives.flatMap((lambda archive: [document for document in list(archive)]))
filtered_words = documents.flatMap((lambda document: get_page_matches(document, keywords)))
matching_docs = filtered_words.map((lambda year_document_page_word: (year_document_page_word[3], {'title': year_document_page_word[1].title, 'place': year_document_page_word[1].place, 'publisher': year_document_page_word[1].publisher, 'page_number': year_document_page_word[2].code, 'content': year_document_page_word[2].content, 'year': year_document_page_word[0], 'document_id': year_document_page_word[1].code, 'filename': year_document_page_word[1].archive.filename})))
result = matching_docs.groupByKey().map((lambda year_context: (year_context[0], list(year_context[1])))).collect()
return result | 4,697,018,643,465,533,000 | Gets concordance for keywords and groups by word.
config_file must be the path to a configuration file with a list
of the keywords to search for, one per line.
Both keywords and words in documents are normalized, by removing
all non-'a-z|A-Z' characters.
Returns result of form:
{
<WORD>:
[
{
"title": <TITLE>,
"place": <PLACE>,
"publisher": <PUBLISHER>,
"page_number": <PAGE_NUMBER>,
"content": <PAGE_CONTENT>,
"year": <YEAR>,
"document_id": <DOCUMENT_ID>,
"filename": <FILENAME>
},
...
],
<WORD>:
...
}
:param archives: RDD of defoe.alto.archive.Archive
:type archives: pyspark.rdd.PipelinedRDD
:param config_file: query configuration file
:type config_file: str or unicode
:param logger: logger (unused)
:type logger: py4j.java_gateway.JavaObject
:return: information on documents in which keywords occur grouped
by word
:rtype: dict | defoe/alto/queries/keyword_concordance_by_word.py | do_query | kallewesterling/defoe | python | def do_query(archives, config_file=None, logger=None, context=None):
'\n Gets concordance for keywords and groups by word.\n\n config_file must be the path to a configuration file with a list\n of the keywords to search for, one per line.\n\n Both keywords and words in documents are normalized, by removing\n all non-\'a-z|A-Z\' characters.\n\n Returns result of form:\n\n {\n <WORD>:\n [\n {\n "title": <TITLE>,\n "place": <PLACE>,\n "publisher": <PUBLISHER>,\n "page_number": <PAGE_NUMBER>,\n "content": <PAGE_CONTENT>,\n "year": <YEAR>,\n "document_id": <DOCUMENT_ID>,\n "filename": <FILENAME>\n },\n ...\n ],\n <WORD>:\n ...\n }\n\n :param archives: RDD of defoe.alto.archive.Archive\n :type archives: pyspark.rdd.PipelinedRDD\n :param config_file: query configuration file\n :type config_file: str or unicode\n :param logger: logger (unused)\n :type logger: py4j.java_gateway.JavaObject\n :return: information on documents in which keywords occur grouped\n by word\n :rtype: dict\n '
keywords = query_utils.get_normalized_keywords(config_file)
documents = archives.flatMap((lambda archive: [document for document in list(archive)]))
filtered_words = documents.flatMap((lambda document: get_page_matches(document, keywords)))
matching_docs = filtered_words.map((lambda year_document_page_word: (year_document_page_word[3], {'title': year_document_page_word[1].title, 'place': year_document_page_word[1].place, 'publisher': year_document_page_word[1].publisher, 'page_number': year_document_page_word[2].code, 'content': year_document_page_word[2].content, 'year': year_document_page_word[0], 'document_id': year_document_page_word[1].code, 'filename': year_document_page_word[1].archive.filename})))
result = matching_docs.groupByKey().map((lambda year_context: (year_context[0], list(year_context[1])))).collect()
return result |
def main():
' main entry point for module execution\n '
OnyxQosModule.main() | -6,186,697,678,587,604,000 | main entry point for module execution | venv/lib/python3.7/site-packages/ansible_collections/mellanox/onyx/plugins/modules/onyx_qos.py | main | DiptoChakrabarty/nexus | python | def main():
' \n '
OnyxQosModule.main() |
def init_module(self):
' initialize module\n '
element_spec = dict(interfaces=dict(type='list', required=True), trust=dict(choices=['L2', 'L3', 'both'], default='L2'), rewrite_pcp=dict(choices=['enabled', 'disabled'], default='disabled'), rewrite_dscp=dict(choices=['enabled', 'disabled'], default='disabled'))
argument_spec = dict()
argument_spec.update(element_spec)
self._module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) | -4,328,371,342,356,709,400 | initialize module | venv/lib/python3.7/site-packages/ansible_collections/mellanox/onyx/plugins/modules/onyx_qos.py | init_module | DiptoChakrabarty/nexus | python | def init_module(self):
' \n '
element_spec = dict(interfaces=dict(type='list', required=True), trust=dict(choices=['L2', 'L3', 'both'], default='L2'), rewrite_pcp=dict(choices=['enabled', 'disabled'], default='disabled'), rewrite_dscp=dict(choices=['enabled', 'disabled'], default='disabled'))
argument_spec = dict()
argument_spec.update(element_spec)
self._module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) |
def format_payoff_matrix(self, payoff_matrix: list, player_1_strategies: list, player_2_strategies: list) -> str:
'\n This is a helper function that turns a payoff matrix and available\n strategies into ASCII art of a payoff matrix\n '
ret = '\t Player 1\n'
ret += (('\t ' + player_1_strategies[0]) + ' ')
for j in range(1, len(payoff_matrix[0])):
ret += (player_1_strategies[j] + ' ')
ret += '\n'
ret += '\t +------------+'
for j in range(1, len(payoff_matrix[0])):
ret += '------------+'
ret += '\n'
ret += (('Player 2 ' + str(player_2_strategies[0])) + ' |')
for j in range(len(payoff_matrix[0])):
ret += ('{:>5g}, {:<5g}'.format(payoff_matrix[0][j][0], payoff_matrix[0][j][1]) + '|')
ret += '\n'
for i in range(1, len(payoff_matrix)):
ret += '\t +------------+'
for j in range(1, len(payoff_matrix[0])):
ret += '------------+'
ret += '\n'
ret += (((('\t ' + player_2_strategies[i]) + ' |') + '{:>5g}, {:<5g}'.format(payoff_matrix[i][0][0], payoff_matrix[i][0][1])) + '|')
for j in range(1, len(payoff_matrix[i])):
ret += ('{:>5g}, {:<5g}'.format(payoff_matrix[i][j][0], payoff_matrix[i][j][1]) + '|')
ret += '\n'
ret += '\t +------------+'
for j in range(1, len(payoff_matrix[0])):
ret += '------------+'
ret += '\n'
return ret | -598,379,013,262,517,200 | This is a helper function that turns a payoff matrix and available
strategies into ASCII art of a payoff matrix | modules/nashequilibrium.py | format_payoff_matrix | benedictvs/FOCS-Calculator | python | def format_payoff_matrix(self, payoff_matrix: list, player_1_strategies: list, player_2_strategies: list) -> str:
'\n This is a helper function that turns a payoff matrix and available\n strategies into ASCII art of a payoff matrix\n '
ret = '\t Player 1\n'
ret += (('\t ' + player_1_strategies[0]) + ' ')
for j in range(1, len(payoff_matrix[0])):
ret += (player_1_strategies[j] + ' ')
ret += '\n'
ret += '\t +------------+'
for j in range(1, len(payoff_matrix[0])):
ret += '------------+'
ret += '\n'
ret += (('Player 2 ' + str(player_2_strategies[0])) + ' |')
for j in range(len(payoff_matrix[0])):
ret += ('{:>5g}, {:<5g}'.format(payoff_matrix[0][j][0], payoff_matrix[0][j][1]) + '|')
ret += '\n'
for i in range(1, len(payoff_matrix)):
ret += '\t +------------+'
for j in range(1, len(payoff_matrix[0])):
ret += '------------+'
ret += '\n'
ret += (((('\t ' + player_2_strategies[i]) + ' |') + '{:>5g}, {:<5g}'.format(payoff_matrix[i][0][0], payoff_matrix[i][0][1])) + '|')
for j in range(1, len(payoff_matrix[i])):
ret += ('{:>5g}, {:<5g}'.format(payoff_matrix[i][j][0], payoff_matrix[i][j][1]) + '|')
ret += '\n'
ret += '\t +------------+'
for j in range(1, len(payoff_matrix[0])):
ret += '------------+'
ret += '\n'
return ret |
def nash(self, payoff_matrix: list, player_1_strategies: list, player_2_strategies: list) -> tuple:
'\n Takes a payoff matrix from game theory and the available strategies for\n both players. Solves for the Nash equilibrium\n '
work = ''
no_dominant_exists = False
while ((not no_dominant_exists) and (not ((len(player_1_strategies) == 1) and (len(player_2_strategies) == 1)))):
is_break = False
for i in range(len(payoff_matrix)):
for j in range(len(payoff_matrix)):
if ((i != j) and (i < len(payoff_matrix)) and (j < len(payoff_matrix))):
is_greater = False
for k in range(len(payoff_matrix[0])):
if (float(payoff_matrix[i][k][0]) >= float(payoff_matrix[j][k][0])):
is_greater = True
if is_greater:
break
if (not is_greater):
work += (((("Player 2's Strategy " + str(player_2_strategies[j])) + ' dominates strategy ') + str(player_2_strategies[i])) + '\n')
payoff_matrix.pop(i)
player_2_strategies.pop(i)
is_break = True
work += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
work += '\n'
break
if is_break:
break
if (not is_break):
no_dominant_exists = True
else:
no_dominant_exists = False
is_break = False
for i in range(len(payoff_matrix[0])):
for j in range(len(payoff_matrix[0])):
if ((i != j) and (i < len(payoff_matrix[0])) and (j < len(payoff_matrix[0]))):
is_greater = False
for k in range(len(payoff_matrix)):
if (float(payoff_matrix[k][i][1]) >= float(payoff_matrix[k][j][1])):
is_greater = True
if is_greater:
break
if (not is_greater):
work += (((("Player 1's Strategy " + str(player_1_strategies[j])) + ' dominates strategy ') + str(player_1_strategies[i])) + '\n')
for index in range(len(payoff_matrix)):
payoff_matrix[index].pop(i)
player_1_strategies.pop(i)
work += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
work += '\n'
is_break = True
break
if (not is_break):
no_dominant_exists = True
else:
no_dominant_exists = False
if is_break:
no_dominant_exists = False
if (not ((len(player_1_strategies) == 1) and (len(player_2_strategies) == 1))):
ans = ('There is no Nash equilibrium, since at least one player has' + ' multiple viable strategies.\n')
work += ans
work += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
else:
ans = ('This is the Nash equilibrium of the entered payoff matrix,' + ' calculated by eliminating dominanted strategies.\n')
ans += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
work += ans
return (ans, work) | -4,585,256,206,811,886,600 | Takes a payoff matrix from game theory and the available strategies for
both players. Solves for the Nash equilibrium | modules/nashequilibrium.py | nash | benedictvs/FOCS-Calculator | python | def nash(self, payoff_matrix: list, player_1_strategies: list, player_2_strategies: list) -> tuple:
'\n Takes a payoff matrix from game theory and the available strategies for\n both players. Solves for the Nash equilibrium\n '
work =
no_dominant_exists = False
while ((not no_dominant_exists) and (not ((len(player_1_strategies) == 1) and (len(player_2_strategies) == 1)))):
is_break = False
for i in range(len(payoff_matrix)):
for j in range(len(payoff_matrix)):
if ((i != j) and (i < len(payoff_matrix)) and (j < len(payoff_matrix))):
is_greater = False
for k in range(len(payoff_matrix[0])):
if (float(payoff_matrix[i][k][0]) >= float(payoff_matrix[j][k][0])):
is_greater = True
if is_greater:
break
if (not is_greater):
work += (((("Player 2's Strategy " + str(player_2_strategies[j])) + ' dominates strategy ') + str(player_2_strategies[i])) + '\n')
payoff_matrix.pop(i)
player_2_strategies.pop(i)
is_break = True
work += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
work += '\n'
break
if is_break:
break
if (not is_break):
no_dominant_exists = True
else:
no_dominant_exists = False
is_break = False
for i in range(len(payoff_matrix[0])):
for j in range(len(payoff_matrix[0])):
if ((i != j) and (i < len(payoff_matrix[0])) and (j < len(payoff_matrix[0]))):
is_greater = False
for k in range(len(payoff_matrix)):
if (float(payoff_matrix[k][i][1]) >= float(payoff_matrix[k][j][1])):
is_greater = True
if is_greater:
break
if (not is_greater):
work += (((("Player 1's Strategy " + str(player_1_strategies[j])) + ' dominates strategy ') + str(player_1_strategies[i])) + '\n')
for index in range(len(payoff_matrix)):
payoff_matrix[index].pop(i)
player_1_strategies.pop(i)
work += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
work += '\n'
is_break = True
break
if (not is_break):
no_dominant_exists = True
else:
no_dominant_exists = False
if is_break:
no_dominant_exists = False
if (not ((len(player_1_strategies) == 1) and (len(player_2_strategies) == 1))):
ans = ('There is no Nash equilibrium, since at least one player has' + ' multiple viable strategies.\n')
work += ans
work += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
else:
ans = ('This is the Nash equilibrium of the entered payoff matrix,' + ' calculated by eliminating dominanted strategies.\n')
ans += self.format_payoff_matrix(payoff_matrix, player_1_strategies, player_2_strategies)
work += ans
return (ans, work) |
def pytest_addoption(parser) -> None:
'Get cli-arguments.\n\n :param parser: pytest parser\n :return:\n '
parser.addoption('--context', action='store', default='', help='The context to use in the kubeconfig file.')
parser.addoption('--image', action='store', default=DEFAULT_IMAGE, help='The Ingress Controller image.')
parser.addoption('--image-pull-policy', action='store', default=DEFAULT_PULL_POLICY, help='The pull policy of the Ingress Controller image.')
parser.addoption('--deployment-type', action='store', default=DEFAULT_DEPLOYMENT_TYPE, help='The type of the IC deployment: deployment or daemon-set.')
parser.addoption('--ic-type', action='store', default=DEFAULT_IC_TYPE, help='The type of the Ingress Controller: nginx-ingress or nginx-ingress-plus.')
parser.addoption('--service', action='store', default=DEFAULT_SERVICE, help='The type of the Ingress Controller service: nodeport or loadbalancer.')
parser.addoption('--replicas', action='store', default=NUM_REPLICAS, help='Number of replica pods for type deployment')
parser.addoption('--node-ip', action='store', help='The public IP of a cluster node. Not required if you use the loadbalancer service (see --service argument).')
parser.addoption('--kubeconfig', action='store', default=os.path.expanduser(KUBE_CONFIG_DEFAULT_LOCATION), help='An absolute path to a kubeconfig file.')
parser.addoption('--show-ic-logs', action='store', default='no', help='Show IC logs in stdout on test failure')
parser.addoption('--batch-start', action='store', default=BATCH_START, help='Run tests for pods restarts with multiple resources deployed (Ingress/VS): True/False')
parser.addoption('--batch-resources', action='store', default=BATCH_RESOURCES, help='Number of VS/Ingress resources to deploy') | 4,674,396,019,310,846,000 | Get cli-arguments.
:param parser: pytest parser
:return: | tests/conftest.py | pytest_addoption | 84flix/kubernetes-ingress | python | def pytest_addoption(parser) -> None:
'Get cli-arguments.\n\n :param parser: pytest parser\n :return:\n '
parser.addoption('--context', action='store', default=, help='The context to use in the kubeconfig file.')
parser.addoption('--image', action='store', default=DEFAULT_IMAGE, help='The Ingress Controller image.')
parser.addoption('--image-pull-policy', action='store', default=DEFAULT_PULL_POLICY, help='The pull policy of the Ingress Controller image.')
parser.addoption('--deployment-type', action='store', default=DEFAULT_DEPLOYMENT_TYPE, help='The type of the IC deployment: deployment or daemon-set.')
parser.addoption('--ic-type', action='store', default=DEFAULT_IC_TYPE, help='The type of the Ingress Controller: nginx-ingress or nginx-ingress-plus.')
parser.addoption('--service', action='store', default=DEFAULT_SERVICE, help='The type of the Ingress Controller service: nodeport or loadbalancer.')
parser.addoption('--replicas', action='store', default=NUM_REPLICAS, help='Number of replica pods for type deployment')
parser.addoption('--node-ip', action='store', help='The public IP of a cluster node. Not required if you use the loadbalancer service (see --service argument).')
parser.addoption('--kubeconfig', action='store', default=os.path.expanduser(KUBE_CONFIG_DEFAULT_LOCATION), help='An absolute path to a kubeconfig file.')
parser.addoption('--show-ic-logs', action='store', default='no', help='Show IC logs in stdout on test failure')
parser.addoption('--batch-start', action='store', default=BATCH_START, help='Run tests for pods restarts with multiple resources deployed (Ingress/VS): True/False')
parser.addoption('--batch-resources', action='store', default=BATCH_RESOURCES, help='Number of VS/Ingress resources to deploy') |
def pytest_collection_modifyitems(config, items) -> None:
"\n Skip tests marked with '@pytest.mark.skip_for_nginx_oss' for Nginx OSS runs.\n Skip tests marked with '@pytest.mark.appprotect' for non AP images.\n\n :param config: pytest config\n :param items: pytest collected test-items\n :return:\n "
if (config.getoption('--ic-type') == 'nginx-ingress'):
skip_for_nginx_oss = pytest.mark.skip(reason='Skip a test for Nginx OSS')
for item in items:
if ('skip_for_nginx_oss' in item.keywords):
item.add_marker(skip_for_nginx_oss)
if (config.getoption('--ic-type') == 'nginx-plus-ingress'):
skip_for_nginx_plus = pytest.mark.skip(reason='Skip a test for Nginx Plus')
for item in items:
if ('skip_for_nginx_plus' in item.keywords):
item.add_marker(skip_for_nginx_plus)
if ('-ap' not in config.getoption('--image')):
appprotect = pytest.mark.skip(reason='Skip AppProtect test in non-AP image')
for item in items:
if ('appprotect' in item.keywords):
item.add_marker(appprotect)
if (str(config.getoption('--batch-start')) != 'True'):
batch_start = pytest.mark.skip(reason='Skipping pod restart test with multiple resources')
for item in items:
if ('batch_start' in item.keywords):
item.add_marker(batch_start) | 8,845,734,107,502,426,000 | Skip tests marked with '@pytest.mark.skip_for_nginx_oss' for Nginx OSS runs.
Skip tests marked with '@pytest.mark.appprotect' for non AP images.
:param config: pytest config
:param items: pytest collected test-items
:return: | tests/conftest.py | pytest_collection_modifyitems | 84flix/kubernetes-ingress | python | def pytest_collection_modifyitems(config, items) -> None:
"\n Skip tests marked with '@pytest.mark.skip_for_nginx_oss' for Nginx OSS runs.\n Skip tests marked with '@pytest.mark.appprotect' for non AP images.\n\n :param config: pytest config\n :param items: pytest collected test-items\n :return:\n "
if (config.getoption('--ic-type') == 'nginx-ingress'):
skip_for_nginx_oss = pytest.mark.skip(reason='Skip a test for Nginx OSS')
for item in items:
if ('skip_for_nginx_oss' in item.keywords):
item.add_marker(skip_for_nginx_oss)
if (config.getoption('--ic-type') == 'nginx-plus-ingress'):
skip_for_nginx_plus = pytest.mark.skip(reason='Skip a test for Nginx Plus')
for item in items:
if ('skip_for_nginx_plus' in item.keywords):
item.add_marker(skip_for_nginx_plus)
if ('-ap' not in config.getoption('--image')):
appprotect = pytest.mark.skip(reason='Skip AppProtect test in non-AP image')
for item in items:
if ('appprotect' in item.keywords):
item.add_marker(appprotect)
if (str(config.getoption('--batch-start')) != 'True'):
batch_start = pytest.mark.skip(reason='Skipping pod restart test with multiple resources')
for item in items:
if ('batch_start' in item.keywords):
item.add_marker(batch_start) |
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item) -> None:
"\n Print out IC Pod logs on test failure.\n\n Only look at actual failing test calls, not setup/teardown.\n Only show the logs if commandline argument `--show-ic-logs` is set to 'yes'\n\n :param item:\n :return:\n "
outcome = (yield)
rep = outcome.get_result()
if ((rep.when == 'call') and rep.failed and (item.config.getoption('--show-ic-logs') == 'yes')):
pod_namespace = item.funcargs['ingress_controller_prerequisites'].namespace
pod_name = get_first_pod_name(item.funcargs['kube_apis'].v1, pod_namespace)
print('\n===================== IC Logs Start =====================')
print(item.funcargs['kube_apis'].v1.read_namespaced_pod_log(pod_name, pod_namespace))
print('\n===================== IC Logs End =====================') | 58,466,163,031,448,530 | Print out IC Pod logs on test failure.
Only look at actual failing test calls, not setup/teardown.
Only show the logs if commandline argument `--show-ic-logs` is set to 'yes'
:param item:
:return: | tests/conftest.py | pytest_runtest_makereport | 84flix/kubernetes-ingress | python | @pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item) -> None:
"\n Print out IC Pod logs on test failure.\n\n Only look at actual failing test calls, not setup/teardown.\n Only show the logs if commandline argument `--show-ic-logs` is set to 'yes'\n\n :param item:\n :return:\n "
outcome = (yield)
rep = outcome.get_result()
if ((rep.when == 'call') and rep.failed and (item.config.getoption('--show-ic-logs') == 'yes')):
pod_namespace = item.funcargs['ingress_controller_prerequisites'].namespace
pod_name = get_first_pod_name(item.funcargs['kube_apis'].v1, pod_namespace)
print('\n===================== IC Logs Start =====================')
print(item.funcargs['kube_apis'].v1.read_namespaced_pod_log(pod_name, pod_namespace))
print('\n===================== IC Logs End =====================') |
def test_retrieve_spls(self):
'Test retrieving spls'
res = self.client.get(SPL_URL, format='json')
serializer = SplSerializer(Spl.objects.filter(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) | -5,536,810,454,583,763,000 | Test retrieving spls | api/dailymed/tests/test_api.py | test_retrieve_spls | coderxio/dailymed-api | python | def test_retrieve_spls(self):
res = self.client.get(SPL_URL, format='json')
serializer = SplSerializer(Spl.objects.filter(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) |
def test_retrieve_spls_filter_by_set(self):
'Test retrieving a spl by set filter'
set_id = Set.objects.first()
res = self.client.get(SPL_URL, {'set_id': set_id.id}, format='json')
serializer = SplSerializer(Spl.objects.filter(set__id=set_id.id), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) | -868,276,020,270,463,200 | Test retrieving a spl by set filter | api/dailymed/tests/test_api.py | test_retrieve_spls_filter_by_set | coderxio/dailymed-api | python | def test_retrieve_spls_filter_by_set(self):
set_id = Set.objects.first()
res = self.client.get(SPL_URL, {'set_id': set_id.id}, format='json')
serializer = SplSerializer(Spl.objects.filter(set__id=set_id.id), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) |
def test_retrieve_spls_filter_by_inactive_ing(self):
'Test retrieving a spl by inactive ingredient filter'
inactive_ing = 'alcohol'
res = self.client.get(SPL_URL, {'inactive_ingredient_name': inactive_ing}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__inactive_ingredients__name__icontains=inactive_ing).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) | 5,513,470,254,975,822,000 | Test retrieving a spl by inactive ingredient filter | api/dailymed/tests/test_api.py | test_retrieve_spls_filter_by_inactive_ing | coderxio/dailymed-api | python | def test_retrieve_spls_filter_by_inactive_ing(self):
inactive_ing = 'alcohol'
res = self.client.get(SPL_URL, {'inactive_ingredient_name': inactive_ing}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__inactive_ingredients__name__icontains=inactive_ing).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) |
def test_retrieve_spls_filter_by_schedule(self):
'Test retrieving spls by schedule filter'
schedule = 'CIV'
res = self.client.get(SPL_URL, {'schedule': schedule}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__schedule=schedule).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) | -8,507,637,084,264,474,000 | Test retrieving spls by schedule filter | api/dailymed/tests/test_api.py | test_retrieve_spls_filter_by_schedule | coderxio/dailymed-api | python | def test_retrieve_spls_filter_by_schedule(self):
schedule = 'CIV'
res = self.client.get(SPL_URL, {'schedule': schedule}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__schedule=schedule).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) |
def test_retrieve_spls_filter_by_drug_name(self):
'Test retrieving spls by drug name filter'
name = 'Ciprofloxacin'
res = self.client.get(SPL_URL, {'product_name': name}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__name=name).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) | 1,683,314,421,140,632,800 | Test retrieving spls by drug name filter | api/dailymed/tests/test_api.py | test_retrieve_spls_filter_by_drug_name | coderxio/dailymed-api | python | def test_retrieve_spls_filter_by_drug_name(self):
name = 'Ciprofloxacin'
res = self.client.get(SPL_URL, {'product_name': name}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__name=name).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(serializer.data, res.data['results']) |
def test_retrieve_spls_filter_by_complex(self):
'Test retrieving spls filtered by set & inactive ingredient'
set_id = 'b88efb93-f1d1-4606-a669-6896f432a27f'
inactive_ing = 'alcohol'
res = self.client.get(SPL_URL, {'set_id': set_id, 'inactive_ingredient_name': inactive_ing}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__inactive_ingredients__name__icontains=inactive_ing, set__id=set_id).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data['results']), 1)
self.assertEqual(serializer.data, res.data['results']) | -66,638,310,692,661,380 | Test retrieving spls filtered by set & inactive ingredient | api/dailymed/tests/test_api.py | test_retrieve_spls_filter_by_complex | coderxio/dailymed-api | python | def test_retrieve_spls_filter_by_complex(self):
set_id = 'b88efb93-f1d1-4606-a669-6896f432a27f'
inactive_ing = 'alcohol'
res = self.client.get(SPL_URL, {'set_id': set_id, 'inactive_ingredient_name': inactive_ing}, format='json')
serializer = SplSerializer(Spl.objects.filter(products__inactive_ingredients__name__icontains=inactive_ing, set__id=set_id).distinct(), many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data['results']), 1)
self.assertEqual(serializer.data, res.data['results']) |
def diag_embed(input, offset=0, dim1=(- 2), dim2=(- 1)):
"\n This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) \n are filled by ``input``. By default, a 2D plane formed by the last two dimensions \n of the returned tensor will be selected.\n\n The argument ``offset`` determines which diagonal is generated:\n\n - If offset = 0, it is the main diagonal.\n - If offset > 0, it is above the main diagonal.\n - If offset < 0, it is below the main diagonal.\n\n Args:\n input(Tensor|numpy.ndarray): The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.\n offset(int, optional): Which diagonal to consider. Default: 0 (main diagonal).\n dim1(int, optional): The first dimension with respect to which to take diagonal. Default: -2.\n dim2(int, optional): The second dimension with respect to which to take diagonal. Default: -1.\n \n Returns:\n Tensor, the output data type is the same as input data type.\n \n Examples:\n .. code-block:: python\n\n import paddle.nn.functional as F\n import numpy as np\n \n diag_embed = np.random.randn(2, 3).astype('float32')\n # [[ 0.7545889 , -0.25074545, 0.5929117 ],\n # [-0.6097662 , -0.01753256, 0.619769 ]]\n\n data1 = F.diag_embed(diag_embed)\n data1.numpy()\n # [[[ 0.7545889 , 0. , 0. ],\n # [ 0. , -0.25074545, 0. ],\n # [ 0. , 0. , 0.5929117 ]],\n\n # [[-0.6097662 , 0. , 0. ],\n # [ 0. , -0.01753256, 0. ],\n # [ 0. , 0. , 0.619769 ]]]\n\n data2 = F.diag_embed(diag_embed, offset=-1, dim1=0, dim2=2)\n data2.numpy()\n # [[[ 0. , 0. , 0. , 0. ],\n # [ 0.7545889 , 0. , 0. , 0. ],\n # [ 0. , -0.25074545, 0. , 0. ],\n # [ 0. , 0. , 0.5929117 , 0. ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [-0.6097662 , 0. , 0. , 0. ],\n # [ 0. , -0.01753256, 0. , 0. ],\n # [ 0. , 0. , 0.619769 , 0. ]]]\n\n data3 = F.diag_embed(diag_embed, offset=1, dim1=0, dim2=2)\n data3.numpy()\n # [[[ 0. , 0.7545889 , 0. , 0. ],\n # [ 0. , -0.6097662 , 0. , 0. ]],\n #\n # [[ 0. , 0. , -0.25074545, 0. ],\n # [ 0. , 0. , -0.01753256, 0. ]],\n #\n # [[ 0. , 0. , 0. , 0.5929117 ],\n # [ 0. , 0. , 0. , 0.619769 ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [ 0. , 0. , 0. , 0. ]]]\n "
inputs = {'Input': [input]}
attrs = {'offset': offset, 'dim1': dim1, 'dim2': dim2}
if (not isinstance(input, Variable)):
input = assign(input)
def __check_input(input, offset, dim1, dim2):
check_dtype(input.dtype, 'Input', ['int32', 'int64', 'float16', 'float32', 'float64'], 'diag_embed')
input_shape = list(input.shape)
assert (len(input_shape) >= 1), ("Input must be at least 1-dimensional, But received Input's dimensional: %s.\n" % len(input_shape))
assert (np.abs(dim1) <= len(input_shape)), ('Dim1 is out of range (expected to be in range of [%d, %d], but got %d).\n' % ((- (len(input_shape) + 1)), len(input_shape), dim1))
assert (np.abs(dim2) <= len(input_shape)), ('Dim2 is out of range (expected to be in range of [%d, %d], but got %d).\n' % ((- (len(input_shape) + 1)), len(input_shape), dim2))
dim1_ = (dim1 if (dim1 >= 0) else ((len(input_shape) + dim1) + 1))
dim2_ = (dim2 if (dim2 >= 0) else ((len(input_shape) + dim2) + 1))
assert (dim1_ != dim2_), ('dim1 and dim2 cannot be the same dimension.But received dim1 = %d, dim2 = %d\n' % (dim1, dim2))
if (not in_dygraph_mode()):
__check_input(input, offset, dim1, dim2)
helper = LayerHelper('diag_embed', **locals())
out = helper.create_variable_for_type_inference(dtype=input.dtype)
helper.append_op(type='diag_embed', inputs={'Input': [input]}, attrs={'offset': offset, 'dim1': dim1, 'dim2': dim2}, outputs={'Out': [out]})
out.stop_gradient = True
return out | 666,630,465,588,496,500 | This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2)
are filled by ``input``. By default, a 2D plane formed by the last two dimensions
of the returned tensor will be selected.
The argument ``offset`` determines which diagonal is generated:
- If offset = 0, it is the main diagonal.
- If offset > 0, it is above the main diagonal.
- If offset < 0, it is below the main diagonal.
Args:
input(Tensor|numpy.ndarray): The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.
offset(int, optional): Which diagonal to consider. Default: 0 (main diagonal).
dim1(int, optional): The first dimension with respect to which to take diagonal. Default: -2.
dim2(int, optional): The second dimension with respect to which to take diagonal. Default: -1.
Returns:
Tensor, the output data type is the same as input data type.
Examples:
.. code-block:: python
import paddle.nn.functional as F
import numpy as np
diag_embed = np.random.randn(2, 3).astype('float32')
# [[ 0.7545889 , -0.25074545, 0.5929117 ],
# [-0.6097662 , -0.01753256, 0.619769 ]]
data1 = F.diag_embed(diag_embed)
data1.numpy()
# [[[ 0.7545889 , 0. , 0. ],
# [ 0. , -0.25074545, 0. ],
# [ 0. , 0. , 0.5929117 ]],
# [[-0.6097662 , 0. , 0. ],
# [ 0. , -0.01753256, 0. ],
# [ 0. , 0. , 0.619769 ]]]
data2 = F.diag_embed(diag_embed, offset=-1, dim1=0, dim2=2)
data2.numpy()
# [[[ 0. , 0. , 0. , 0. ],
# [ 0.7545889 , 0. , 0. , 0. ],
# [ 0. , -0.25074545, 0. , 0. ],
# [ 0. , 0. , 0.5929117 , 0. ]],
#
# [[ 0. , 0. , 0. , 0. ],
# [-0.6097662 , 0. , 0. , 0. ],
# [ 0. , -0.01753256, 0. , 0. ],
# [ 0. , 0. , 0.619769 , 0. ]]]
data3 = F.diag_embed(diag_embed, offset=1, dim1=0, dim2=2)
data3.numpy()
# [[[ 0. , 0.7545889 , 0. , 0. ],
# [ 0. , -0.6097662 , 0. , 0. ]],
#
# [[ 0. , 0. , -0.25074545, 0. ],
# [ 0. , 0. , -0.01753256, 0. ]],
#
# [[ 0. , 0. , 0. , 0.5929117 ],
# [ 0. , 0. , 0. , 0.619769 ]],
#
# [[ 0. , 0. , 0. , 0. ],
# [ 0. , 0. , 0. , 0. ]]] | python/paddle/nn/functional/extension.py | diag_embed | wangna11BD/Paddle | python | def diag_embed(input, offset=0, dim1=(- 2), dim2=(- 1)):
"\n This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) \n are filled by ``input``. By default, a 2D plane formed by the last two dimensions \n of the returned tensor will be selected.\n\n The argument ``offset`` determines which diagonal is generated:\n\n - If offset = 0, it is the main diagonal.\n - If offset > 0, it is above the main diagonal.\n - If offset < 0, it is below the main diagonal.\n\n Args:\n input(Tensor|numpy.ndarray): The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.\n offset(int, optional): Which diagonal to consider. Default: 0 (main diagonal).\n dim1(int, optional): The first dimension with respect to which to take diagonal. Default: -2.\n dim2(int, optional): The second dimension with respect to which to take diagonal. Default: -1.\n \n Returns:\n Tensor, the output data type is the same as input data type.\n \n Examples:\n .. code-block:: python\n\n import paddle.nn.functional as F\n import numpy as np\n \n diag_embed = np.random.randn(2, 3).astype('float32')\n # [[ 0.7545889 , -0.25074545, 0.5929117 ],\n # [-0.6097662 , -0.01753256, 0.619769 ]]\n\n data1 = F.diag_embed(diag_embed)\n data1.numpy()\n # [[[ 0.7545889 , 0. , 0. ],\n # [ 0. , -0.25074545, 0. ],\n # [ 0. , 0. , 0.5929117 ]],\n\n # [[-0.6097662 , 0. , 0. ],\n # [ 0. , -0.01753256, 0. ],\n # [ 0. , 0. , 0.619769 ]]]\n\n data2 = F.diag_embed(diag_embed, offset=-1, dim1=0, dim2=2)\n data2.numpy()\n # [[[ 0. , 0. , 0. , 0. ],\n # [ 0.7545889 , 0. , 0. , 0. ],\n # [ 0. , -0.25074545, 0. , 0. ],\n # [ 0. , 0. , 0.5929117 , 0. ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [-0.6097662 , 0. , 0. , 0. ],\n # [ 0. , -0.01753256, 0. , 0. ],\n # [ 0. , 0. , 0.619769 , 0. ]]]\n\n data3 = F.diag_embed(diag_embed, offset=1, dim1=0, dim2=2)\n data3.numpy()\n # [[[ 0. , 0.7545889 , 0. , 0. ],\n # [ 0. , -0.6097662 , 0. , 0. ]],\n #\n # [[ 0. , 0. , -0.25074545, 0. ],\n # [ 0. , 0. , -0.01753256, 0. ]],\n #\n # [[ 0. , 0. , 0. , 0.5929117 ],\n # [ 0. , 0. , 0. , 0.619769 ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [ 0. , 0. , 0. , 0. ]]]\n "
inputs = {'Input': [input]}
attrs = {'offset': offset, 'dim1': dim1, 'dim2': dim2}
if (not isinstance(input, Variable)):
input = assign(input)
def __check_input(input, offset, dim1, dim2):
check_dtype(input.dtype, 'Input', ['int32', 'int64', 'float16', 'float32', 'float64'], 'diag_embed')
input_shape = list(input.shape)
assert (len(input_shape) >= 1), ("Input must be at least 1-dimensional, But received Input's dimensional: %s.\n" % len(input_shape))
assert (np.abs(dim1) <= len(input_shape)), ('Dim1 is out of range (expected to be in range of [%d, %d], but got %d).\n' % ((- (len(input_shape) + 1)), len(input_shape), dim1))
assert (np.abs(dim2) <= len(input_shape)), ('Dim2 is out of range (expected to be in range of [%d, %d], but got %d).\n' % ((- (len(input_shape) + 1)), len(input_shape), dim2))
dim1_ = (dim1 if (dim1 >= 0) else ((len(input_shape) + dim1) + 1))
dim2_ = (dim2 if (dim2 >= 0) else ((len(input_shape) + dim2) + 1))
assert (dim1_ != dim2_), ('dim1 and dim2 cannot be the same dimension.But received dim1 = %d, dim2 = %d\n' % (dim1, dim2))
if (not in_dygraph_mode()):
__check_input(input, offset, dim1, dim2)
helper = LayerHelper('diag_embed', **locals())
out = helper.create_variable_for_type_inference(dtype=input.dtype)
helper.append_op(type='diag_embed', inputs={'Input': [input]}, attrs={'offset': offset, 'dim1': dim1, 'dim2': dim2}, outputs={'Out': [out]})
out.stop_gradient = True
return out |
def duplicate_batch(batch, tokenzier, args):
'\n 句子进行重复\n '
new_batch = []
for sentence in batch:
new_batch.append(sentence)
new_batch.append(sentence)
batch_encoding = tokenzier(new_batch, padding=True, truncation=True, max_length=args.max_length, return_tensors='pt')
return batch_encoding | 1,107,520,179,547,964,900 | 句子进行重复 | simcse/train_unsup.py | duplicate_batch | Macielyoung/sentence_representation_matching | python | def duplicate_batch(batch, tokenzier, args):
'\n \n '
new_batch = []
for sentence in batch:
new_batch.append(sentence)
new_batch.append(sentence)
batch_encoding = tokenzier(new_batch, padding=True, truncation=True, max_length=args.max_length, return_tensors='pt')
return batch_encoding |
def topological_sort(self, start, visited, sort):
'Perform topological sort on a directed acyclic graph.'
current = start
visited.append(current)
neighbors = edges[current]
for neighbor in neighbors:
if (neighbor not in visited):
sort = topological_sort(neighbor, visited, sort)
sort.append(current)
if (len(visited) != len(vertices)):
for vertice in vertices:
if (vertice not in visited):
sort = topological_sort(vertice, visited, sort)
return sort | -7,265,521,565,580,027,000 | Perform topological sort on a directed acyclic graph. | algorithm/python/topological_sort.py | topological_sort | yennanliu/Python_basics | python | def topological_sort(self, start, visited, sort):
current = start
visited.append(current)
neighbors = edges[current]
for neighbor in neighbors:
if (neighbor not in visited):
sort = topological_sort(neighbor, visited, sort)
sort.append(current)
if (len(visited) != len(vertices)):
for vertice in vertices:
if (vertice not in visited):
sort = topological_sort(vertice, visited, sort)
return sort |
def __init__(self, api, data):
'\n Internal use only: initialize sample serie\n '
if (((data is not None) & (type(data) == dict)) & ('name' in data.keys())):
super().__init__(api, data, 'seriesID', str(data['name']))
else:
raise Exception('no (valid) sampleSerie data') | 2,506,736,206,531,914,000 | Internal use only: initialize sample serie | elabjournal/elabjournal/SampleSerie.py | __init__ | matthijsbrouwer/elabjournal-python | python | def __init__(self, api, data):
'\n \n '
if (((data is not None) & (type(data) == dict)) & ('name' in data.keys())):
super().__init__(api, data, 'seriesID', str(data['name']))
else:
raise Exception('no (valid) sampleSerie data') |
def barcode(self):
'\n Get the barcode.\n '
if ('barcode' in self.data()):
barcode = self.data()['barcode']
return barcode
return None | -556,167,806,567,873,200 | Get the barcode. | elabjournal/elabjournal/SampleSerie.py | barcode | matthijsbrouwer/elabjournal-python | python | def barcode(self):
'\n \n '
if ('barcode' in self.data()):
barcode = self.data()['barcode']
return barcode
return None |
def samples(self):
'\n Get a dict with the samples for this sample serie.\n The sampleID is used as a key, the value is a sample object. \n '
sample_list = []
if ('samples' in self.data()):
samplesData = self.data()['samples']
if isinstance(samplesData, list):
for sampleItem in samplesData:
if (isinstance(sampleItem, dict) & ('sampleID' in sampleItem)):
sample_list.append(sampleItem['sampleID'])
elif (isinstance(sampleItem, numbers.Integral) | isinstance(sampleItem, str)):
sample_list.append(sampleItem)
return self._eLABJournalObject__api.sample(sample_list) | -5,221,679,118,685,270,000 | Get a dict with the samples for this sample serie.
The sampleID is used as a key, the value is a sample object. | elabjournal/elabjournal/SampleSerie.py | samples | matthijsbrouwer/elabjournal-python | python | def samples(self):
'\n Get a dict with the samples for this sample serie.\n The sampleID is used as a key, the value is a sample object. \n '
sample_list = []
if ('samples' in self.data()):
samplesData = self.data()['samples']
if isinstance(samplesData, list):
for sampleItem in samplesData:
if (isinstance(sampleItem, dict) & ('sampleID' in sampleItem)):
sample_list.append(sampleItem['sampleID'])
elif (isinstance(sampleItem, numbers.Integral) | isinstance(sampleItem, str)):
sample_list.append(sampleItem)
return self._eLABJournalObject__api.sample(sample_list) |
def main():
'Start the ROS driver and ROS node.'
rospy.init_node('axis_driver')
arg_defaults = {'hostname': '192.168.0.90', 'username': None, 'password': None, 'width': 704, 'height': 576, 'frame_id': 'axis_camera', 'camera_info_url': '', 'use_encrypted_password': False, 'camera_id': 1, 'auto_wakeup_camera': True, 'compression': 0, 'fps': 24, 'use_color': True, 'use_square_pixels': False}
args = read_args_with_defaults(arg_defaults)
axis = Axis(**args)
rate = rospy.Rate(1)
while (not rospy.is_shutdown()):
axis.diagnostic_updater.update()
try:
rate.sleep()
except rospy.ROSTimeMovedBackwardsException:
rospy.logwarn('Detected jump back in time.') | -7,634,728,595,484,451,000 | Start the ROS driver and ROS node. | nodes/axis.py | main | MarcoStb1993/axis_camera | python | def main():
rospy.init_node('axis_driver')
arg_defaults = {'hostname': '192.168.0.90', 'username': None, 'password': None, 'width': 704, 'height': 576, 'frame_id': 'axis_camera', 'camera_info_url': , 'use_encrypted_password': False, 'camera_id': 1, 'auto_wakeup_camera': True, 'compression': 0, 'fps': 24, 'use_color': True, 'use_square_pixels': False}
args = read_args_with_defaults(arg_defaults)
axis = Axis(**args)
rate = rospy.Rate(1)
while (not rospy.is_shutdown()):
axis.diagnostic_updater.update()
try:
rate.sleep()
except rospy.ROSTimeMovedBackwardsException:
rospy.logwarn('Detected jump back in time.') |
def read_args_with_defaults(arg_defaults):
"Look up parameters starting in the driver's private parameter space, but also searching outer namespaces.\n Defining them in a higher namespace allows the axis_ptz.py script to share parameters with the driver."
args = {}
for (name, val) in arg_defaults.iteritems():
full_name = rospy.search_param(name)
if (full_name is None):
args[name] = val
else:
args[name] = rospy.get_param(full_name, val)
if (args['frame_id'][0] != '/'):
tf_prefix = rospy.search_param('tf_prefix')
prefix_val = ''
if (tf_prefix is not None):
prefix_val = rospy.get_param(tf_prefix)
if (prefix_val[0] != '/'):
prefix_val = ('/' + prefix_val)
args['frame_id'] = ((prefix_val + '/') + args['frame_id'])
return args | 3,282,720,258,080,658,400 | Look up parameters starting in the driver's private parameter space, but also searching outer namespaces.
Defining them in a higher namespace allows the axis_ptz.py script to share parameters with the driver. | nodes/axis.py | read_args_with_defaults | MarcoStb1993/axis_camera | python | def read_args_with_defaults(arg_defaults):
"Look up parameters starting in the driver's private parameter space, but also searching outer namespaces.\n Defining them in a higher namespace allows the axis_ptz.py script to share parameters with the driver."
args = {}
for (name, val) in arg_defaults.iteritems():
full_name = rospy.search_param(name)
if (full_name is None):
args[name] = val
else:
args[name] = rospy.get_param(full_name, val)
if (args['frame_id'][0] != '/'):
tf_prefix = rospy.search_param('tf_prefix')
prefix_val =
if (tf_prefix is not None):
prefix_val = rospy.get_param(tf_prefix)
if (prefix_val[0] != '/'):
prefix_val = ('/' + prefix_val)
args['frame_id'] = ((prefix_val + '/') + args['frame_id'])
return args |
def __init__(self, hostname, username, password, width, height, frame_id, camera_info_url, use_encrypted_password, camera_id=1, auto_wakeup_camera=True, compression=0, fps=24, use_color=True, use_square_pixels=False):
'Create the ROS-VAPIX interface.\n\n :param hostname: Hostname of the camera (without http://, can be an IP address).\n :type hostname: basestring\n :param username: If login is needed, provide a username here.\n :type username: :py:obj:`basestring` | None\n :param password: If login is needed, provide a password here.\n :type password: :py:obj:`basestring` | None\n :param width: Width of the requested video stream in pixels (can be changed later). Must be one of the supported\n resolutions. If `None`, the resolution will be chosen by height only. If also `height` is `None`,\n then the default camera resolution will be used.\n :type width: int|None\n :param height: Height of the requested video stream in pixels (can be changed later). Must be one of the\n supported resolutions. If `None`, the resolution will be chosen by width only. If also `width` is\n `None`, then the default camera resolution will be used.\n :type height: int|None\n :param frame_id: The ROS TF frame assigned to the camera.\n :type frame_id: basestring\n :param camera_info_url: The URL pointing to the camera calaibration, if available.\n :type camera_info_url: basestring\n :param use_encrypted_password: Whether to use Plain HTTP Auth (False) or Digest HTTP Auth (True).\n :type use_encrypted_password: bool\n :param camera_id: ID (number) of the camera. Can be 1 to 4.\n :type camera_id: int\n :param auto_wakeup_camera: If True, there will be a wakeup trial after first unsuccessful network command.\n :type auto_wakeup_camera: bool\n :param compression: Compression of the image (0 - no compression, 100 - max compression).\n :type compression: int\n :param fps: The desired frames per second.\n :type fps: int\n :param use_color: If True, send a color stream, otherwise send only grayscale image.\n :type use_color: bool\n :param use_square_pixels: If True, the resolution will be stretched to match 1:1 pixels.\n By default, the pixels have a ratio of 11:12.\n :type use_square_pixels: bool\n :raises: :py:exc:`ValueError` if the requested resolution (either the `resolution`, or `width`+`height`\n is not supported.\n '
self.video_params_changed = False
self.__initializing = True
self._hostname = hostname
self._camera_id = camera_id
self.diagnostic_updater = Updater()
self.diagnostic_updater.setHardwareID(hostname)
self._api = None
while ((self._api is None) and (not rospy.is_shutdown())):
try:
self._api = VAPIX.get_api_for_camera(hostname, username, password, camera_id, use_encrypted_password)
except (IOError, ValueError):
rospy.loginfo(('Retrying connection to VAPIX on host %s, camera %d in 2 seconds.' % (hostname, camera_id)))
rospy.sleep(2)
if rospy.is_shutdown():
return
self._allowed_resolutions = self._get_allowed_resolutions()
rospy.loginfo(('The following resolutions are available for camera %d:\n%s' % (camera_id, '\n'.join([str(res) for res in self._allowed_resolutions]))))
rospy.set_param('~allowed_resolutions', [res.get_vapix_representation() for res in self._allowed_resolutions])
self._auto_wakeup_camera = auto_wakeup_camera
self._width = None
self._height = None
self._resolution = None
self._compression = None
self._fps = None
self._use_color = None
self._use_square_pixels = None
width = (width if (width != '') else None)
height = (height if (height != '') else None)
if ((width is None) and (height is None)):
self.set_resolution(self._allowed_resolutions[0])
else:
resolution = self.find_resolution_by_size(width, height)
self.set_resolution(resolution.get_vapix_representation())
self.set_compression(compression)
self.set_fps(fps)
self.set_use_color(use_color)
self.set_use_square_pixels(use_square_pixels)
change_enum_items(VideoStreamConfig, 'resolution', [{'name': (res.name if isinstance(res, CIFVideoResolution) else str(res)), 'value': res.get_vapix_representation(), 'description': str(res)} for res in self._allowed_resolutions], self._resolution.get_vapix_representation())
self._video_stream_param_change_server = dynamic_reconfigure.server.Server(VideoStreamConfig, self.reconfigure_video)
self._frame_id = frame_id
self._camera_info_url = camera_info_url
self._camera_name = camera_info_manager.genCameraName(self._hostname)
self._camera_info = camera_info_manager.CameraInfoManager(cname=self._camera_name, url=self._camera_info_url)
self._camera_info.loadCameraInfo()
self._streaming_thread = None
self._video_publisher_frequency_diagnostic = FrequencyStatusParam({'min': self._fps, 'max': self._fps})
self._video_publisher = PausableDiagnosedPublisher(self, rospy.Publisher('image_raw/compressed', CompressedImage, self, queue_size=100), self.diagnostic_updater, self._video_publisher_frequency_diagnostic, TimeStampStatusParam())
self._camera_info_publisher = PausableDiagnosedPublisher(self, rospy.Publisher('camera_info', CameraInfo, self, queue_size=100), self.diagnostic_updater, self._video_publisher_frequency_diagnostic, TimeStampStatusParam())
self._snapshot_server = rospy.Service('take_snapshot', TakeSnapshot, self.take_snapshot)
self.diagnostic_updater.add(FunctionDiagnosticTask('Camera parameters', self._camera_diagnostic_callback))
self.username = username
self.password = password
self.use_encrypted_password = use_encrypted_password
self.st = None
self.pub = self._video_publisher
self.caminfo_pub = self._camera_info_publisher
self.__initializing = False | 7,536,219,766,544,866,000 | Create the ROS-VAPIX interface.
:param hostname: Hostname of the camera (without http://, can be an IP address).
:type hostname: basestring
:param username: If login is needed, provide a username here.
:type username: :py:obj:`basestring` | None
:param password: If login is needed, provide a password here.
:type password: :py:obj:`basestring` | None
:param width: Width of the requested video stream in pixels (can be changed later). Must be one of the supported
resolutions. If `None`, the resolution will be chosen by height only. If also `height` is `None`,
then the default camera resolution will be used.
:type width: int|None
:param height: Height of the requested video stream in pixels (can be changed later). Must be one of the
supported resolutions. If `None`, the resolution will be chosen by width only. If also `width` is
`None`, then the default camera resolution will be used.
:type height: int|None
:param frame_id: The ROS TF frame assigned to the camera.
:type frame_id: basestring
:param camera_info_url: The URL pointing to the camera calaibration, if available.
:type camera_info_url: basestring
:param use_encrypted_password: Whether to use Plain HTTP Auth (False) or Digest HTTP Auth (True).
:type use_encrypted_password: bool
:param camera_id: ID (number) of the camera. Can be 1 to 4.
:type camera_id: int
:param auto_wakeup_camera: If True, there will be a wakeup trial after first unsuccessful network command.
:type auto_wakeup_camera: bool
:param compression: Compression of the image (0 - no compression, 100 - max compression).
:type compression: int
:param fps: The desired frames per second.
:type fps: int
:param use_color: If True, send a color stream, otherwise send only grayscale image.
:type use_color: bool
:param use_square_pixels: If True, the resolution will be stretched to match 1:1 pixels.
By default, the pixels have a ratio of 11:12.
:type use_square_pixels: bool
:raises: :py:exc:`ValueError` if the requested resolution (either the `resolution`, or `width`+`height`
is not supported. | nodes/axis.py | __init__ | MarcoStb1993/axis_camera | python | def __init__(self, hostname, username, password, width, height, frame_id, camera_info_url, use_encrypted_password, camera_id=1, auto_wakeup_camera=True, compression=0, fps=24, use_color=True, use_square_pixels=False):
'Create the ROS-VAPIX interface.\n\n :param hostname: Hostname of the camera (without http://, can be an IP address).\n :type hostname: basestring\n :param username: If login is needed, provide a username here.\n :type username: :py:obj:`basestring` | None\n :param password: If login is needed, provide a password here.\n :type password: :py:obj:`basestring` | None\n :param width: Width of the requested video stream in pixels (can be changed later). Must be one of the supported\n resolutions. If `None`, the resolution will be chosen by height only. If also `height` is `None`,\n then the default camera resolution will be used.\n :type width: int|None\n :param height: Height of the requested video stream in pixels (can be changed later). Must be one of the\n supported resolutions. If `None`, the resolution will be chosen by width only. If also `width` is\n `None`, then the default camera resolution will be used.\n :type height: int|None\n :param frame_id: The ROS TF frame assigned to the camera.\n :type frame_id: basestring\n :param camera_info_url: The URL pointing to the camera calaibration, if available.\n :type camera_info_url: basestring\n :param use_encrypted_password: Whether to use Plain HTTP Auth (False) or Digest HTTP Auth (True).\n :type use_encrypted_password: bool\n :param camera_id: ID (number) of the camera. Can be 1 to 4.\n :type camera_id: int\n :param auto_wakeup_camera: If True, there will be a wakeup trial after first unsuccessful network command.\n :type auto_wakeup_camera: bool\n :param compression: Compression of the image (0 - no compression, 100 - max compression).\n :type compression: int\n :param fps: The desired frames per second.\n :type fps: int\n :param use_color: If True, send a color stream, otherwise send only grayscale image.\n :type use_color: bool\n :param use_square_pixels: If True, the resolution will be stretched to match 1:1 pixels.\n By default, the pixels have a ratio of 11:12.\n :type use_square_pixels: bool\n :raises: :py:exc:`ValueError` if the requested resolution (either the `resolution`, or `width`+`height`\n is not supported.\n '
self.video_params_changed = False
self.__initializing = True
self._hostname = hostname
self._camera_id = camera_id
self.diagnostic_updater = Updater()
self.diagnostic_updater.setHardwareID(hostname)
self._api = None
while ((self._api is None) and (not rospy.is_shutdown())):
try:
self._api = VAPIX.get_api_for_camera(hostname, username, password, camera_id, use_encrypted_password)
except (IOError, ValueError):
rospy.loginfo(('Retrying connection to VAPIX on host %s, camera %d in 2 seconds.' % (hostname, camera_id)))
rospy.sleep(2)
if rospy.is_shutdown():
return
self._allowed_resolutions = self._get_allowed_resolutions()
rospy.loginfo(('The following resolutions are available for camera %d:\n%s' % (camera_id, '\n'.join([str(res) for res in self._allowed_resolutions]))))
rospy.set_param('~allowed_resolutions', [res.get_vapix_representation() for res in self._allowed_resolutions])
self._auto_wakeup_camera = auto_wakeup_camera
self._width = None
self._height = None
self._resolution = None
self._compression = None
self._fps = None
self._use_color = None
self._use_square_pixels = None
width = (width if (width != ) else None)
height = (height if (height != ) else None)
if ((width is None) and (height is None)):
self.set_resolution(self._allowed_resolutions[0])
else:
resolution = self.find_resolution_by_size(width, height)
self.set_resolution(resolution.get_vapix_representation())
self.set_compression(compression)
self.set_fps(fps)
self.set_use_color(use_color)
self.set_use_square_pixels(use_square_pixels)
change_enum_items(VideoStreamConfig, 'resolution', [{'name': (res.name if isinstance(res, CIFVideoResolution) else str(res)), 'value': res.get_vapix_representation(), 'description': str(res)} for res in self._allowed_resolutions], self._resolution.get_vapix_representation())
self._video_stream_param_change_server = dynamic_reconfigure.server.Server(VideoStreamConfig, self.reconfigure_video)
self._frame_id = frame_id
self._camera_info_url = camera_info_url
self._camera_name = camera_info_manager.genCameraName(self._hostname)
self._camera_info = camera_info_manager.CameraInfoManager(cname=self._camera_name, url=self._camera_info_url)
self._camera_info.loadCameraInfo()
self._streaming_thread = None
self._video_publisher_frequency_diagnostic = FrequencyStatusParam({'min': self._fps, 'max': self._fps})
self._video_publisher = PausableDiagnosedPublisher(self, rospy.Publisher('image_raw/compressed', CompressedImage, self, queue_size=100), self.diagnostic_updater, self._video_publisher_frequency_diagnostic, TimeStampStatusParam())
self._camera_info_publisher = PausableDiagnosedPublisher(self, rospy.Publisher('camera_info', CameraInfo, self, queue_size=100), self.diagnostic_updater, self._video_publisher_frequency_diagnostic, TimeStampStatusParam())
self._snapshot_server = rospy.Service('take_snapshot', TakeSnapshot, self.take_snapshot)
self.diagnostic_updater.add(FunctionDiagnosticTask('Camera parameters', self._camera_diagnostic_callback))
self.username = username
self.password = password
self.use_encrypted_password = use_encrypted_password
self.st = None
self.pub = self._video_publisher
self.caminfo_pub = self._camera_info_publisher
self.__initializing = False |
def peer_subscribe(self, topic_name, topic_publish, peer_publish):
'Lazy-start the image-publisher.'
if (self._streaming_thread is None):
self._streaming_thread = ImageStreamingThread(self)
self._streaming_thread.start()
else:
self._streaming_thread.resume() | -9,192,376,579,225,204,000 | Lazy-start the image-publisher. | nodes/axis.py | peer_subscribe | MarcoStb1993/axis_camera | python | def peer_subscribe(self, topic_name, topic_publish, peer_publish):
if (self._streaming_thread is None):
self._streaming_thread = ImageStreamingThread(self)
self._streaming_thread.start()
else:
self._streaming_thread.resume() |
def peer_unsubscribe(self, topic_name, num_peers):
'Lazy-stop the image-publisher when nobody is interested'
if (num_peers == 0):
self._streaming_thread.pause() | 3,966,300,546,944,964,600 | Lazy-stop the image-publisher when nobody is interested | nodes/axis.py | peer_unsubscribe | MarcoStb1993/axis_camera | python | def peer_unsubscribe(self, topic_name, num_peers):
if (num_peers == 0):
self._streaming_thread.pause() |
def take_snapshot(self, request):
'Retrieve a snapshot from the camera.\n\n :param request: The service request.\n :type request: :py:class:`axis_camera.srv.TakeSnapshotRequest`\n :return: The response containing the image.\n :rtype: :py:class:`axis_camera.srv.TakeSnapshotResponse`\n :raises: :py:exc:`IOError`, :py:exc:`urllib2.URLError`\n '
image_data = self._api.take_snapshot()
image = CompressedImage()
image.header.stamp = rospy.Time.now()
image.header.frame_id = self._frame_id
image.format = 'jpeg'
image.data = image_data
response = TakeSnapshotResponse()
response.image = image
return response | 5,884,849,822,967,185,000 | Retrieve a snapshot from the camera.
:param request: The service request.
:type request: :py:class:`axis_camera.srv.TakeSnapshotRequest`
:return: The response containing the image.
:rtype: :py:class:`axis_camera.srv.TakeSnapshotResponse`
:raises: :py:exc:`IOError`, :py:exc:`urllib2.URLError` | nodes/axis.py | take_snapshot | MarcoStb1993/axis_camera | python | def take_snapshot(self, request):
'Retrieve a snapshot from the camera.\n\n :param request: The service request.\n :type request: :py:class:`axis_camera.srv.TakeSnapshotRequest`\n :return: The response containing the image.\n :rtype: :py:class:`axis_camera.srv.TakeSnapshotResponse`\n :raises: :py:exc:`IOError`, :py:exc:`urllib2.URLError`\n '
image_data = self._api.take_snapshot()
image = CompressedImage()
image.header.stamp = rospy.Time.now()
image.header.frame_id = self._frame_id
image.format = 'jpeg'
image.data = image_data
response = TakeSnapshotResponse()
response.image = image
return response |
def reconfigure_video(self, config, level):
'Dynamic reconfigure callback for video parameters.\n\n :param config: The requested configuration.\n :type config: dict\n :param level: Unused here.\n :type level: int\n :return: The config corresponding to what was really achieved.\n :rtype: dict\n '
if self.__initializing:
config.compression = self._compression
config.fps = self._fps
config.use_color = self._use_color
config.use_square_pixels = self._use_square_pixels
config.resolution = self._resolution.get_vapix_representation()
else:
self.__try_set_value_from_config(config, 'compression', self.set_compression)
self.__try_set_value_from_config(config, 'fps', self.set_fps)
self.__try_set_value_from_config(config, 'use_color', self.set_use_color)
self.__try_set_value_from_config(config, 'use_square_pixels', self.set_use_square_pixels)
try:
self.set_resolution(config.resolution)
except ValueError:
config.resolution = self._resolution.get_vapix_representation()
return config | -8,028,459,420,616,422,000 | Dynamic reconfigure callback for video parameters.
:param config: The requested configuration.
:type config: dict
:param level: Unused here.
:type level: int
:return: The config corresponding to what was really achieved.
:rtype: dict | nodes/axis.py | reconfigure_video | MarcoStb1993/axis_camera | python | def reconfigure_video(self, config, level):
'Dynamic reconfigure callback for video parameters.\n\n :param config: The requested configuration.\n :type config: dict\n :param level: Unused here.\n :type level: int\n :return: The config corresponding to what was really achieved.\n :rtype: dict\n '
if self.__initializing:
config.compression = self._compression
config.fps = self._fps
config.use_color = self._use_color
config.use_square_pixels = self._use_square_pixels
config.resolution = self._resolution.get_vapix_representation()
else:
self.__try_set_value_from_config(config, 'compression', self.set_compression)
self.__try_set_value_from_config(config, 'fps', self.set_fps)
self.__try_set_value_from_config(config, 'use_color', self.set_use_color)
self.__try_set_value_from_config(config, 'use_square_pixels', self.set_use_square_pixels)
try:
self.set_resolution(config.resolution)
except ValueError:
config.resolution = self._resolution.get_vapix_representation()
return config |
def __try_set_value_from_config(self, config, field, setter):
"First, try to call `setter(config[field])`, and if this call doesn't succeed. set the field in config to\n its value stored in this class.\n\n :param config: The dynamic reconfigure config dictionary.\n :type config: dict\n :param field: The field name (both in :py:obj:`config` and in :py:obj:`self`).\n :type field: basestring\n :param setter: The setter to use to set the value.\n :type setter: lambda function\n "
try:
setter(config[field])
except ValueError:
config[field] = getattr(self, field) | 7,981,268,935,643,443,000 | First, try to call `setter(config[field])`, and if this call doesn't succeed. set the field in config to
its value stored in this class.
:param config: The dynamic reconfigure config dictionary.
:type config: dict
:param field: The field name (both in :py:obj:`config` and in :py:obj:`self`).
:type field: basestring
:param setter: The setter to use to set the value.
:type setter: lambda function | nodes/axis.py | __try_set_value_from_config | MarcoStb1993/axis_camera | python | def __try_set_value_from_config(self, config, field, setter):
"First, try to call `setter(config[field])`, and if this call doesn't succeed. set the field in config to\n its value stored in this class.\n\n :param config: The dynamic reconfigure config dictionary.\n :type config: dict\n :param field: The field name (both in :py:obj:`config` and in :py:obj:`self`).\n :type field: basestring\n :param setter: The setter to use to set the value.\n :type setter: lambda function\n "
try:
setter(config[field])
except ValueError:
config[field] = getattr(self, field) |
def set_resolution(self, resolution_value):
'Request a new resolution for the video stream.\n\n :param resolution_value: The string of type `width`x`height` or a :py:class:`VideoResolution` object.\n :type resolution_value: basestring|VideoResolution\n :raises: :py:exc:`ValueError` if the resolution is unknown/unsupported.\n '
resolution = None
if isinstance(resolution_value, VideoResolution):
resolution = resolution_value
elif isinstance(resolution_value, basestring):
resolution = self._get_resolution_from_param_value(resolution_value)
if (resolution is None):
raise ValueError(('Unsupported resolution type specified: %r' % resolution_value))
if ((self._resolution is None) or (resolution != self._resolution)):
self._resolution = resolution
self.video_params_changed = True
self._width = resolution.get_resolution(self._use_square_pixels)[0]
self._height = resolution.get_resolution(self._use_square_pixels)[1] | 1,512,016,567,957,172,000 | Request a new resolution for the video stream.
:param resolution_value: The string of type `width`x`height` or a :py:class:`VideoResolution` object.
:type resolution_value: basestring|VideoResolution
:raises: :py:exc:`ValueError` if the resolution is unknown/unsupported. | nodes/axis.py | set_resolution | MarcoStb1993/axis_camera | python | def set_resolution(self, resolution_value):
'Request a new resolution for the video stream.\n\n :param resolution_value: The string of type `width`x`height` or a :py:class:`VideoResolution` object.\n :type resolution_value: basestring|VideoResolution\n :raises: :py:exc:`ValueError` if the resolution is unknown/unsupported.\n '
resolution = None
if isinstance(resolution_value, VideoResolution):
resolution = resolution_value
elif isinstance(resolution_value, basestring):
resolution = self._get_resolution_from_param_value(resolution_value)
if (resolution is None):
raise ValueError(('Unsupported resolution type specified: %r' % resolution_value))
if ((self._resolution is None) or (resolution != self._resolution)):
self._resolution = resolution
self.video_params_changed = True
self._width = resolution.get_resolution(self._use_square_pixels)[0]
self._height = resolution.get_resolution(self._use_square_pixels)[1] |
def _get_resolution_from_param_value(self, value):
'Return a :py:class:`VideoResolution` object corresponding to the given video resolution param string.\n\n :param value: Value of the resolution parameter to parse (of form `width`x`height`).\n :type value: basestring\n :return: The :py:class:`VideoResolution` corresponding to the given resolution param string.\n :rtype: :py:class:`VideoResolution`\n :raises: :py:exc:`ValueError` if the resolution is unknown/unsupported.\n '
for resolution in self._allowed_resolutions:
if (resolution.get_vapix_representation() == value):
return resolution
raise ValueError(('%s is not a valid valid resolution.' % value)) | -8,950,817,674,447,291,000 | Return a :py:class:`VideoResolution` object corresponding to the given video resolution param string.
:param value: Value of the resolution parameter to parse (of form `width`x`height`).
:type value: basestring
:return: The :py:class:`VideoResolution` corresponding to the given resolution param string.
:rtype: :py:class:`VideoResolution`
:raises: :py:exc:`ValueError` if the resolution is unknown/unsupported. | nodes/axis.py | _get_resolution_from_param_value | MarcoStb1993/axis_camera | python | def _get_resolution_from_param_value(self, value):
'Return a :py:class:`VideoResolution` object corresponding to the given video resolution param string.\n\n :param value: Value of the resolution parameter to parse (of form `width`x`height`).\n :type value: basestring\n :return: The :py:class:`VideoResolution` corresponding to the given resolution param string.\n :rtype: :py:class:`VideoResolution`\n :raises: :py:exc:`ValueError` if the resolution is unknown/unsupported.\n '
for resolution in self._allowed_resolutions:
if (resolution.get_vapix_representation() == value):
return resolution
raise ValueError(('%s is not a valid valid resolution.' % value)) |
def find_resolution_by_size(self, width, height):
'Return a :py:class:`VideoResolution` object with the given dimensions.\n\n If there are more resolutions with the same size, any of them may be returned.\n\n :param width: Image width in pixels. If `None`, resolutions will be matched only by height.\n :type width: int|None\n :param height: Image height in pixels. If `None`, resolutions will be matched only by width.\n :type height: int|None\n :return: The corresponding resolution object.\n :rtype: :py:class:`VideoResolution`\n :raises: :py:exc:`ValueError` if no resolution with the given dimensions can be found.\n :raises: :py:exc:`ValueError` if both `width` and `height` are None.\n '
if ((width is None) and (height is None)):
raise ValueError('Either width or height of the desired resolution must be specified.')
for resolution in self._allowed_resolutions:
size = resolution.get_resolution(use_square_pixels=False)
if (((width is None) or (width == size[0])) and ((height is None) or (height == size[1]))):
return resolution
size = resolution.get_resolution(use_square_pixels=True)
if (((width is None) or (width == size[0])) and ((height is None) or (height == size[1]))):
return resolution
raise ValueError(('Cannot find a supported resolution with dimensions %sx%s' % (width, height))) | -2,798,699,544,438,996,500 | Return a :py:class:`VideoResolution` object with the given dimensions.
If there are more resolutions with the same size, any of them may be returned.
:param width: Image width in pixels. If `None`, resolutions will be matched only by height.
:type width: int|None
:param height: Image height in pixels. If `None`, resolutions will be matched only by width.
:type height: int|None
:return: The corresponding resolution object.
:rtype: :py:class:`VideoResolution`
:raises: :py:exc:`ValueError` if no resolution with the given dimensions can be found.
:raises: :py:exc:`ValueError` if both `width` and `height` are None. | nodes/axis.py | find_resolution_by_size | MarcoStb1993/axis_camera | python | def find_resolution_by_size(self, width, height):
'Return a :py:class:`VideoResolution` object with the given dimensions.\n\n If there are more resolutions with the same size, any of them may be returned.\n\n :param width: Image width in pixels. If `None`, resolutions will be matched only by height.\n :type width: int|None\n :param height: Image height in pixels. If `None`, resolutions will be matched only by width.\n :type height: int|None\n :return: The corresponding resolution object.\n :rtype: :py:class:`VideoResolution`\n :raises: :py:exc:`ValueError` if no resolution with the given dimensions can be found.\n :raises: :py:exc:`ValueError` if both `width` and `height` are None.\n '
if ((width is None) and (height is None)):
raise ValueError('Either width or height of the desired resolution must be specified.')
for resolution in self._allowed_resolutions:
size = resolution.get_resolution(use_square_pixels=False)
if (((width is None) or (width == size[0])) and ((height is None) or (height == size[1]))):
return resolution
size = resolution.get_resolution(use_square_pixels=True)
if (((width is None) or (width == size[0])) and ((height is None) or (height == size[1]))):
return resolution
raise ValueError(('Cannot find a supported resolution with dimensions %sx%s' % (width, height))) |
def _get_allowed_resolutions(self):
'Return a list of resolutions supported both by the camera.\n\n :return: The supported resolutions list.\n :rtype: list of :py:class:`VideoResolution`\n '
camera_resolutions = self._get_resolutions_supported_by_camera()
return camera_resolutions | -3,372,507,955,636,219,000 | Return a list of resolutions supported both by the camera.
:return: The supported resolutions list.
:rtype: list of :py:class:`VideoResolution` | nodes/axis.py | _get_allowed_resolutions | MarcoStb1993/axis_camera | python | def _get_allowed_resolutions(self):
'Return a list of resolutions supported both by the camera.\n\n :return: The supported resolutions list.\n :rtype: list of :py:class:`VideoResolution`\n '
camera_resolutions = self._get_resolutions_supported_by_camera()
return camera_resolutions |
def _get_resolutions_supported_by_camera(self):
'Return a list of resolutions supported the camera.\n\n :return: The supported resolutions list.\n :rtype: list of :py:class:`VideoResolution`\n '
try:
names = self._api.parse_list_parameter_value(self._api.get_parameter('Properties.Image.Resolution'))
return [VideoResolution.parse_from_vapix_param_value(name, self._api) for name in names]
except (IOError, ValueError):
rospy.logwarn('Could not determine resolutions supported by the camera. Asssuming only CIF.')
return [CIFVideoResolution('CIF', 384, 288)] | -8,883,113,227,496,016,000 | Return a list of resolutions supported the camera.
:return: The supported resolutions list.
:rtype: list of :py:class:`VideoResolution` | nodes/axis.py | _get_resolutions_supported_by_camera | MarcoStb1993/axis_camera | python | def _get_resolutions_supported_by_camera(self):
'Return a list of resolutions supported the camera.\n\n :return: The supported resolutions list.\n :rtype: list of :py:class:`VideoResolution`\n '
try:
names = self._api.parse_list_parameter_value(self._api.get_parameter('Properties.Image.Resolution'))
return [VideoResolution.parse_from_vapix_param_value(name, self._api) for name in names]
except (IOError, ValueError):
rospy.logwarn('Could not determine resolutions supported by the camera. Asssuming only CIF.')
return [CIFVideoResolution('CIF', 384, 288)] |
def set_compression(self, compression):
'Request the given compression level for the video stream.\n\n :param compression: Compression of the image (0 - no compression, 100 - max compression).\n :type compression: int\n :raises: :py:exc:`ValueError` if the given compression level is outside the allowed range.\n '
if (compression != self._compression):
self._compression = self.sanitize_compression(compression)
self.video_params_changed = True | -1,130,117,131,443,176,700 | Request the given compression level for the video stream.
:param compression: Compression of the image (0 - no compression, 100 - max compression).
:type compression: int
:raises: :py:exc:`ValueError` if the given compression level is outside the allowed range. | nodes/axis.py | set_compression | MarcoStb1993/axis_camera | python | def set_compression(self, compression):
'Request the given compression level for the video stream.\n\n :param compression: Compression of the image (0 - no compression, 100 - max compression).\n :type compression: int\n :raises: :py:exc:`ValueError` if the given compression level is outside the allowed range.\n '
if (compression != self._compression):
self._compression = self.sanitize_compression(compression)
self.video_params_changed = True |
@staticmethod
def sanitize_compression(compression):
'Make sure the given value can be used as a compression level of the video stream.\n\n :param compression: Compression of the image (0 - no compression, 100 - max compression).\n :type compression: int\n :return: The given compression converted to an int.\n :rtype: int\n :raises: :py:exc:`ValueError` if the given compression level is outside the allowed range.\n '
compression = int(compression)
if (not (0 <= compression <= 100)):
raise ValueError(('%s is not a valid value for compression.' % str(compression)))
return compression | -7,312,961,599,501,351,000 | Make sure the given value can be used as a compression level of the video stream.
:param compression: Compression of the image (0 - no compression, 100 - max compression).
:type compression: int
:return: The given compression converted to an int.
:rtype: int
:raises: :py:exc:`ValueError` if the given compression level is outside the allowed range. | nodes/axis.py | sanitize_compression | MarcoStb1993/axis_camera | python | @staticmethod
def sanitize_compression(compression):
'Make sure the given value can be used as a compression level of the video stream.\n\n :param compression: Compression of the image (0 - no compression, 100 - max compression).\n :type compression: int\n :return: The given compression converted to an int.\n :rtype: int\n :raises: :py:exc:`ValueError` if the given compression level is outside the allowed range.\n '
compression = int(compression)
if (not (0 <= compression <= 100)):
raise ValueError(('%s is not a valid value for compression.' % str(compression)))
return compression |
def set_fps(self, fps):
'Request the given compression level for the video stream.\n\n :param fps: The desired frames per second.\n :type fps: int\n :raises: :py:exc:`ValueError` if the given FPS is outside the allowed range.\n '
if (fps != self._fps):
self._fps = self.sanitize_fps(fps)
self.video_params_changed = True
if hasattr(self, '_video_publisher_frequency_diagnostic'):
self._video_publisher_frequency_diagnostic.freq_bound['min'] = self._fps
self._video_publisher_frequency_diagnostic.freq_bound['max'] = self._fps | -1,207,212,672,288,412,200 | Request the given compression level for the video stream.
:param fps: The desired frames per second.
:type fps: int
:raises: :py:exc:`ValueError` if the given FPS is outside the allowed range. | nodes/axis.py | set_fps | MarcoStb1993/axis_camera | python | def set_fps(self, fps):
'Request the given compression level for the video stream.\n\n :param fps: The desired frames per second.\n :type fps: int\n :raises: :py:exc:`ValueError` if the given FPS is outside the allowed range.\n '
if (fps != self._fps):
self._fps = self.sanitize_fps(fps)
self.video_params_changed = True
if hasattr(self, '_video_publisher_frequency_diagnostic'):
self._video_publisher_frequency_diagnostic.freq_bound['min'] = self._fps
self._video_publisher_frequency_diagnostic.freq_bound['max'] = self._fps |
@staticmethod
def sanitize_fps(fps):
'Make sure the given value can be used as FPS of the video stream.\n\n :param fps: The desired frames per second.\n :type fps: int\n :return: The given FPS converted to an int.\n :rtype: int\n :raises: :py:exc:`ValueError` if the given FPS is outside the allowed range.\n '
fps = int(fps)
if (not (1 <= fps <= 30)):
raise ValueError(('%s is not a valid value for FPS.' % str(fps)))
return fps | 7,733,244,502,197,703,000 | Make sure the given value can be used as FPS of the video stream.
:param fps: The desired frames per second.
:type fps: int
:return: The given FPS converted to an int.
:rtype: int
:raises: :py:exc:`ValueError` if the given FPS is outside the allowed range. | nodes/axis.py | sanitize_fps | MarcoStb1993/axis_camera | python | @staticmethod
def sanitize_fps(fps):
'Make sure the given value can be used as FPS of the video stream.\n\n :param fps: The desired frames per second.\n :type fps: int\n :return: The given FPS converted to an int.\n :rtype: int\n :raises: :py:exc:`ValueError` if the given FPS is outside the allowed range.\n '
fps = int(fps)
if (not (1 <= fps <= 30)):
raise ValueError(('%s is not a valid value for FPS.' % str(fps)))
return fps |
def set_use_color(self, use_color):
'Request using/not using color in the video stream.\n :param use_color: If True, send a color stream, otherwise send only grayscale image.\n\n :type use_color: bool\n :raises: :py:exc:`ValueError` if the given argument is not a bool.\n '
if (use_color != self._use_color):
self._use_color = self.sanitize_bool(use_color, 'use_color')
self.video_params_changed = True | 2,469,160,273,032,331,300 | Request using/not using color in the video stream.
:param use_color: If True, send a color stream, otherwise send only grayscale image.
:type use_color: bool
:raises: :py:exc:`ValueError` if the given argument is not a bool. | nodes/axis.py | set_use_color | MarcoStb1993/axis_camera | python | def set_use_color(self, use_color):
'Request using/not using color in the video stream.\n :param use_color: If True, send a color stream, otherwise send only grayscale image.\n\n :type use_color: bool\n :raises: :py:exc:`ValueError` if the given argument is not a bool.\n '
if (use_color != self._use_color):
self._use_color = self.sanitize_bool(use_color, 'use_color')
self.video_params_changed = True |
def set_use_square_pixels(self, use_square_pixels):
'Request using/not using square pixels.\n\n :param use_square_pixels: If True, the resolution will be stretched to match 1:1 pixels.\n By default, the pixels have a ratio of 11:12.\n :type use_square_pixels: bool\n :raises: :py:exc:`ValueError` if the given argument is not a bool.\n '
if (use_square_pixels != self._use_square_pixels):
self._use_square_pixels = self.sanitize_bool(use_square_pixels, 'use_square_pixels')
self.video_params_changed = True | -3,645,591,623,173,462,000 | Request using/not using square pixels.
:param use_square_pixels: If True, the resolution will be stretched to match 1:1 pixels.
By default, the pixels have a ratio of 11:12.
:type use_square_pixels: bool
:raises: :py:exc:`ValueError` if the given argument is not a bool. | nodes/axis.py | set_use_square_pixels | MarcoStb1993/axis_camera | python | def set_use_square_pixels(self, use_square_pixels):
'Request using/not using square pixels.\n\n :param use_square_pixels: If True, the resolution will be stretched to match 1:1 pixels.\n By default, the pixels have a ratio of 11:12.\n :type use_square_pixels: bool\n :raises: :py:exc:`ValueError` if the given argument is not a bool.\n '
if (use_square_pixels != self._use_square_pixels):
self._use_square_pixels = self.sanitize_bool(use_square_pixels, 'use_square_pixels')
self.video_params_changed = True |
@staticmethod
def sanitize_bool(value, field_name):
'Convert the given value to a bool.\n\n :param value: Either True, False,, "1", "0", 1 or 0.\n :type value: :py:class:`basestring` | :py:class:`bool` | :py:class:`int`\n :param field_name: Name of the field this value belongs to (just for debug messages).\n :type field_name: basestring\n :return: The bool value of the given value.\n :rtype: :py:class:`bool`\n :raises: :py:exc:`ValueError` if the given value is not supported in this conversion.\n '
if (value not in (True, False, '1', '0', 1, 0)):
raise ValueError(('%s is not a valid value for %s.' % (str(value), field_name)))
if (value == '0'):
return False
return bool(value) | 4,932,215,436,621,322,000 | Convert the given value to a bool.
:param value: Either True, False,, "1", "0", 1 or 0.
:type value: :py:class:`basestring` | :py:class:`bool` | :py:class:`int`
:param field_name: Name of the field this value belongs to (just for debug messages).
:type field_name: basestring
:return: The bool value of the given value.
:rtype: :py:class:`bool`
:raises: :py:exc:`ValueError` if the given value is not supported in this conversion. | nodes/axis.py | sanitize_bool | MarcoStb1993/axis_camera | python | @staticmethod
def sanitize_bool(value, field_name):
'Convert the given value to a bool.\n\n :param value: Either True, False,, "1", "0", 1 or 0.\n :type value: :py:class:`basestring` | :py:class:`bool` | :py:class:`int`\n :param field_name: Name of the field this value belongs to (just for debug messages).\n :type field_name: basestring\n :return: The bool value of the given value.\n :rtype: :py:class:`bool`\n :raises: :py:exc:`ValueError` if the given value is not supported in this conversion.\n '
if (value not in (True, False, '1', '0', 1, 0)):
raise ValueError(('%s is not a valid value for %s.' % (str(value), field_name)))
if (value == '0'):
return False
return bool(value) |
def __init__(self, width, height):
'Create a representation of the resolution.\n\n :param width: Width of the resolution in pixels.\n :type width: int\n :param height: Height of the resolution in pixels.\n :type height: int\n '
super(VideoResolution, self).__init__()
self.width = int(width)
self.height = int(height)
self.square_pixel_conversion_ratio_width = (12.0 / 11.0)
self.square_pixel_conversion_ratio_height = 1 | -5,380,199,725,355,814,000 | Create a representation of the resolution.
:param width: Width of the resolution in pixels.
:type width: int
:param height: Height of the resolution in pixels.
:type height: int | nodes/axis.py | __init__ | MarcoStb1993/axis_camera | python | def __init__(self, width, height):
'Create a representation of the resolution.\n\n :param width: Width of the resolution in pixels.\n :type width: int\n :param height: Height of the resolution in pixels.\n :type height: int\n '
super(VideoResolution, self).__init__()
self.width = int(width)
self.height = int(height)
self.square_pixel_conversion_ratio_width = (12.0 / 11.0)
self.square_pixel_conversion_ratio_height = 1 |
def get_resolution(self, use_square_pixels=False):
'Get the image dimensions corresponding to this resolution.\n\n :param use_square_pixels: Whether to strech the resulting resolution to square pixels.\n :type use_square_pixels: bool\n :return: A tuple (width, height)\n :rtype: tuple\n '
width = self.width
height = self.height
if use_square_pixels:
width = int(math.ceil((self.square_pixel_conversion_ratio_width * self.width)))
height = int(math.ceil((self.square_pixel_conversion_ratio_height * self.height)))
return (width, height) | -3,825,175,919,994,191,400 | Get the image dimensions corresponding to this resolution.
:param use_square_pixels: Whether to strech the resulting resolution to square pixels.
:type use_square_pixels: bool
:return: A tuple (width, height)
:rtype: tuple | nodes/axis.py | get_resolution | MarcoStb1993/axis_camera | python | def get_resolution(self, use_square_pixels=False):
'Get the image dimensions corresponding to this resolution.\n\n :param use_square_pixels: Whether to strech the resulting resolution to square pixels.\n :type use_square_pixels: bool\n :return: A tuple (width, height)\n :rtype: tuple\n '
width = self.width
height = self.height
if use_square_pixels:
width = int(math.ceil((self.square_pixel_conversion_ratio_width * self.width)))
height = int(math.ceil((self.square_pixel_conversion_ratio_height * self.height)))
return (width, height) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.