INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Adds a callback to call upon failure | def add_failure_cleanup(self, function, *args, **kwargs):
"""Adds a callback to call upon failure"""
with self._failure_cleanups_lock:
self._failure_cleanups.append(
FunctionContainer(function, *args, **kwargs)) |
Announce that future is done running and run associated callbacks | def announce_done(self):
"""Announce that future is done running and run associated callbacks
This will run any failure cleanups if the transfer failed if not
they have not been run, allows the result() to be unblocked, and will
run any done callbacks associated to the TransferFuture if... |
Submit a task to complete | def submit(self, task, tag=None, block=True):
"""Submit a task to complete
:type task: s3transfer.tasks.Task
:param task: The task to run __call__ on
:type tag: s3transfer.futures.TaskTag
:param tag: An optional tag to associate to the task. This
is used to overrid... |
Adds a callback to be completed once future is done | def add_done_callback(self, fn):
"""Adds a callback to be completed once future is done
:parm fn: A callable that takes no arguments. Note that is different
than concurrent.futures.Future.add_done_callback that requires
a single argument for the future.
"""
# The... |
: param client: The client associated with the transfer manager | def _submit(self, client, request_executor, transfer_future, **kwargs):
"""
:param client: The client associated with the transfer manager
:type config: s3transfer.manager.TransferConfig
:param config: The transfer config associated with the transfer
manager
:type o... |
: param client: The client associated with the transfer manager | def _submit(self, client, config, osutil, request_executor,
transfer_future):
"""
:param client: The client associated with the transfer manager
:type config: s3transfer.manager.TransferConfig
:param config: The transfer config associated with the transfer
ma... |
: param client: The client to use when calling PutObject: param copy_source: The CopySource parameter to use: param bucket: The name of the bucket to copy to: param key: The name of the key to copy to: param extra_args: A dictionary of any extra arguments that may be used in the upload.: param callbacks: List of callba... | def _main(self, client, copy_source, bucket, key, extra_args, callbacks,
size):
"""
:param client: The client to use when calling PutObject
:param copy_source: The CopySource parameter to use
:param bucket: The name of the bucket to copy to
:param key: The name of t... |
: param client: The client to use when calling PutObject: param copy_source: The CopySource parameter to use: param bucket: The name of the bucket to upload to: param key: The name of the key to upload to: param upload_id: The id of the upload: param part_number: The number representing the part of the multipart upload... | def _main(self, client, copy_source, bucket, key, upload_id, part_number,
extra_args, callbacks, size):
"""
:param client: The client to use when calling PutObject
:param copy_source: The CopySource parameter to use
:param bucket: The name of the bucket to upload to
... |
Convenience factory function to create from a filename. | def from_filename(cls, filename, start_byte, chunk_size, callback=None,
enable_callback=True):
"""Convenience factory function to create from a filename.
:type start_byte: int
:param start_byte: The first byte from which to start reading.
:type chunk_size: int
... |
Upload a file to an S3 object. | def upload_file(self, filename, bucket, key,
callback=None, extra_args=None):
"""Upload a file to an S3 object.
Variants have also been injected into S3 client, Bucket and Object.
You don't have to use S3Transfer.upload_file() directly.
"""
if extra_args is N... |
Download an S3 object to a file. | def download_file(self, bucket, key, filename, extra_args=None,
callback=None):
"""Download an S3 object to a file.
Variants have also been injected into S3 client, Bucket and Object.
You don't have to use S3Transfer.download_file() directly.
"""
# This met... |
: type transfer_future: s3transfer. futures. TransferFuture: param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for | def _main(self, transfer_future, **kwargs):
"""
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future associated with the
transfer request that tasks are being submitted for
:param kwargs: Any additional kwargs that you may want... |
: param client: The client to use when calling CreateMultipartUpload: param bucket: The name of the bucket to upload to: param key: The name of the key to upload to: param extra_args: A dictionary of any extra arguments that may be used in the intialization. | def _main(self, client, bucket, key, extra_args):
"""
:param client: The client to use when calling CreateMultipartUpload
:param bucket: The name of the bucket to upload to
:param key: The name of the key to upload to
:param extra_args: A dictionary of any extra arguments that ma... |
: param client: The client to use when calling CompleteMultipartUpload: param bucket: The name of the bucket to upload to: param key: The name of the key to upload to: param upload_id: The id of the upload: param parts: A list of parts to use to complete the multipart upload:: | def _main(self, client, bucket, key, upload_id, parts, extra_args):
"""
:param client: The client to use when calling CompleteMultipartUpload
:param bucket: The name of the bucket to upload to
:param key: The name of the key to upload to
:param upload_id: The id of the upload
... |
Create a PythonFile object with specified file_path and content. If content is None then it is loaded from the file_path method. Otherwise file_path is only used for reporting errors. | def parse(file_path, content=None):
"""
Create a PythonFile object with specified file_path and content.
If content is None then, it is loaded from the file_path method.
Otherwise, file_path is only used for reporting errors.
"""
try:
# Parso reads files in bi... |
Find functions with step decorator in parsed file | def _iter_step_func_decorators(self):
"""Find functions with step decorator in parsed file"""
func_defs = [func for func in self.py_tree.iter_funcdefs()] + [func for cls in self.py_tree.iter_classdefs() for func in cls.iter_funcdefs()]
for func in func_defs:
for decorator in func.get... |
Get the arguments passed to step decorators converted to python objects. | def _step_decorator_args(self, decorator):
"""
Get the arguments passed to step decorators
converted to python objects.
"""
args = decorator.children[3:-2]
step = None
if len(args) == 1:
try:
step = ast.literal_eval(args[0].get_code())
... |
Iterate over steps in the parsed file. | def iter_steps(self):
"""Iterate over steps in the parsed file."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
if step:
span = self._span_from_pos(decorator.start_pos, func.end_pos)
yield st... |
Find the ast node which contains the text. | def _find_step_node(self, step_text):
"""Find the ast node which contains the text."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
arg_node = decorator.children[3]
if step == step_text:
return a... |
Find the step with old_text and change it to new_text. The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old. | def refactor_step(self, old_text, new_text, move_param_from_idx):
"""
Find the step with old_text and change it to new_text.The step function
parameters are also changed according to move_param_from_idx.
Each entry in this list should specify parameter position from old.
"""
... |
Create a PythonFile object with specified file_path and content. If content is None then it is loaded from the file_path method. Otherwise file_path is only used for reporting errors. | def parse(file_path, content=None):
"""
Create a PythonFile object with specified file_path and content.
If content is None then, it is loaded from the file_path method.
Otherwise, file_path is only used for reporting errors.
"""
try:
if content is None:
... |
Find functions with step decorator in parsed file. | def _iter_step_func_decorators(self):
"""Find functions with step decorator in parsed file."""
for node in self.py_tree.find_all('def'):
for decorator in node.decorators:
if decorator.name.value == 'step':
yield node, decorator
break |
Get arguments passed to step decorators converted to python objects. | def _step_decorator_args(self, decorator):
"""
Get arguments passed to step decorators converted to python objects.
"""
args = decorator.call.value
step = None
if len(args) == 1:
try:
step = args[0].value.to_python()
except (ValueEr... |
Iterate over steps in the parsed file. | def iter_steps(self):
"""Iterate over steps in the parsed file."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
if step:
yield step, func.name, self._span_for_node(func, True) |
Find the ast node which contains the text. | def _find_step_node(self, step_text):
"""Find the ast node which contains the text."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
arg_node = decorator.call.value[0].value
if step == step_text:
... |
Find the step with old_text and change it to new_text. The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old | def refactor_step(self, old_text, new_text, move_param_from_idx):
"""
Find the step with old_text and change it to new_text.
The step function parameters are also changed according
to move_param_from_idx. Each entry in this list should
specify parameter position from old
... |
Select default parser for loading and refactoring steps. Passing redbaron as argument will select the old paring engine from v0. 3. 3 | def select_python_parser(parser=None):
"""
Select default parser for loading and refactoring steps. Passing `redbaron` as argument
will select the old paring engine from v0.3.3
Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our
best to make... |
List team memberships for a team by ID. | def list(self, teamId, max=None, **request_parameters):
"""List team memberships for a team, by ID.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all team memberships re... |
Add someone to a team by Person ID or email address. | def create(self, teamId, personId=None, personEmail=None,
isModerator=False, **request_parameters):
"""Add someone to a team by Person ID or email address.
Add someone to a team by Person ID or email address; optionally making
them a moderator.
Args:
teamId(b... |
Update a team membership by ID. | def update(self, membershipId, isModerator=None, **request_parameters):
"""Update a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
isModerator(bool): Set to True to make the person a team moderator.
**request_parameters: Additional re... |
Delete a team membership by ID. | def delete(self, membershipId):
"""Delete a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
che... |
Get a cat fact from catfact. ninja and return it as a string. | def get_catfact():
"""Get a cat fact from catfact.ninja and return it as a string.
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
to create the desired functionality into this bot.
"""
response = requests.get(CAT_FACTS_URL, verify=False)
response.raise_for_status()
... |
Respond to inbound webhook JSON HTTP POSTs from Webex Teams. | def POST(self):
"""Respond to inbound webhook JSON HTTP POSTs from Webex Teams."""
# Get the POST data sent from Webex Teams
json_data = web.data()
print("\nWEBHOOK POST RECEIVED:")
print(json_data, "\n")
# Create a Webhook object from the JSON data
webhook_obj =... |
List room memberships. | def list(self, roomId=None, personId=None, personEmail=None, max=None,
**request_parameters):
"""List room memberships.
By default, lists memberships for rooms to which the authenticated user
belongs.
Use query parameters to filter the response.
Use `roomId` to li... |
Delete a membership by ID. | def delete(self, membershipId):
"""Delete a membership, by ID.
Args:
membershipId(basestring): The membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(me... |
Convert a string ( bytes str or unicode ) to unicode. | def to_unicode(string):
"""Convert a string (bytes, str or unicode) to unicode."""
assert isinstance(string, basestring)
if sys.version_info[0] >= 3:
if isinstance(string, bytes):
return string.decode('utf-8')
else:
return string
else:
if isinstance(string... |
Convert a string ( bytes str or unicode ) to bytes. | def to_bytes(string):
"""Convert a string (bytes, str or unicode) to bytes."""
assert isinstance(string, basestring)
if sys.version_info[0] >= 3:
if isinstance(string, str):
return string.encode('utf-8')
else:
return string
else:
if isinstance(string, unic... |
Verify that base_url specifies a protocol and network location. | def validate_base_url(base_url):
"""Verify that base_url specifies a protocol and network location."""
parsed_url = urllib.parse.urlparse(base_url)
if parsed_url.scheme and parsed_url.netloc:
return parsed_url.geturl()
else:
error_message = "base_url must contain a valid scheme (protocol... |
Check to see if string is an validly - formatted web url. | def is_web_url(string):
"""Check to see if string is an validly-formatted web url."""
assert isinstance(string, basestring)
parsed_url = urllib.parse.urlparse(string)
return (
(
parsed_url.scheme.lower() == 'http'
or parsed_url.scheme.lower() == 'https'
)
... |
Open the file and return an EncodableFile tuple. | def open_local_file(file_path):
"""Open the file and return an EncodableFile tuple."""
assert isinstance(file_path, basestring)
assert is_local_file(file_path)
file_name = os.path.basename(file_path)
file_object = open(file_path, 'rb')
content_type = mimetypes.guess_type(file_name)[0] or 'text/p... |
Object is an instance of one of the acceptable types or None. | def check_type(o, acceptable_types, may_be_none=True):
"""Object is an instance of one of the acceptable types or None.
Args:
o: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
may_be_none(bool): Whether or not the object may be None.
Raises:
... |
Creates a dict with the inputted items ; pruning any that are None. | def dict_from_items_with_values(*dictionaries, **items):
"""Creates a dict with the inputted items; pruning any that are `None`.
Args:
*dictionaries(dict): Dictionaries of items to be pruned and included.
**items: Items to be pruned and included.
Returns:
dict: A dictionary contain... |
Check response code against the expected code ; raise ApiError. | def check_response_code(response, expected_response_code):
"""Check response code against the expected code; raise ApiError.
Checks the requests.response.status_code against the provided expected
response code (erc), and raises a ApiError if they do not match.
Args:
response(requests.response)... |
Given a dictionary or JSON string ; return a dictionary. | def json_dict(json_data):
"""Given a dictionary or JSON string; return a dictionary.
Args:
json_data(dict, str): Input JSON object.
Returns:
A Python dictionary with the contents of the JSON object.
Raises:
TypeError: If the input object is not a dictionary or string.
"""... |
strptime with the Webex Teams DateTime format as the default. | def strptime(cls, date_string, format=WEBEX_TEAMS_DATETIME_FORMAT):
"""strptime with the Webex Teams DateTime format as the default."""
return super(WebexTeamsDateTime, cls).strptime(
date_string, format
).replace(tzinfo=ZuluTimeZone()) |
List rooms. | def list(self, teamId=None, type=None, sortBy=None, max=None,
**request_parameters):
"""List rooms.
By default, lists rooms to which the authenticated user belongs.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It ... |
Create a room. | def create(self, title, teamId=None, **request_parameters):
"""Create a room.
The authenticated user is automatically added as a member of the room.
Args:
title(basestring): A user-friendly name for the room.
teamId(basestring): The team ID with which this room is
... |
Update details for a room by ID. | def update(self, roomId, title=None, **request_parameters):
"""Update details for a room, by ID.
Args:
roomId(basestring): The room ID.
title(basestring): A user-friendly name for the room.
**request_parameters: Additional request parameters (provides
... |
Delete a room. | def delete(self, roomId):
"""Delete a room.
Args:
roomId(basestring): The ID of the room to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(roomId, base... |
List all licenses for a given organization. | def list(self, orgId=None, **request_parameters):
"""List all licenses for a given organization.
If no orgId is specified, the default is the organization of the
authenticated user.
Args:
orgId(basestring): Specify the organization, by ID.
**request_parameters: ... |
Creation date and time in ISO8601 format. | def created(self):
"""Creation date and time in ISO8601 format."""
created = self._json_data.get('created')
if created:
return WebexTeamsDateTime.strptime(created)
else:
return None |
Function Decorator: Containerize calls to a generator function. | def generator_container(generator_function):
"""Function Decorator: Containerize calls to a generator function.
Args:
generator_function(func): The generator function being containerized.
Returns:
func: A wrapper function that containerizes the calls to the generator
function.
... |
Processes incoming requests to the/ events URI. | def webex_teams_webhook_events():
"""Processes incoming requests to the '/events' URI."""
if request.method == 'GET':
return ("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webex Tea... |
Attempt to get the access token from the environment. | def _get_access_token():
"""Attempt to get the access token from the environment.
Try using the current and legacy environment variables. If the access token
is found in a legacy environment variable, raise a deprecation warning.
Returns:
The access token found in the environment (str), or Non... |
Create a webhook. | def create(self, name, targetUrl, resource, event,
filter=None, secret=None, **request_parameters):
"""Create a webhook.
Args:
name(basestring): A user-friendly name for this webhook.
targetUrl(basestring): The URL that receives POST requests for
e... |
Update a webhook by ID. | def update(self, webhookId, name=None, targetUrl=None,
**request_parameters):
"""Update a webhook, by ID.
Args:
webhookId(basestring): The webhook ID.
name(basestring): A user-friendly name for this webhook.
targetUrl(basestring): The URL that receives... |
Delete a webhook by ID. | def delete(self, webhookId):
"""Delete a webhook, by ID.
Args:
webhookId(basestring): The ID of the webhook to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
chec... |
Remove max = null parameter from URL. | def _fix_next_url(next_url):
"""Remove max=null parameter from URL.
Patch for Webex Teams Defect: 'next' URL returned in the Link headers of
the responses contain an errant 'max=null' parameter, which causes the
next request (to this URL) to fail if the URL is requested as-is.
This patch parses t... |
The timeout ( seconds ) for a single HTTP REST API request. | def single_request_timeout(self, value):
"""The timeout (seconds) for a single HTTP REST API request."""
check_type(value, int)
assert value is None or value > 0
self._single_request_timeout = value |
Enable or disable automatic rate - limit handling. | def wait_on_rate_limit(self, value):
"""Enable or disable automatic rate-limit handling."""
check_type(value, bool, may_be_none=False)
self._wait_on_rate_limit = value |
Update the HTTP headers used for requests in this session. | def update_headers(self, headers):
"""Update the HTTP headers used for requests in this session.
Note: Updates provided by the dictionary passed as the `headers`
parameter to this method are merged into the session headers by adding
new key-value pairs and/or updating the values of exis... |
Given a relative or absolute URL ; return an absolute URL. | def abs_url(self, url):
"""Given a relative or absolute URL; return an absolute URL.
Args:
url(basestring): A relative or absolute URL.
Returns:
str: An absolute URL.
"""
parsed_url = urllib.parse.urlparse(url)
if not parsed_url.scheme and not p... |
Abstract base method for making requests to the Webex Teams APIs. | def request(self, method, url, erc, **kwargs):
"""Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support for Webex Te... |
Sends a GET request. | def get(self, url, params=None, **kwargs):
"""Sends a GET request.
Args:
url(basestring): The URL of the API endpoint.
params(dict): The parameters for the HTTP GET request.
**kwargs:
erc(int): The expected (success) response code for the request.
... |
Return a generator that GETs and yields pages of data. | def get_pages(self, url, params=None, **kwargs):
"""Return a generator that GETs and yields pages of data.
Provides native support for RFC5988 Web Linking.
Args:
url(basestring): The URL of the API endpoint.
params(dict): The parameters for the HTTP GET request.
... |
Return a generator that GETs and yields individual JSON items. | def get_items(self, url, params=None, **kwargs):
"""Return a generator that GETs and yields individual JSON `items`.
Yields individual `items` from Webex Teams's top-level {'items': [...]}
JSON objects. Provides native support for RFC5988 Web Linking. The
generator will request additio... |
Sends a PUT request. | def put(self, url, json=None, data=None, **kwargs):
"""Sends a PUT request.
Args:
url(basestring): The URL of the API endpoint.
json: Data to be sent in JSON format in tbe body of the request.
data: Data to be sent in the body of the request.
**kwargs:
... |
Sends a DELETE request. | def delete(self, url, **kwargs):
"""Sends a DELETE request.
Args:
url(basestring): The URL of the API endpoint.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
... |
Create a new guest issuer using the provided issuer token. | def create(self, subject, displayName, issuerToken, expiration, secret):
"""Create a new guest issuer using the provided issuer token.
This function returns a guest issuer with an api access token.
Args:
subject(basestring): Unique and public identifier
displayName(base... |
Lists messages in a room. | def list(self, roomId, mentionedPeople=None, before=None,
beforeMessage=None, max=None, **request_parameters):
"""Lists messages in a room.
Each message will include content attachments if present.
The list API sorts the messages in descending order by creation date.
This... |
Post a message and optionally a attachment to a room. | def create(self, roomId=None, toPersonId=None, toPersonEmail=None,
text=None, markdown=None, files=None, **request_parameters):
"""Post a message, and optionally a attachment, to a room.
The files parameter is a list, which accepts multiple values to allow
for future expansion, b... |
Delete a message. | def delete(self, messageId):
"""Delete a message.
Args:
messageId(basestring): The ID of the message to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(... |
List people | def list(self, email=None, displayName=None, id=None, orgId=None, max=None,
**request_parameters):
"""List people
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yie... |
Create a new user account for a given organization | def create(self, emails, displayName=None, firstName=None, lastName=None,
avatar=None, orgId=None, roles=None, licenses=None,
**request_parameters):
"""Create a new user account for a given organization
Only an admin can create a new user account.
Args:
... |
Get a person s details by ID. | def get(self, personId):
"""Get a person's details, by ID.
Args:
personId(basestring): The ID of the person to be retrieved.
Returns:
Person: A Person object with the details of the requested person.
Raises:
TypeError: If the parameter types are inc... |
Update details for a person by ID. | def update(self, personId, emails=None, displayName=None, firstName=None,
lastName=None, avatar=None, orgId=None, roles=None,
licenses=None, **request_parameters):
"""Update details for a person, by ID.
Only an admin can update a person's details.
Email addresses ... |
Remove a person from the system. | def delete(self, personId):
"""Remove a person from the system.
Only an admin can remove a person.
Args:
personId(basestring): The ID of the person to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams ... |
Get the details of the person accessing the API. | def me(self):
"""Get the details of the person accessing the API.
Raises:
ApiError: If the Webex Teams cloud returns an error.
"""
# API request
json_data = self._session.get(API_ENDPOINT + '/me')
# Return a person object created from the response JSON data... |
List all roles. | def list(self, **request_parameters):
"""List all roles.
Args:
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
... |
List teams to which the authenticated user belongs. | def list(self, max=None, **request_parameters):
"""List teams to which the authenticated user belongs.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all teams returned b... |
Create a team. | def create(self, name, **request_parameters):
"""Create a team.
The authenticated user is automatically added as a member of the team.
Args:
name(basestring): A user-friendly name for the team.
**request_parameters: Additional request parameters (provides
... |
Update details for a team by ID. | def update(self, teamId, name=None, **request_parameters):
"""Update details for a team, by ID.
Args:
teamId(basestring): The team ID.
name(basestring): A user-friendly name for the team.
**request_parameters: Additional request parameters (provides
s... |
Delete a team. | def delete(self, teamId):
"""Delete a team.
Args:
teamId(basestring): The ID of the team to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(teamId, base... |
List events. | def list(self, resource=None, type=None, actorId=None, _from=None, to=None,
max=None, **request_parameters):
"""List events.
List events in your organization. Several query parameters are
available to filter the response.
Note: `from` is a keyword in Python and may not be ... |
Serialize data to an frozen tuple. | def _serialize(cls, data):
"""Serialize data to an frozen tuple."""
if hasattr(data, "__hash__") and callable(data.__hash__):
# If the data is already hashable (should be immutable) return it
return data
elif isinstance(data, list):
# Freeze the elements of th... |
Exchange an Authorization Code for an Access Token. | def get(self, client_id, client_secret, code, redirect_uri):
"""Exchange an Authorization Code for an Access Token.
Exchange an Authorization Code for an Access Token that can be used to
invoke the APIs.
Args:
client_id(basestring): Provided when you created your integratio... |
The date and time of the person s last activity. | def lastActivity(self):
"""The date and time of the person's last activity."""
last_activity = self._json_data.get('lastActivity')
if last_activity:
return WebexTeamsDateTime.strptime(last_activity)
else:
return None |
Respond to inbound webhook JSON HTTP POST from Webex Teams. | def post_events_service(request):
"""Respond to inbound webhook JSON HTTP POST from Webex Teams."""
# Get the POST data sent from Webex Teams
json_data = request.json
log.info("\n")
log.info("WEBHOOK POST RECEIVED:")
log.info(json_data)
log.info("\n")
# Create a Webhook object from the... |
Get the ngrok public HTTP URL from the local client API. | def get_ngrok_public_url():
"""Get the ngrok public HTTP URL from the local client API."""
try:
response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels",
headers={'content-type': 'application/json'})
response.raise_for_status()
except request... |
Find a webhook by name. | def delete_webhooks_with_name(api, name):
"""Find a webhook by name."""
for webhook in api.webhooks.list():
if webhook.name == name:
print("Deleting Webhook:", webhook.name, webhook.targetUrl)
api.webhooks.delete(webhook.id) |
Create a Webex Teams webhook pointing to the public ngrok URL. | def create_ngrok_webhook(api, ngrok_public_url):
"""Create a Webex Teams webhook pointing to the public ngrok URL."""
print("Creating Webhook...")
webhook = api.webhooks.create(
name=WEBHOOK_NAME,
targetUrl=urljoin(ngrok_public_url, WEBHOOK_URL_SUFFIX),
resource=WEBHOOK_RESOURC... |
Delete previous webhooks. If local ngrok tunnel create a webhook. | def main():
"""Delete previous webhooks. If local ngrok tunnel, create a webhook."""
api = WebexTeamsAPI()
delete_webhooks_with_name(api, name=WEBHOOK_NAME)
public_url = get_ngrok_public_url()
if public_url is not None:
create_ngrok_webhook(api, public_url) |
Since there isn t a real sensor connected read () creates random data. | def read(self):
"""
Since there isn't a real sensor connected, read() creates random
data.
"""
data = [0]*6
for i in range(6):
data[i] = random.uniform(-2048, 2048)
accel = data[:3]
mag = data[3:]
return (accel, mag) |
Output DSMR data to console. | def console():
"""Output DSMR data to console."""
parser = argparse.ArgumentParser(description=console.__doc__)
parser.add_argument('--device', default='/dev/ttyUSB0',
help='port to read DSMR data from')
parser.add_argument('--host', default=None,
help='a... |
Read complete DSMR telegram s from the serial interface and parse it into CosemObject s and MbusObject s | def read(self):
"""
Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's
:rtype: generator
"""
with serial.Serial(**self.serial_settings) as serial_handle:
while True:
data = serial_handle.re... |
Read complete DSMR telegram s from the serial interface and parse it into CosemObject s and MbusObject s. | def read(self, queue):
"""
Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's.
Instead of being a generator, values are pushed to provided queue for
asynchronous processing.
:rtype: None
"""
# create ... |
Creates a DSMR asyncio protocol. | def create_dsmr_protocol(dsmr_version, telegram_callback, loop=None):
"""Creates a DSMR asyncio protocol."""
if dsmr_version == '2.2':
specification = telegram_specifications.V2_2
serial_settings = SERIAL_SETTINGS_V2_2
elif dsmr_version == '4':
specification = telegram_specification... |
Creates a DSMR asyncio protocol coroutine using serial port. | def create_dsmr_reader(port, dsmr_version, telegram_callback, loop=None):
"""Creates a DSMR asyncio protocol coroutine using serial port."""
protocol, serial_settings = create_dsmr_protocol(
dsmr_version, telegram_callback, loop=None)
serial_settings['url'] = port
conn = create_serial_connectio... |
Creates a DSMR asyncio protocol coroutine using TCP connection. | def create_tcp_dsmr_reader(host, port, dsmr_version,
telegram_callback, loop=None):
"""Creates a DSMR asyncio protocol coroutine using TCP connection."""
protocol, _ = create_dsmr_protocol(
dsmr_version, telegram_callback, loop=None)
conn = loop.create_connection(protocol,... |
Add incoming data to buffer. | def data_received(self, data):
"""Add incoming data to buffer."""
data = data.decode('ascii')
self.log.debug('received data: %s', data)
self.telegram_buffer.append(data)
for telegram in self.telegram_buffer.get_all():
self.handle_telegram(telegram) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.