partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
bdist_wheel.add_requirements
Add additional requirements from setup.cfg to file metadata_path
libraries/botframework-connector/azure_bdist_wheel.py
def add_requirements(self, metadata_path): """Add additional requirements from setup.cfg to file metadata_path""" additional = list(self.setupcfg_requirements()) if not additional: return pkg_info = read_pkg_info(metadata_path) if 'Provides-Extra' in pkg_info or 'Requires-Dist' in pkg_info: warnings.warn('setup.cfg requirements overwrite values from setup.py') del pkg_info['Provides-Extra'] del pkg_info['Requires-Dist'] for k, v in additional: pkg_info[k] = v write_pkg_info(metadata_path, pkg_info)
def add_requirements(self, metadata_path): """Add additional requirements from setup.cfg to file metadata_path""" additional = list(self.setupcfg_requirements()) if not additional: return pkg_info = read_pkg_info(metadata_path) if 'Provides-Extra' in pkg_info or 'Requires-Dist' in pkg_info: warnings.warn('setup.cfg requirements overwrite values from setup.py') del pkg_info['Provides-Extra'] del pkg_info['Requires-Dist'] for k, v in additional: pkg_info[k] = v write_pkg_info(metadata_path, pkg_info)
[ "Add", "additional", "requirements", "from", "setup", ".", "cfg", "to", "file", "metadata_path" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/azure_bdist_wheel.py#L355-L366
[ "def", "add_requirements", "(", "self", ",", "metadata_path", ")", ":", "additional", "=", "list", "(", "self", ".", "setupcfg_requirements", "(", ")", ")", "if", "not", "additional", ":", "return", "pkg_info", "=", "read_pkg_info", "(", "metadata_path", ")", "if", "'Provides-Extra'", "in", "pkg_info", "or", "'Requires-Dist'", "in", "pkg_info", ":", "warnings", ".", "warn", "(", "'setup.cfg requirements overwrite values from setup.py'", ")", "del", "pkg_info", "[", "'Provides-Extra'", "]", "del", "pkg_info", "[", "'Requires-Dist'", "]", "for", "k", ",", "v", "in", "additional", ":", "pkg_info", "[", "k", "]", "=", "v", "write_pkg_info", "(", "metadata_path", ",", "pkg_info", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
bdist_wheel.egg2dist
Convert an .egg-info directory into a .dist-info directory
libraries/botframework-connector/azure_bdist_wheel.py
def egg2dist(self, egginfo_path, distinfo_path): """Convert an .egg-info directory into a .dist-info directory""" def adios(p): """Appropriately delete directory, file or link.""" if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p): shutil.rmtree(p) elif os.path.exists(p): os.unlink(p) adios(distinfo_path) if not os.path.exists(egginfo_path): # There is no egg-info. This is probably because the egg-info # file/directory is not named matching the distribution name used # to name the archive file. Check for this case and report # accordingly. import glob pat = os.path.join(os.path.dirname(egginfo_path), '*.egg-info') possible = glob.glob(pat) err = "Egg metadata expected at %s but not found" % (egginfo_path,) if possible: alt = os.path.basename(possible[0]) err += " (%s found - possible misnamed archive file?)" % (alt,) raise ValueError(err) if os.path.isfile(egginfo_path): # .egg-info is a single file pkginfo_path = egginfo_path pkg_info = self._pkginfo_to_metadata(egginfo_path, egginfo_path) os.mkdir(distinfo_path) else: # .egg-info is a directory pkginfo_path = os.path.join(egginfo_path, 'PKG-INFO') pkg_info = self._pkginfo_to_metadata(egginfo_path, pkginfo_path) # ignore common egg metadata that is useless to wheel shutil.copytree(egginfo_path, distinfo_path, ignore=lambda x, y: set(('PKG-INFO', 'requires.txt', 'SOURCES.txt', 'not-zip-safe',))) # delete dependency_links if it is only whitespace dependency_links_path = os.path.join(distinfo_path, 'dependency_links.txt') with open(dependency_links_path, 'r') as dependency_links_file: dependency_links = dependency_links_file.read().strip() if not dependency_links: adios(dependency_links_path) write_pkg_info(os.path.join(distinfo_path, 'METADATA'), pkg_info) # XXX deprecated. Still useful for current distribute/setuptools. metadata_path = os.path.join(distinfo_path, 'METADATA') self.add_requirements(metadata_path) # XXX intentionally a different path than the PEP. metadata_json_path = os.path.join(distinfo_path, 'metadata.json') pymeta = pkginfo_to_dict(metadata_path, distribution=self.distribution) if 'description' in pymeta: description_filename = 'DESCRIPTION.rst' description_text = pymeta.pop('description') description_path = os.path.join(distinfo_path, description_filename) with open(description_path, "wb") as description_file: description_file.write(description_text.encode('utf-8')) pymeta['extensions']['python.details']['document_names']['description'] = description_filename # XXX heuristically copy any LICENSE/LICENSE.txt? license = self.license_file() if license: license_filename = 'LICENSE.txt' shutil.copy(license, os.path.join(self.distinfo_dir, license_filename)) pymeta['extensions']['python.details']['document_names']['license'] = license_filename with open(metadata_json_path, "w") as metadata_json: json.dump(pymeta, metadata_json, sort_keys=True) adios(egginfo_path)
def egg2dist(self, egginfo_path, distinfo_path): """Convert an .egg-info directory into a .dist-info directory""" def adios(p): """Appropriately delete directory, file or link.""" if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p): shutil.rmtree(p) elif os.path.exists(p): os.unlink(p) adios(distinfo_path) if not os.path.exists(egginfo_path): # There is no egg-info. This is probably because the egg-info # file/directory is not named matching the distribution name used # to name the archive file. Check for this case and report # accordingly. import glob pat = os.path.join(os.path.dirname(egginfo_path), '*.egg-info') possible = glob.glob(pat) err = "Egg metadata expected at %s but not found" % (egginfo_path,) if possible: alt = os.path.basename(possible[0]) err += " (%s found - possible misnamed archive file?)" % (alt,) raise ValueError(err) if os.path.isfile(egginfo_path): # .egg-info is a single file pkginfo_path = egginfo_path pkg_info = self._pkginfo_to_metadata(egginfo_path, egginfo_path) os.mkdir(distinfo_path) else: # .egg-info is a directory pkginfo_path = os.path.join(egginfo_path, 'PKG-INFO') pkg_info = self._pkginfo_to_metadata(egginfo_path, pkginfo_path) # ignore common egg metadata that is useless to wheel shutil.copytree(egginfo_path, distinfo_path, ignore=lambda x, y: set(('PKG-INFO', 'requires.txt', 'SOURCES.txt', 'not-zip-safe',))) # delete dependency_links if it is only whitespace dependency_links_path = os.path.join(distinfo_path, 'dependency_links.txt') with open(dependency_links_path, 'r') as dependency_links_file: dependency_links = dependency_links_file.read().strip() if not dependency_links: adios(dependency_links_path) write_pkg_info(os.path.join(distinfo_path, 'METADATA'), pkg_info) # XXX deprecated. Still useful for current distribute/setuptools. metadata_path = os.path.join(distinfo_path, 'METADATA') self.add_requirements(metadata_path) # XXX intentionally a different path than the PEP. metadata_json_path = os.path.join(distinfo_path, 'metadata.json') pymeta = pkginfo_to_dict(metadata_path, distribution=self.distribution) if 'description' in pymeta: description_filename = 'DESCRIPTION.rst' description_text = pymeta.pop('description') description_path = os.path.join(distinfo_path, description_filename) with open(description_path, "wb") as description_file: description_file.write(description_text.encode('utf-8')) pymeta['extensions']['python.details']['document_names']['description'] = description_filename # XXX heuristically copy any LICENSE/LICENSE.txt? license = self.license_file() if license: license_filename = 'LICENSE.txt' shutil.copy(license, os.path.join(self.distinfo_dir, license_filename)) pymeta['extensions']['python.details']['document_names']['license'] = license_filename with open(metadata_json_path, "w") as metadata_json: json.dump(pymeta, metadata_json, sort_keys=True) adios(egginfo_path)
[ "Convert", "an", ".", "egg", "-", "info", "directory", "into", "a", ".", "dist", "-", "info", "directory" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/azure_bdist_wheel.py#L368-L448
[ "def", "egg2dist", "(", "self", ",", "egginfo_path", ",", "distinfo_path", ")", ":", "def", "adios", "(", "p", ")", ":", "\"\"\"Appropriately delete directory, file or link.\"\"\"", "if", "os", ".", "path", ".", "exists", "(", "p", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "p", ")", "and", "os", ".", "path", ".", "isdir", "(", "p", ")", ":", "shutil", ".", "rmtree", "(", "p", ")", "elif", "os", ".", "path", ".", "exists", "(", "p", ")", ":", "os", ".", "unlink", "(", "p", ")", "adios", "(", "distinfo_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "egginfo_path", ")", ":", "# There is no egg-info. This is probably because the egg-info", "# file/directory is not named matching the distribution name used", "# to name the archive file. Check for this case and report", "# accordingly.", "import", "glob", "pat", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "egginfo_path", ")", ",", "'*.egg-info'", ")", "possible", "=", "glob", ".", "glob", "(", "pat", ")", "err", "=", "\"Egg metadata expected at %s but not found\"", "%", "(", "egginfo_path", ",", ")", "if", "possible", ":", "alt", "=", "os", ".", "path", ".", "basename", "(", "possible", "[", "0", "]", ")", "err", "+=", "\" (%s found - possible misnamed archive file?)\"", "%", "(", "alt", ",", ")", "raise", "ValueError", "(", "err", ")", "if", "os", ".", "path", ".", "isfile", "(", "egginfo_path", ")", ":", "# .egg-info is a single file", "pkginfo_path", "=", "egginfo_path", "pkg_info", "=", "self", ".", "_pkginfo_to_metadata", "(", "egginfo_path", ",", "egginfo_path", ")", "os", ".", "mkdir", "(", "distinfo_path", ")", "else", ":", "# .egg-info is a directory", "pkginfo_path", "=", "os", ".", "path", ".", "join", "(", "egginfo_path", ",", "'PKG-INFO'", ")", "pkg_info", "=", "self", ".", "_pkginfo_to_metadata", "(", "egginfo_path", ",", "pkginfo_path", ")", "# ignore common egg metadata that is useless to wheel", "shutil", ".", "copytree", "(", "egginfo_path", ",", "distinfo_path", ",", "ignore", "=", "lambda", "x", ",", "y", ":", "set", "(", "(", "'PKG-INFO'", ",", "'requires.txt'", ",", "'SOURCES.txt'", ",", "'not-zip-safe'", ",", ")", ")", ")", "# delete dependency_links if it is only whitespace", "dependency_links_path", "=", "os", ".", "path", ".", "join", "(", "distinfo_path", ",", "'dependency_links.txt'", ")", "with", "open", "(", "dependency_links_path", ",", "'r'", ")", "as", "dependency_links_file", ":", "dependency_links", "=", "dependency_links_file", ".", "read", "(", ")", ".", "strip", "(", ")", "if", "not", "dependency_links", ":", "adios", "(", "dependency_links_path", ")", "write_pkg_info", "(", "os", ".", "path", ".", "join", "(", "distinfo_path", ",", "'METADATA'", ")", ",", "pkg_info", ")", "# XXX deprecated. Still useful for current distribute/setuptools.", "metadata_path", "=", "os", ".", "path", ".", "join", "(", "distinfo_path", ",", "'METADATA'", ")", "self", ".", "add_requirements", "(", "metadata_path", ")", "# XXX intentionally a different path than the PEP.", "metadata_json_path", "=", "os", ".", "path", ".", "join", "(", "distinfo_path", ",", "'metadata.json'", ")", "pymeta", "=", "pkginfo_to_dict", "(", "metadata_path", ",", "distribution", "=", "self", ".", "distribution", ")", "if", "'description'", "in", "pymeta", ":", "description_filename", "=", "'DESCRIPTION.rst'", "description_text", "=", "pymeta", ".", "pop", "(", "'description'", ")", "description_path", "=", "os", ".", "path", ".", "join", "(", "distinfo_path", ",", "description_filename", ")", "with", "open", "(", "description_path", ",", "\"wb\"", ")", "as", "description_file", ":", "description_file", ".", "write", "(", "description_text", ".", "encode", "(", "'utf-8'", ")", ")", "pymeta", "[", "'extensions'", "]", "[", "'python.details'", "]", "[", "'document_names'", "]", "[", "'description'", "]", "=", "description_filename", "# XXX heuristically copy any LICENSE/LICENSE.txt?", "license", "=", "self", ".", "license_file", "(", ")", "if", "license", ":", "license_filename", "=", "'LICENSE.txt'", "shutil", ".", "copy", "(", "license", ",", "os", ".", "path", ".", "join", "(", "self", ".", "distinfo_dir", ",", "license_filename", ")", ")", "pymeta", "[", "'extensions'", "]", "[", "'python.details'", "]", "[", "'document_names'", "]", "[", "'license'", "]", "=", "license_filename", "with", "open", "(", "metadata_json_path", ",", "\"w\"", ")", "as", "metadata_json", ":", "json", ".", "dump", "(", "pymeta", ",", "metadata_json", ",", "sort_keys", "=", "True", ")", "adios", "(", "egginfo_path", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ConversationsOperations.get_conversations
GetConversations. List the Conversations in which this bot has participated. GET from this method with a skip token The return value is a ConversationsResult, which contains an array of ConversationMembers and a skip token. If the skip token is not empty, then there are further values to be returned. Call this method again with the returned token to get more values. Each ConversationMembers object contains the ID of the conversation and an array of ChannelAccounts that describe the members of the conversation. :param continuation_token: skip or continuation token :type continuation_token: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ConversationsResult or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.ConversationsResult or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
libraries/botframework-connector/botframework/connector/operations/_conversations_operations.py
def get_conversations( self, continuation_token=None, custom_headers=None, raw=False, **operation_config): """GetConversations. List the Conversations in which this bot has participated. GET from this method with a skip token The return value is a ConversationsResult, which contains an array of ConversationMembers and a skip token. If the skip token is not empty, then there are further values to be returned. Call this method again with the returned token to get more values. Each ConversationMembers object contains the ID of the conversation and an array of ChannelAccounts that describe the members of the conversation. :param continuation_token: skip or continuation token :type continuation_token: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ConversationsResult or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.ConversationsResult or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>` """ # Construct URL url = self.get_conversations.metadata['url'] # Construct parameters query_parameters = {} if continuation_token is not None: query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if custom_headers: header_parameters.update(custom_headers) # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.ErrorResponseException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ConversationsResult', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
def get_conversations( self, continuation_token=None, custom_headers=None, raw=False, **operation_config): """GetConversations. List the Conversations in which this bot has participated. GET from this method with a skip token The return value is a ConversationsResult, which contains an array of ConversationMembers and a skip token. If the skip token is not empty, then there are further values to be returned. Call this method again with the returned token to get more values. Each ConversationMembers object contains the ID of the conversation and an array of ChannelAccounts that describe the members of the conversation. :param continuation_token: skip or continuation token :type continuation_token: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ConversationsResult or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.ConversationsResult or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>` """ # Construct URL url = self.get_conversations.metadata['url'] # Construct parameters query_parameters = {} if continuation_token is not None: query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if custom_headers: header_parameters.update(custom_headers) # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.ErrorResponseException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ConversationsResult', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
[ "GetConversations", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/operations/_conversations_operations.py#L41-L98
[ "def", "get_conversations", "(", "self", ",", "continuation_token", "=", "None", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "operation_config", ")", ":", "# Construct URL", "url", "=", "self", ".", "get_conversations", ".", "metadata", "[", "'url'", "]", "# Construct parameters", "query_parameters", "=", "{", "}", "if", "continuation_token", "is", "not", "None", ":", "query_parameters", "[", "'continuationToken'", "]", "=", "self", ".", "_serialize", ".", "query", "(", "\"continuation_token\"", ",", "continuation_token", ",", "'str'", ")", "# Construct headers", "header_parameters", "=", "{", "}", "header_parameters", "[", "'Accept'", "]", "=", "'application/json'", "if", "custom_headers", ":", "header_parameters", ".", "update", "(", "custom_headers", ")", "# Construct and send request", "request", "=", "self", ".", "_client", ".", "get", "(", "url", ",", "query_parameters", ",", "header_parameters", ")", "response", "=", "self", ".", "_client", ".", "send", "(", "request", ",", "stream", "=", "False", ",", "*", "*", "operation_config", ")", "if", "response", ".", "status_code", "not", "in", "[", "200", "]", ":", "raise", "models", ".", "ErrorResponseException", "(", "self", ".", "_deserialize", ",", "response", ")", "deserialized", "=", "None", "if", "response", ".", "status_code", "==", "200", ":", "deserialized", "=", "self", ".", "_deserialize", "(", "'ConversationsResult'", ",", "response", ")", "if", "raw", ":", "client_raw_response", "=", "ClientRawResponse", "(", "deserialized", ",", "response", ")", "return", "client_raw_response", "return", "deserialized" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ConversationsOperations.create_conversation
CreateConversation. Create a new Conversation. POST to this method with a * Bot being the bot creating the conversation * IsGroup set to true if this is not a direct message (default is false) * Array containing the members to include in the conversation The return value is a ResourceResponse which contains a conversation id which is suitable for use in the message payload and REST API uris. Most channels only support the semantics of bots initiating a direct message conversation. An example of how to do that would be: ``` var resource = await connector.conversations.CreateConversation(new ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new ChannelAccount("user1") } ); await connect.Conversations.SendToConversationAsync(resource.Id, new Activity() ... ) ; ```. :param parameters: Parameters to create the conversation from :type parameters: ~botframework.connector.models.ConversationParameters :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ConversationResourceResponse or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.ConversationResourceResponse or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
libraries/botframework-connector/botframework/connector/operations/_conversations_operations.py
def create_conversation( self, parameters, custom_headers=None, raw=False, **operation_config): """CreateConversation. Create a new Conversation. POST to this method with a * Bot being the bot creating the conversation * IsGroup set to true if this is not a direct message (default is false) * Array containing the members to include in the conversation The return value is a ResourceResponse which contains a conversation id which is suitable for use in the message payload and REST API uris. Most channels only support the semantics of bots initiating a direct message conversation. An example of how to do that would be: ``` var resource = await connector.conversations.CreateConversation(new ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new ChannelAccount("user1") } ); await connect.Conversations.SendToConversationAsync(resource.Id, new Activity() ... ) ; ```. :param parameters: Parameters to create the conversation from :type parameters: ~botframework.connector.models.ConversationParameters :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ConversationResourceResponse or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.ConversationResourceResponse or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>` """ # Construct URL url = self.create_conversation.metadata['url'] # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if custom_headers: header_parameters.update(custom_headers) # Construct body body_content = self._serialize.body(parameters, 'ConversationParameters') # Construct and send request request = self._client.post(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200, 201, 202]: raise models.ErrorResponseException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ConversationResourceResponse', response) if response.status_code == 201: deserialized = self._deserialize('ConversationResourceResponse', response) if response.status_code == 202: deserialized = self._deserialize('ConversationResourceResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
def create_conversation( self, parameters, custom_headers=None, raw=False, **operation_config): """CreateConversation. Create a new Conversation. POST to this method with a * Bot being the bot creating the conversation * IsGroup set to true if this is not a direct message (default is false) * Array containing the members to include in the conversation The return value is a ResourceResponse which contains a conversation id which is suitable for use in the message payload and REST API uris. Most channels only support the semantics of bots initiating a direct message conversation. An example of how to do that would be: ``` var resource = await connector.conversations.CreateConversation(new ConversationParameters(){ Bot = bot, members = new ChannelAccount[] { new ChannelAccount("user1") } ); await connect.Conversations.SendToConversationAsync(resource.Id, new Activity() ... ) ; ```. :param parameters: Parameters to create the conversation from :type parameters: ~botframework.connector.models.ConversationParameters :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ConversationResourceResponse or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.ConversationResourceResponse or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>` """ # Construct URL url = self.create_conversation.metadata['url'] # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if custom_headers: header_parameters.update(custom_headers) # Construct body body_content = self._serialize.body(parameters, 'ConversationParameters') # Construct and send request request = self._client.post(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200, 201, 202]: raise models.ErrorResponseException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ConversationResourceResponse', response) if response.status_code == 201: deserialized = self._deserialize('ConversationResourceResponse', response) if response.status_code == 202: deserialized = self._deserialize('ConversationResourceResponse', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
[ "CreateConversation", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/operations/_conversations_operations.py#L101-L173
[ "def", "create_conversation", "(", "self", ",", "parameters", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "operation_config", ")", ":", "# Construct URL", "url", "=", "self", ".", "create_conversation", ".", "metadata", "[", "'url'", "]", "# Construct parameters", "query_parameters", "=", "{", "}", "# Construct headers", "header_parameters", "=", "{", "}", "header_parameters", "[", "'Accept'", "]", "=", "'application/json'", "header_parameters", "[", "'Content-Type'", "]", "=", "'application/json; charset=utf-8'", "if", "custom_headers", ":", "header_parameters", ".", "update", "(", "custom_headers", ")", "# Construct body", "body_content", "=", "self", ".", "_serialize", ".", "body", "(", "parameters", ",", "'ConversationParameters'", ")", "# Construct and send request", "request", "=", "self", ".", "_client", ".", "post", "(", "url", ",", "query_parameters", ",", "header_parameters", ",", "body_content", ")", "response", "=", "self", ".", "_client", ".", "send", "(", "request", ",", "stream", "=", "False", ",", "*", "*", "operation_config", ")", "if", "response", ".", "status_code", "not", "in", "[", "200", ",", "201", ",", "202", "]", ":", "raise", "models", ".", "ErrorResponseException", "(", "self", ".", "_deserialize", ",", "response", ")", "deserialized", "=", "None", "if", "response", ".", "status_code", "==", "200", ":", "deserialized", "=", "self", ".", "_deserialize", "(", "'ConversationResourceResponse'", ",", "response", ")", "if", "response", ".", "status_code", "==", "201", ":", "deserialized", "=", "self", ".", "_deserialize", "(", "'ConversationResourceResponse'", ",", "response", ")", "if", "response", ".", "status_code", "==", "202", ":", "deserialized", "=", "self", ".", "_deserialize", "(", "'ConversationResourceResponse'", ",", "response", ")", "if", "raw", ":", "client_raw_response", "=", "ClientRawResponse", "(", "deserialized", ",", "response", ")", "return", "client_raw_response", "return", "deserialized" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ConversationsOperations.get_conversation_paged_members
GetConversationPagedMembers. Enumerate the members of a conversation one page at a time. This REST API takes a ConversationId. Optionally a pageSize and/or continuationToken can be provided. It returns a PagedMembersResult, which contains an array of ChannelAccounts representing the members of the conversation and a continuation token that can be used to get more values. One page of ChannelAccounts records are returned with each call. The number of records in a page may vary between channels and calls. The pageSize parameter can be used as a suggestion. If there are no additional results the response will not contain a continuation token. If there are no members in the conversation the Members will be empty or not present in the response. A response to a request that has a continuation token from a prior request may rarely return members from a previous request. :param conversation_id: Conversation ID :type conversation_id: str :param page_size: Suggested page size :type page_size: int :param continuation_token: Continuation Token :type continuation_token: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: PagedMembersResult or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.PagedMembersResult or ~msrest.pipeline.ClientRawResponse :raises: :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
libraries/botframework-connector/botframework/connector/operations/_conversations_operations.py
def get_conversation_paged_members( self, conversation_id, page_size=None, continuation_token=None, custom_headers=None, raw=False, **operation_config): """GetConversationPagedMembers. Enumerate the members of a conversation one page at a time. This REST API takes a ConversationId. Optionally a pageSize and/or continuationToken can be provided. It returns a PagedMembersResult, which contains an array of ChannelAccounts representing the members of the conversation and a continuation token that can be used to get more values. One page of ChannelAccounts records are returned with each call. The number of records in a page may vary between channels and calls. The pageSize parameter can be used as a suggestion. If there are no additional results the response will not contain a continuation token. If there are no members in the conversation the Members will be empty or not present in the response. A response to a request that has a continuation token from a prior request may rarely return members from a previous request. :param conversation_id: Conversation ID :type conversation_id: str :param page_size: Suggested page size :type page_size: int :param continuation_token: Continuation Token :type continuation_token: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: PagedMembersResult or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.PagedMembersResult or ~msrest.pipeline.ClientRawResponse :raises: :class:`HttpOperationError<msrest.exceptions.HttpOperationError>` """ # Construct URL url = self.get_conversation_paged_members.metadata['url'] path_format_arguments = { 'conversationId': self._serialize.url("conversation_id", conversation_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if page_size is not None: query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int') if continuation_token is not None: query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if custom_headers: header_parameters.update(custom_headers) # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise HttpOperationError(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('PagedMembersResult', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
def get_conversation_paged_members( self, conversation_id, page_size=None, continuation_token=None, custom_headers=None, raw=False, **operation_config): """GetConversationPagedMembers. Enumerate the members of a conversation one page at a time. This REST API takes a ConversationId. Optionally a pageSize and/or continuationToken can be provided. It returns a PagedMembersResult, which contains an array of ChannelAccounts representing the members of the conversation and a continuation token that can be used to get more values. One page of ChannelAccounts records are returned with each call. The number of records in a page may vary between channels and calls. The pageSize parameter can be used as a suggestion. If there are no additional results the response will not contain a continuation token. If there are no members in the conversation the Members will be empty or not present in the response. A response to a request that has a continuation token from a prior request may rarely return members from a previous request. :param conversation_id: Conversation ID :type conversation_id: str :param page_size: Suggested page size :type page_size: int :param continuation_token: Continuation Token :type continuation_token: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: PagedMembersResult or ClientRawResponse if raw=true :rtype: ~botframework.connector.models.PagedMembersResult or ~msrest.pipeline.ClientRawResponse :raises: :class:`HttpOperationError<msrest.exceptions.HttpOperationError>` """ # Construct URL url = self.get_conversation_paged_members.metadata['url'] path_format_arguments = { 'conversationId': self._serialize.url("conversation_id", conversation_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if page_size is not None: query_parameters['pageSize'] = self._serialize.query("page_size", page_size, 'int') if continuation_token is not None: query_parameters['continuationToken'] = self._serialize.query("continuation_token", continuation_token, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if custom_headers: header_parameters.update(custom_headers) # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise HttpOperationError(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('PagedMembersResult', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
[ "GetConversationPagedMembers", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/operations/_conversations_operations.py#L574-L645
[ "def", "get_conversation_paged_members", "(", "self", ",", "conversation_id", ",", "page_size", "=", "None", ",", "continuation_token", "=", "None", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "operation_config", ")", ":", "# Construct URL", "url", "=", "self", ".", "get_conversation_paged_members", ".", "metadata", "[", "'url'", "]", "path_format_arguments", "=", "{", "'conversationId'", ":", "self", ".", "_serialize", ".", "url", "(", "\"conversation_id\"", ",", "conversation_id", ",", "'str'", ")", "}", "url", "=", "self", ".", "_client", ".", "format_url", "(", "url", ",", "*", "*", "path_format_arguments", ")", "# Construct parameters", "query_parameters", "=", "{", "}", "if", "page_size", "is", "not", "None", ":", "query_parameters", "[", "'pageSize'", "]", "=", "self", ".", "_serialize", ".", "query", "(", "\"page_size\"", ",", "page_size", ",", "'int'", ")", "if", "continuation_token", "is", "not", "None", ":", "query_parameters", "[", "'continuationToken'", "]", "=", "self", ".", "_serialize", ".", "query", "(", "\"continuation_token\"", ",", "continuation_token", ",", "'str'", ")", "# Construct headers", "header_parameters", "=", "{", "}", "header_parameters", "[", "'Accept'", "]", "=", "'application/json'", "if", "custom_headers", ":", "header_parameters", ".", "update", "(", "custom_headers", ")", "# Construct and send request", "request", "=", "self", ".", "_client", ".", "get", "(", "url", ",", "query_parameters", ",", "header_parameters", ")", "response", "=", "self", ".", "_client", ".", "send", "(", "request", ",", "stream", "=", "False", ",", "*", "*", "operation_config", ")", "if", "response", ".", "status_code", "not", "in", "[", "200", "]", ":", "raise", "HttpOperationError", "(", "self", ".", "_deserialize", ",", "response", ")", "deserialized", "=", "None", "if", "response", ".", "status_code", "==", "200", ":", "deserialized", "=", "self", ".", "_deserialize", "(", "'PagedMembersResult'", ",", "response", ")", "if", "raw", ":", "client_raw_response", "=", "ClientRawResponse", "(", "deserialized", ",", "response", ")", "return", "client_raw_response", "return", "deserialized" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
BotTelemetryClient.track_pageview
Send information about the page viewed in the application (a web page for instance). :param name: the name of the page that was viewed. :param url: the URL of the page that was viewed. :param duration: the duration of the page view in milliseconds. (defaults to: 0) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py
def track_pageview(self, name: str, url, duration: int = 0, properties : Dict[str, object]=None, measurements: Dict[str, object]=None) -> None: """ Send information about the page viewed in the application (a web page for instance). :param name: the name of the page that was viewed. :param url: the URL of the page that was viewed. :param duration: the duration of the page view in milliseconds. (defaults to: 0) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
def track_pageview(self, name: str, url, duration: int = 0, properties : Dict[str, object]=None, measurements: Dict[str, object]=None) -> None: """ Send information about the page viewed in the application (a web page for instance). :param name: the name of the page that was viewed. :param url: the URL of the page that was viewed. :param duration: the duration of the page view in milliseconds. (defaults to: 0) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
[ "Send", "information", "about", "the", "page", "viewed", "in", "the", "application", "(", "a", "web", "page", "for", "instance", ")", ".", ":", "param", "name", ":", "the", "name", "of", "the", "page", "that", "was", "viewed", ".", ":", "param", "url", ":", "the", "URL", "of", "the", "page", "that", "was", "viewed", ".", ":", "param", "duration", ":", "the", "duration", "of", "the", "page", "view", "in", "milliseconds", ".", "(", "defaults", "to", ":", "0", ")", ":", "param", "properties", ":", "the", "set", "of", "custom", "properties", "the", "client", "wants", "attached", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "measurements", ":", "the", "set", "of", "custom", "measurements", "the", "client", "wants", "to", "attach", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py#L16-L26
[ "def", "track_pageview", "(", "self", ",", "name", ":", "str", ",", "url", ",", "duration", ":", "int", "=", "0", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "measurements", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ")", "->", "None", ":", "raise", "NotImplementedError", "(", "'BotTelemetryClient.track_request(): is not implemented.'", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
BotTelemetryClient.track_exception
Send information about a single exception that occurred in the application. :param type: the type of the exception that was thrown. :param value: the exception that the client wants to send. :param tb: the traceback information as returned by :func:`sys.exc_info`. :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py
def track_exception(self, type: type = None, value : Exception =None, tb : traceback =None, properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None: """ Send information about a single exception that occurred in the application. :param type: the type of the exception that was thrown. :param value: the exception that the client wants to send. :param tb: the traceback information as returned by :func:`sys.exc_info`. :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
def track_exception(self, type: type = None, value : Exception =None, tb : traceback =None, properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None: """ Send information about a single exception that occurred in the application. :param type: the type of the exception that was thrown. :param value: the exception that the client wants to send. :param tb: the traceback information as returned by :func:`sys.exc_info`. :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
[ "Send", "information", "about", "a", "single", "exception", "that", "occurred", "in", "the", "application", ".", ":", "param", "type", ":", "the", "type", "of", "the", "exception", "that", "was", "thrown", ".", ":", "param", "value", ":", "the", "exception", "that", "the", "client", "wants", "to", "send", ".", ":", "param", "tb", ":", "the", "traceback", "information", "as", "returned", "by", ":", "func", ":", "sys", ".", "exc_info", ".", ":", "param", "properties", ":", "the", "set", "of", "custom", "properties", "the", "client", "wants", "attached", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "measurements", ":", "the", "set", "of", "custom", "measurements", "the", "client", "wants", "to", "attach", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py#L29-L39
[ "def", "track_exception", "(", "self", ",", "type", ":", "type", "=", "None", ",", "value", ":", "Exception", "=", "None", ",", "tb", ":", "traceback", "=", "None", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "measurements", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ")", "->", "None", ":", "raise", "NotImplementedError", "(", "'BotTelemetryClient.track_request(): is not implemented.'", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
BotTelemetryClient.track_metric
Send information about a single metric data point that was captured for the application. :param name: The name of the metric that was captured. :param value: The value of the metric that was captured. :param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`) :param count: the number of metrics that were aggregated into this data point. (defaults to: None) :param min: the minimum of all metrics collected that were aggregated into this data point. (defaults to: None) :param max: the maximum of all metrics collected that were aggregated into this data point. (defaults to: None) :param std_dev: the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py
def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None, count: int =None, min: float=None, max: float=None, std_dev: float=None, properties: Dict[str, object]=None) -> NotImplemented: """ Send information about a single metric data point that was captured for the application. :param name: The name of the metric that was captured. :param value: The value of the metric that was captured. :param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`) :param count: the number of metrics that were aggregated into this data point. (defaults to: None) :param min: the minimum of all metrics collected that were aggregated into this data point. (defaults to: None) :param max: the maximum of all metrics collected that were aggregated into this data point. (defaults to: None) :param std_dev: the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_metric(): is not implemented.')
def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None, count: int =None, min: float=None, max: float=None, std_dev: float=None, properties: Dict[str, object]=None) -> NotImplemented: """ Send information about a single metric data point that was captured for the application. :param name: The name of the metric that was captured. :param value: The value of the metric that was captured. :param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`) :param count: the number of metrics that were aggregated into this data point. (defaults to: None) :param min: the minimum of all metrics collected that were aggregated into this data point. (defaults to: None) :param max: the maximum of all metrics collected that were aggregated into this data point. (defaults to: None) :param std_dev: the standard deviation of all metrics collected that were aggregated into this data point. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_metric(): is not implemented.')
[ "Send", "information", "about", "a", "single", "metric", "data", "point", "that", "was", "captured", "for", "the", "application", ".", ":", "param", "name", ":", "The", "name", "of", "the", "metric", "that", "was", "captured", ".", ":", "param", "value", ":", "The", "value", "of", "the", "metric", "that", "was", "captured", ".", ":", "param", "type", ":", "The", "type", "of", "the", "metric", ".", "(", "defaults", "to", ":", "TelemetryDataPointType", ".", "aggregation", ")", ":", "param", "count", ":", "the", "number", "of", "metrics", "that", "were", "aggregated", "into", "this", "data", "point", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "min", ":", "the", "minimum", "of", "all", "metrics", "collected", "that", "were", "aggregated", "into", "this", "data", "point", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "max", ":", "the", "maximum", "of", "all", "metrics", "collected", "that", "were", "aggregated", "into", "this", "data", "point", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "std_dev", ":", "the", "standard", "deviation", "of", "all", "metrics", "collected", "that", "were", "aggregated", "into", "this", "data", "point", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "properties", ":", "the", "set", "of", "custom", "properties", "the", "client", "wants", "attached", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py#L53-L67
[ "def", "track_metric", "(", "self", ",", "name", ":", "str", ",", "value", ":", "float", ",", "type", ":", "TelemetryDataPointType", "=", "None", ",", "count", ":", "int", "=", "None", ",", "min", ":", "float", "=", "None", ",", "max", ":", "float", "=", "None", ",", "std_dev", ":", "float", "=", "None", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ")", "->", "NotImplemented", ":", "raise", "NotImplementedError", "(", "'BotTelemetryClient.track_metric(): is not implemented.'", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
BotTelemetryClient.track_request
Sends a single request that was captured for the application. :param name: The name for this request. All requests with the same name will be grouped together. :param url: The actual URL for this request (to show in individual request instances). :param success: True if the request ended in success, False otherwise. :param start_time: the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None) :param duration: the number of milliseconds that this request lasted. (defaults to: None) :param response_code: the response code that this request returned. (defaults to: None) :param http_method: the HTTP method that triggered this request. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) :param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None)
libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py
def track_request(self, name: str, url: str, success: bool, start_time: str=None, duration: int=None, response_code: str =None, http_method: str=None, properties: Dict[str, object]=None, measurements: Dict[str, object]=None, request_id: str=None): """ Sends a single request that was captured for the application. :param name: The name for this request. All requests with the same name will be grouped together. :param url: The actual URL for this request (to show in individual request instances). :param success: True if the request ended in success, False otherwise. :param start_time: the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None) :param duration: the number of milliseconds that this request lasted. (defaults to: None) :param response_code: the response code that this request returned. (defaults to: None) :param http_method: the HTTP method that triggered this request. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) :param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
def track_request(self, name: str, url: str, success: bool, start_time: str=None, duration: int=None, response_code: str =None, http_method: str=None, properties: Dict[str, object]=None, measurements: Dict[str, object]=None, request_id: str=None): """ Sends a single request that was captured for the application. :param name: The name for this request. All requests with the same name will be grouped together. :param url: The actual URL for this request (to show in individual request instances). :param success: True if the request ended in success, False otherwise. :param start_time: the start time of the request. The value should look the same as the one returned by :func:`datetime.isoformat()` (defaults to: None) :param duration: the number of milliseconds that this request lasted. (defaults to: None) :param response_code: the response code that this request returned. (defaults to: None) :param http_method: the HTTP method that triggered this request. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) :param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_request(): is not implemented.')
[ "Sends", "a", "single", "request", "that", "was", "captured", "for", "the", "application", ".", ":", "param", "name", ":", "The", "name", "for", "this", "request", ".", "All", "requests", "with", "the", "same", "name", "will", "be", "grouped", "together", ".", ":", "param", "url", ":", "The", "actual", "URL", "for", "this", "request", "(", "to", "show", "in", "individual", "request", "instances", ")", ".", ":", "param", "success", ":", "True", "if", "the", "request", "ended", "in", "success", "False", "otherwise", ".", ":", "param", "start_time", ":", "the", "start", "time", "of", "the", "request", ".", "The", "value", "should", "look", "the", "same", "as", "the", "one", "returned", "by", ":", "func", ":", "datetime", ".", "isoformat", "()", "(", "defaults", "to", ":", "None", ")", ":", "param", "duration", ":", "the", "number", "of", "milliseconds", "that", "this", "request", "lasted", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "response_code", ":", "the", "response", "code", "that", "this", "request", "returned", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "http_method", ":", "the", "HTTP", "method", "that", "triggered", "this", "request", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "properties", ":", "the", "set", "of", "custom", "properties", "the", "client", "wants", "attached", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "measurements", ":", "the", "set", "of", "custom", "measurements", "the", "client", "wants", "to", "attach", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "request_id", ":", "the", "id", "for", "this", "request", ".", "If", "None", "a", "new", "uuid", "will", "be", "generated", ".", "(", "defaults", "to", ":", "None", ")" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py#L80-L97
[ "def", "track_request", "(", "self", ",", "name", ":", "str", ",", "url", ":", "str", ",", "success", ":", "bool", ",", "start_time", ":", "str", "=", "None", ",", "duration", ":", "int", "=", "None", ",", "response_code", ":", "str", "=", "None", ",", "http_method", ":", "str", "=", "None", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "measurements", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "request_id", ":", "str", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'BotTelemetryClient.track_request(): is not implemented.'", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
BotTelemetryClient.track_dependency
Sends a single dependency telemetry that was captured for the application. :param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. :param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. :param type: the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. (default to: None) :param target: the target site of a dependency call. Examples are server name, host address. (default to: None) :param duration: the number of milliseconds that this dependency call lasted. (defaults to: None) :param success: true if the dependency call ended in success, false otherwise. (defaults to: None) :param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) :param id: the id for this dependency call. If None, a new uuid will be generated. (defaults to: None)
libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py
def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None, success:bool=None, result_code:str=None, properties:Dict[str, object]=None, measurements:Dict[str, object]=None, dependency_id:str=None): """ Sends a single dependency telemetry that was captured for the application. :param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. :param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. :param type: the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. (default to: None) :param target: the target site of a dependency call. Examples are server name, host address. (default to: None) :param duration: the number of milliseconds that this dependency call lasted. (defaults to: None) :param success: true if the dependency call ended in success, false otherwise. (defaults to: None) :param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) :param id: the id for this dependency call. If None, a new uuid will be generated. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_dependency(): is not implemented.')
def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None, success:bool=None, result_code:str=None, properties:Dict[str, object]=None, measurements:Dict[str, object]=None, dependency_id:str=None): """ Sends a single dependency telemetry that was captured for the application. :param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. :param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. :param type: the dependency type name. Low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. (default to: None) :param target: the target site of a dependency call. Examples are server name, host address. (default to: None) :param duration: the number of milliseconds that this dependency call lasted. (defaults to: None) :param success: true if the dependency call ended in success, false otherwise. (defaults to: None) :param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code. (defaults to: None) :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) :param id: the id for this dependency call. If None, a new uuid will be generated. (defaults to: None) """ raise NotImplementedError('BotTelemetryClient.track_dependency(): is not implemented.')
[ "Sends", "a", "single", "dependency", "telemetry", "that", "was", "captured", "for", "the", "application", ".", ":", "param", "name", ":", "the", "name", "of", "the", "command", "initiated", "with", "this", "dependency", "call", ".", "Low", "cardinality", "value", ".", "Examples", "are", "stored", "procedure", "name", "and", "URL", "path", "template", ".", ":", "param", "data", ":", "the", "command", "initiated", "by", "this", "dependency", "call", ".", "Examples", "are", "SQL", "statement", "and", "HTTP", "URL", "with", "all", "query", "parameters", ".", ":", "param", "type", ":", "the", "dependency", "type", "name", ".", "Low", "cardinality", "value", "for", "logical", "grouping", "of", "dependencies", "and", "interpretation", "of", "other", "fields", "like", "commandName", "and", "resultCode", ".", "Examples", "are", "SQL", "Azure", "table", "and", "HTTP", ".", "(", "default", "to", ":", "None", ")", ":", "param", "target", ":", "the", "target", "site", "of", "a", "dependency", "call", ".", "Examples", "are", "server", "name", "host", "address", ".", "(", "default", "to", ":", "None", ")", ":", "param", "duration", ":", "the", "number", "of", "milliseconds", "that", "this", "dependency", "call", "lasted", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "success", ":", "true", "if", "the", "dependency", "call", "ended", "in", "success", "false", "otherwise", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "result_code", ":", "the", "result", "code", "of", "a", "dependency", "call", ".", "Examples", "are", "SQL", "error", "code", "and", "HTTP", "status", "code", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "properties", ":", "the", "set", "of", "custom", "properties", "the", "client", "wants", "attached", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "measurements", ":", "the", "set", "of", "custom", "measurements", "the", "client", "wants", "to", "attach", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "id", ":", "the", "id", "for", "this", "dependency", "call", ".", "If", "None", "a", "new", "uuid", "will", "be", "generated", ".", "(", "defaults", "to", ":", "None", ")" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/bot_telemetry_client.py#L100-L116
[ "def", "track_dependency", "(", "self", ",", "name", ":", "str", ",", "data", ":", "str", ",", "type", ":", "str", "=", "None", ",", "target", ":", "str", "=", "None", ",", "duration", ":", "int", "=", "None", ",", "success", ":", "bool", "=", "None", ",", "result_code", ":", "str", "=", "None", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "measurements", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "dependency_id", ":", "str", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'BotTelemetryClient.track_dependency(): is not implemented.'", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
MessageFactory.text
Returns a simple text message. :Example: message = MessageFactory.text('Greetings from example message') await context.send_activity(message) :param text: :param speak: :param input_hint: :return:
libraries/botbuilder-core/botbuilder/core/message_factory.py
def text(text: str, speak: str = None, input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity: """ Returns a simple text message. :Example: message = MessageFactory.text('Greetings from example message') await context.send_activity(message) :param text: :param speak: :param input_hint: :return: """ message = Activity(type=ActivityTypes.message, text=text, input_hint=input_hint) if speak: message.speak = speak return message
def text(text: str, speak: str = None, input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity: """ Returns a simple text message. :Example: message = MessageFactory.text('Greetings from example message') await context.send_activity(message) :param text: :param speak: :param input_hint: :return: """ message = Activity(type=ActivityTypes.message, text=text, input_hint=input_hint) if speak: message.speak = speak return message
[ "Returns", "a", "simple", "text", "message", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/message_factory.py#L27-L44
[ "def", "text", "(", "text", ":", "str", ",", "speak", ":", "str", "=", "None", ",", "input_hint", ":", "Union", "[", "InputHints", ",", "str", "]", "=", "InputHints", ".", "accepting_input", ")", "->", "Activity", ":", "message", "=", "Activity", "(", "type", "=", "ActivityTypes", ".", "message", ",", "text", "=", "text", ",", "input_hint", "=", "input_hint", ")", "if", "speak", ":", "message", ".", "speak", "=", "speak", "return", "message" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
MessageFactory.suggested_actions
Returns a message that includes a set of suggested actions and optional text. :Example: message = MessageFactory.suggested_actions([CardAction(title='a', type=ActionTypes.im_back, value='a'), CardAction(title='b', type=ActionTypes.im_back, value='b'), CardAction(title='c', type=ActionTypes.im_back, value='c')], 'Choose a color') await context.send_activity(message) :param actions: :param text: :param speak: :param input_hint: :return:
libraries/botbuilder-core/botbuilder/core/message_factory.py
def suggested_actions(actions: List[CardAction], text: str = None, speak: str = None, input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity: """ Returns a message that includes a set of suggested actions and optional text. :Example: message = MessageFactory.suggested_actions([CardAction(title='a', type=ActionTypes.im_back, value='a'), CardAction(title='b', type=ActionTypes.im_back, value='b'), CardAction(title='c', type=ActionTypes.im_back, value='c')], 'Choose a color') await context.send_activity(message) :param actions: :param text: :param speak: :param input_hint: :return: """ actions = SuggestedActions(actions=actions) message = Activity(type=ActivityTypes.message, input_hint=input_hint, suggested_actions=actions) if text: message.text = text if speak: message.speak = speak return message
def suggested_actions(actions: List[CardAction], text: str = None, speak: str = None, input_hint: Union[InputHints, str] = InputHints.accepting_input) -> Activity: """ Returns a message that includes a set of suggested actions and optional text. :Example: message = MessageFactory.suggested_actions([CardAction(title='a', type=ActionTypes.im_back, value='a'), CardAction(title='b', type=ActionTypes.im_back, value='b'), CardAction(title='c', type=ActionTypes.im_back, value='c')], 'Choose a color') await context.send_activity(message) :param actions: :param text: :param speak: :param input_hint: :return: """ actions = SuggestedActions(actions=actions) message = Activity(type=ActivityTypes.message, input_hint=input_hint, suggested_actions=actions) if text: message.text = text if speak: message.speak = speak return message
[ "Returns", "a", "message", "that", "includes", "a", "set", "of", "suggested", "actions", "and", "optional", "text", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/message_factory.py#L47-L70
[ "def", "suggested_actions", "(", "actions", ":", "List", "[", "CardAction", "]", ",", "text", ":", "str", "=", "None", ",", "speak", ":", "str", "=", "None", ",", "input_hint", ":", "Union", "[", "InputHints", ",", "str", "]", "=", "InputHints", ".", "accepting_input", ")", "->", "Activity", ":", "actions", "=", "SuggestedActions", "(", "actions", "=", "actions", ")", "message", "=", "Activity", "(", "type", "=", "ActivityTypes", ".", "message", ",", "input_hint", "=", "input_hint", ",", "suggested_actions", "=", "actions", ")", "if", "text", ":", "message", ".", "text", "=", "text", "if", "speak", ":", "message", ".", "speak", "=", "speak", "return", "message" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
MessageFactory.attachment
Returns a single message activity containing an attachment. :Example: message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='White T-Shirt', images=[CardImage(url='https://example.com/whiteShirt.jpg')], buttons=[CardAction(title='buy')]))) await context.send_activity(message) :param attachment: :param text: :param speak: :param input_hint: :return:
libraries/botbuilder-core/botbuilder/core/message_factory.py
def attachment(attachment: Attachment, text: str = None, speak: str = None, input_hint: Union[InputHints, str] = None): """ Returns a single message activity containing an attachment. :Example: message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='White T-Shirt', images=[CardImage(url='https://example.com/whiteShirt.jpg')], buttons=[CardAction(title='buy')]))) await context.send_activity(message) :param attachment: :param text: :param speak: :param input_hint: :return: """ return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)
def attachment(attachment: Attachment, text: str = None, speak: str = None, input_hint: Union[InputHints, str] = None): """ Returns a single message activity containing an attachment. :Example: message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='White T-Shirt', images=[CardImage(url='https://example.com/whiteShirt.jpg')], buttons=[CardAction(title='buy')]))) await context.send_activity(message) :param attachment: :param text: :param speak: :param input_hint: :return: """ return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)
[ "Returns", "a", "single", "message", "activity", "containing", "an", "attachment", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/message_factory.py#L73-L90
[ "def", "attachment", "(", "attachment", ":", "Attachment", ",", "text", ":", "str", "=", "None", ",", "speak", ":", "str", "=", "None", ",", "input_hint", ":", "Union", "[", "InputHints", ",", "str", "]", "=", "None", ")", ":", "return", "attachment_activity", "(", "AttachmentLayoutTypes", ".", "list", ",", "[", "attachment", "]", ",", "text", ",", "speak", ",", "input_hint", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
MessageFactory.list
Returns a message that will display a set of attachments in list form. :Example: message = MessageFactory.list([CardFactory.hero_card(HeroCard(title='title1', images=[CardImage(url='imageUrl1')], buttons=[CardAction(title='button1')])), CardFactory.hero_card(HeroCard(title='title2', images=[CardImage(url='imageUrl2')], buttons=[CardAction(title='button2')])), CardFactory.hero_card(HeroCard(title='title3', images=[CardImage(url='imageUrl3')], buttons=[CardAction(title='button3')]))]) await context.send_activity(message) :param attachments: :param text: :param speak: :param input_hint: :return:
libraries/botbuilder-core/botbuilder/core/message_factory.py
def list(attachments: List[Attachment], text: str = None, speak: str = None, input_hint: Union[InputHints, str] = None) -> Activity: """ Returns a message that will display a set of attachments in list form. :Example: message = MessageFactory.list([CardFactory.hero_card(HeroCard(title='title1', images=[CardImage(url='imageUrl1')], buttons=[CardAction(title='button1')])), CardFactory.hero_card(HeroCard(title='title2', images=[CardImage(url='imageUrl2')], buttons=[CardAction(title='button2')])), CardFactory.hero_card(HeroCard(title='title3', images=[CardImage(url='imageUrl3')], buttons=[CardAction(title='button3')]))]) await context.send_activity(message) :param attachments: :param text: :param speak: :param input_hint: :return: """ return attachment_activity(AttachmentLayoutTypes.list, attachments, text, speak, input_hint)
def list(attachments: List[Attachment], text: str = None, speak: str = None, input_hint: Union[InputHints, str] = None) -> Activity: """ Returns a message that will display a set of attachments in list form. :Example: message = MessageFactory.list([CardFactory.hero_card(HeroCard(title='title1', images=[CardImage(url='imageUrl1')], buttons=[CardAction(title='button1')])), CardFactory.hero_card(HeroCard(title='title2', images=[CardImage(url='imageUrl2')], buttons=[CardAction(title='button2')])), CardFactory.hero_card(HeroCard(title='title3', images=[CardImage(url='imageUrl3')], buttons=[CardAction(title='button3')]))]) await context.send_activity(message) :param attachments: :param text: :param speak: :param input_hint: :return: """ return attachment_activity(AttachmentLayoutTypes.list, attachments, text, speak, input_hint)
[ "Returns", "a", "message", "that", "will", "display", "a", "set", "of", "attachments", "in", "list", "form", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/message_factory.py#L93-L116
[ "def", "list", "(", "attachments", ":", "List", "[", "Attachment", "]", ",", "text", ":", "str", "=", "None", ",", "speak", ":", "str", "=", "None", ",", "input_hint", ":", "Union", "[", "InputHints", ",", "str", "]", "=", "None", ")", "->", "Activity", ":", "return", "attachment_activity", "(", "AttachmentLayoutTypes", ".", "list", ",", "attachments", ",", "text", ",", "speak", ",", "input_hint", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
MessageFactory.content_url
Returns a message that will display a single image or video to a user. :Example: message = MessageFactory.content_url('https://example.com/hawaii.jpg', 'image/jpeg', 'Hawaii Trip', 'A photo from our family vacation.') await context.send_activity(message) :param url: :param content_type: :param name: :param text: :param speak: :param input_hint: :return:
libraries/botbuilder-core/botbuilder/core/message_factory.py
def content_url(url: str, content_type: str, name: str = None, text: str = None, speak: str = None, input_hint: Union[InputHints, str] = None): """ Returns a message that will display a single image or video to a user. :Example: message = MessageFactory.content_url('https://example.com/hawaii.jpg', 'image/jpeg', 'Hawaii Trip', 'A photo from our family vacation.') await context.send_activity(message) :param url: :param content_type: :param name: :param text: :param speak: :param input_hint: :return: """ attachment = Attachment(content_type=content_type, content_url=url) if name: attachment.name = name return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)
def content_url(url: str, content_type: str, name: str = None, text: str = None, speak: str = None, input_hint: Union[InputHints, str] = None): """ Returns a message that will display a single image or video to a user. :Example: message = MessageFactory.content_url('https://example.com/hawaii.jpg', 'image/jpeg', 'Hawaii Trip', 'A photo from our family vacation.') await context.send_activity(message) :param url: :param content_type: :param name: :param text: :param speak: :param input_hint: :return: """ attachment = Attachment(content_type=content_type, content_url=url) if name: attachment.name = name return attachment_activity(AttachmentLayoutTypes.list, [attachment], text, speak, input_hint)
[ "Returns", "a", "message", "that", "will", "display", "a", "single", "image", "or", "video", "to", "a", "user", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/message_factory.py#L145-L166
[ "def", "content_url", "(", "url", ":", "str", ",", "content_type", ":", "str", ",", "name", ":", "str", "=", "None", ",", "text", ":", "str", "=", "None", ",", "speak", ":", "str", "=", "None", ",", "input_hint", ":", "Union", "[", "InputHints", ",", "str", "]", "=", "None", ")", ":", "attachment", "=", "Attachment", "(", "content_type", "=", "content_type", ",", "content_url", "=", "url", ")", "if", "name", ":", "attachment", ".", "name", "=", "name", "return", "attachment_activity", "(", "AttachmentLayoutTypes", ".", "list", ",", "[", "attachment", "]", ",", "text", ",", "speak", ",", "input_hint", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ChannelValidation.authenticate_token_service_url
Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :param service_url: Claim value that must match in the identity. :type service_url: str :return: A valid ClaimsIdentity. :raises Exception:
libraries/botframework-connector/botframework/connector/auth/channel_validation.py
async def authenticate_token_service_url(auth_header: str, credentials: CredentialProvider, service_url: str, channel_id: str) -> ClaimsIdentity: """ Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :param service_url: Claim value that must match in the identity. :type service_url: str :return: A valid ClaimsIdentity. :raises Exception: """ identity = await asyncio.ensure_future( ChannelValidation.authenticate_token(auth_header, credentials, channel_id)) service_url_claim = identity.get_claim_value(ChannelValidation.SERVICE_URL_CLAIM) if service_url_claim != service_url: # Claim must match. Not Authorized. raise Exception('Unauthorized. service_url claim do not match.') return identity
async def authenticate_token_service_url(auth_header: str, credentials: CredentialProvider, service_url: str, channel_id: str) -> ClaimsIdentity: """ Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :param service_url: Claim value that must match in the identity. :type service_url: str :return: A valid ClaimsIdentity. :raises Exception: """ identity = await asyncio.ensure_future( ChannelValidation.authenticate_token(auth_header, credentials, channel_id)) service_url_claim = identity.get_claim_value(ChannelValidation.SERVICE_URL_CLAIM) if service_url_claim != service_url: # Claim must match. Not Authorized. raise Exception('Unauthorized. service_url claim do not match.') return identity
[ "Validate", "the", "incoming", "Auth", "Header" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/auth/channel_validation.py#L25-L49
[ "async", "def", "authenticate_token_service_url", "(", "auth_header", ":", "str", ",", "credentials", ":", "CredentialProvider", ",", "service_url", ":", "str", ",", "channel_id", ":", "str", ")", "->", "ClaimsIdentity", ":", "identity", "=", "await", "asyncio", ".", "ensure_future", "(", "ChannelValidation", ".", "authenticate_token", "(", "auth_header", ",", "credentials", ",", "channel_id", ")", ")", "service_url_claim", "=", "identity", ".", "get_claim_value", "(", "ChannelValidation", ".", "SERVICE_URL_CLAIM", ")", "if", "service_url_claim", "!=", "service_url", ":", "# Claim must match. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. service_url claim do not match.'", ")", "return", "identity" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ChannelValidation.authenticate_token
Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :return: A valid ClaimsIdentity. :raises Exception:
libraries/botframework-connector/botframework/connector/auth/channel_validation.py
async def authenticate_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity: """ Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :return: A valid ClaimsIdentity. :raises Exception: """ token_extractor = JwtTokenExtractor( ChannelValidation.TO_BOT_FROM_CHANNEL_TOKEN_VALIDATION_PARAMETERS, Constants.TO_BOT_FROM_CHANNEL_OPEN_ID_METADATA_URL, Constants.ALLOWED_SIGNING_ALGORITHMS) identity = await asyncio.ensure_future( token_extractor.get_identity_from_auth_header(auth_header, channel_id)) if not identity: # No valid identity. Not Authorized. raise Exception('Unauthorized. No valid identity.') if not identity.isAuthenticated: # The token is in some way invalid. Not Authorized. raise Exception('Unauthorized. Is not authenticated') # Now check that the AppID in the claimset matches # what we're looking for. Note that in a multi-tenant bot, this value # comes from developer code that may be reaching out to a service, hence the # Async validation. # Look for the "aud" claim, but only if issued from the Bot Framework if identity.get_claim_value(Constants.ISSUER_CLAIM) != Constants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER: # The relevant Audience Claim MUST be present. Not Authorized. raise Exception('Unauthorized. Audience Claim MUST be present.') # The AppId from the claim in the token must match the AppId specified by the developer. # Note that the Bot Framework uses the Audience claim ("aud") to pass the AppID. aud_claim = identity.get_claim_value(Constants.AUDIENCE_CLAIM) is_valid_app_id = await asyncio.ensure_future(credentials.is_valid_appid(aud_claim or "")) if not is_valid_app_id: # The AppId is not valid or not present. Not Authorized. raise Exception('Unauthorized. Invalid AppId passed on token: ', aud_claim) return identity
async def authenticate_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity: """ Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :return: A valid ClaimsIdentity. :raises Exception: """ token_extractor = JwtTokenExtractor( ChannelValidation.TO_BOT_FROM_CHANNEL_TOKEN_VALIDATION_PARAMETERS, Constants.TO_BOT_FROM_CHANNEL_OPEN_ID_METADATA_URL, Constants.ALLOWED_SIGNING_ALGORITHMS) identity = await asyncio.ensure_future( token_extractor.get_identity_from_auth_header(auth_header, channel_id)) if not identity: # No valid identity. Not Authorized. raise Exception('Unauthorized. No valid identity.') if not identity.isAuthenticated: # The token is in some way invalid. Not Authorized. raise Exception('Unauthorized. Is not authenticated') # Now check that the AppID in the claimset matches # what we're looking for. Note that in a multi-tenant bot, this value # comes from developer code that may be reaching out to a service, hence the # Async validation. # Look for the "aud" claim, but only if issued from the Bot Framework if identity.get_claim_value(Constants.ISSUER_CLAIM) != Constants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER: # The relevant Audience Claim MUST be present. Not Authorized. raise Exception('Unauthorized. Audience Claim MUST be present.') # The AppId from the claim in the token must match the AppId specified by the developer. # Note that the Bot Framework uses the Audience claim ("aud") to pass the AppID. aud_claim = identity.get_claim_value(Constants.AUDIENCE_CLAIM) is_valid_app_id = await asyncio.ensure_future(credentials.is_valid_appid(aud_claim or "")) if not is_valid_app_id: # The AppId is not valid or not present. Not Authorized. raise Exception('Unauthorized. Invalid AppId passed on token: ', aud_claim) return identity
[ "Validate", "the", "incoming", "Auth", "Header" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/auth/channel_validation.py#L52-L99
[ "async", "def", "authenticate_token", "(", "auth_header", ":", "str", ",", "credentials", ":", "CredentialProvider", ",", "channel_id", ":", "str", ")", "->", "ClaimsIdentity", ":", "token_extractor", "=", "JwtTokenExtractor", "(", "ChannelValidation", ".", "TO_BOT_FROM_CHANNEL_TOKEN_VALIDATION_PARAMETERS", ",", "Constants", ".", "TO_BOT_FROM_CHANNEL_OPEN_ID_METADATA_URL", ",", "Constants", ".", "ALLOWED_SIGNING_ALGORITHMS", ")", "identity", "=", "await", "asyncio", ".", "ensure_future", "(", "token_extractor", ".", "get_identity_from_auth_header", "(", "auth_header", ",", "channel_id", ")", ")", "if", "not", "identity", ":", "# No valid identity. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. No valid identity.'", ")", "if", "not", "identity", ".", "isAuthenticated", ":", "# The token is in some way invalid. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. Is not authenticated'", ")", "# Now check that the AppID in the claimset matches", "# what we're looking for. Note that in a multi-tenant bot, this value", "# comes from developer code that may be reaching out to a service, hence the", "# Async validation.", "# Look for the \"aud\" claim, but only if issued from the Bot Framework", "if", "identity", ".", "get_claim_value", "(", "Constants", ".", "ISSUER_CLAIM", ")", "!=", "Constants", ".", "TO_BOT_FROM_CHANNEL_TOKEN_ISSUER", ":", "# The relevant Audience Claim MUST be present. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. Audience Claim MUST be present.'", ")", "# The AppId from the claim in the token must match the AppId specified by the developer.", "# Note that the Bot Framework uses the Audience claim (\"aud\") to pass the AppID.", "aud_claim", "=", "identity", ".", "get_claim_value", "(", "Constants", ".", "AUDIENCE_CLAIM", ")", "is_valid_app_id", "=", "await", "asyncio", ".", "ensure_future", "(", "credentials", ".", "is_valid_appid", "(", "aud_claim", "or", "\"\"", ")", ")", "if", "not", "is_valid_app_id", ":", "# The AppId is not valid or not present. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. Invalid AppId passed on token: '", ",", "aud_claim", ")", "return", "identity" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ActivityUtil.create_trace
Creates a trace activity based on this activity. :param turn_activity: :type turn_activity: Activity :param name: The value to assign to the trace activity's <see cref="Activity.name"/> property. :type name: str :param value: The value to assign to the trace activity's <see cref="Activity.value"/> property., defaults to None :param value: object, optional :param value_type: The value to assign to the trace activity's <see cref="Activity.value_type"/> property, defaults to None :param value_type: str, optional :param label: The value to assign to the trace activity's <see cref="Activity.label"/> property, defaults to None :param label: str, optional :return: The created trace activity. :rtype: Activity
libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py
def create_trace( turn_activity: Activity, name: str, value: object = None, value_type: str = None, label: str = None, ) -> Activity: """Creates a trace activity based on this activity. :param turn_activity: :type turn_activity: Activity :param name: The value to assign to the trace activity's <see cref="Activity.name"/> property. :type name: str :param value: The value to assign to the trace activity's <see cref="Activity.value"/> property., defaults to None :param value: object, optional :param value_type: The value to assign to the trace activity's <see cref="Activity.value_type"/> property, defaults to None :param value_type: str, optional :param label: The value to assign to the trace activity's <see cref="Activity.label"/> property, defaults to None :param label: str, optional :return: The created trace activity. :rtype: Activity """ from_property = ( ChannelAccount( id=turn_activity.recipient.id, name=turn_activity.recipient.name ) if turn_activity.recipient is not None else ChannelAccount() ) if value_type is None and value is not None: value_type = type(value).__name__ reply = Activity( type=ActivityTypes.trace, timestamp=datetime.utcnow(), from_property=from_property, recipient=ChannelAccount( id=turn_activity.from_property.id, name=turn_activity.from_property.name ), reply_to_id=turn_activity.id, service_url=turn_activity.service_url, channel_id=turn_activity.channel_id, conversation=ConversationAccount( is_group=turn_activity.conversation.is_group, id=turn_activity.conversation.id, name=turn_activity.conversation.name, ), name=name, label=label, value_type=value_type, value=value, ) return reply
def create_trace( turn_activity: Activity, name: str, value: object = None, value_type: str = None, label: str = None, ) -> Activity: """Creates a trace activity based on this activity. :param turn_activity: :type turn_activity: Activity :param name: The value to assign to the trace activity's <see cref="Activity.name"/> property. :type name: str :param value: The value to assign to the trace activity's <see cref="Activity.value"/> property., defaults to None :param value: object, optional :param value_type: The value to assign to the trace activity's <see cref="Activity.value_type"/> property, defaults to None :param value_type: str, optional :param label: The value to assign to the trace activity's <see cref="Activity.label"/> property, defaults to None :param label: str, optional :return: The created trace activity. :rtype: Activity """ from_property = ( ChannelAccount( id=turn_activity.recipient.id, name=turn_activity.recipient.name ) if turn_activity.recipient is not None else ChannelAccount() ) if value_type is None and value is not None: value_type = type(value).__name__ reply = Activity( type=ActivityTypes.trace, timestamp=datetime.utcnow(), from_property=from_property, recipient=ChannelAccount( id=turn_activity.from_property.id, name=turn_activity.from_property.name ), reply_to_id=turn_activity.id, service_url=turn_activity.service_url, channel_id=turn_activity.channel_id, conversation=ConversationAccount( is_group=turn_activity.conversation.is_group, id=turn_activity.conversation.id, name=turn_activity.conversation.name, ), name=name, label=label, value_type=value_type, value=value, ) return reply
[ "Creates", "a", "trace", "activity", "based", "on", "this", "activity", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py#L16-L69
[ "def", "create_trace", "(", "turn_activity", ":", "Activity", ",", "name", ":", "str", ",", "value", ":", "object", "=", "None", ",", "value_type", ":", "str", "=", "None", ",", "label", ":", "str", "=", "None", ",", ")", "->", "Activity", ":", "from_property", "=", "(", "ChannelAccount", "(", "id", "=", "turn_activity", ".", "recipient", ".", "id", ",", "name", "=", "turn_activity", ".", "recipient", ".", "name", ")", "if", "turn_activity", ".", "recipient", "is", "not", "None", "else", "ChannelAccount", "(", ")", ")", "if", "value_type", "is", "None", "and", "value", "is", "not", "None", ":", "value_type", "=", "type", "(", "value", ")", ".", "__name__", "reply", "=", "Activity", "(", "type", "=", "ActivityTypes", ".", "trace", ",", "timestamp", "=", "datetime", ".", "utcnow", "(", ")", ",", "from_property", "=", "from_property", ",", "recipient", "=", "ChannelAccount", "(", "id", "=", "turn_activity", ".", "from_property", ".", "id", ",", "name", "=", "turn_activity", ".", "from_property", ".", "name", ")", ",", "reply_to_id", "=", "turn_activity", ".", "id", ",", "service_url", "=", "turn_activity", ".", "service_url", ",", "channel_id", "=", "turn_activity", ".", "channel_id", ",", "conversation", "=", "ConversationAccount", "(", "is_group", "=", "turn_activity", ".", "conversation", ".", "is_group", ",", "id", "=", "turn_activity", ".", "conversation", ".", "id", ",", "name", "=", "turn_activity", ".", "conversation", ".", "name", ",", ")", ",", "name", "=", "name", ",", "label", "=", "label", ",", "value_type", "=", "value_type", ",", "value", "=", "value", ",", ")", "return", "reply" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogSet.add
Adds a new dialog to the set and returns the added dialog. :param dialog: The dialog to add.
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_set.py
async def add(self, dialog: Dialog): """ Adds a new dialog to the set and returns the added dialog. :param dialog: The dialog to add. """ if dialog is None or not isinstance(dialog, Dialog): raise TypeError('DialogSet.add(): dialog cannot be None and must be a Dialog or derived class.') if dialog.id in self._dialogs: raise TypeError("DialogSet.add(): A dialog with an id of '%s' already added." % dialog.id) # dialog.telemetry_client = this._telemetry_client; self._dialogs[dialog.id] = dialog return self
async def add(self, dialog: Dialog): """ Adds a new dialog to the set and returns the added dialog. :param dialog: The dialog to add. """ if dialog is None or not isinstance(dialog, Dialog): raise TypeError('DialogSet.add(): dialog cannot be None and must be a Dialog or derived class.') if dialog.id in self._dialogs: raise TypeError("DialogSet.add(): A dialog with an id of '%s' already added." % dialog.id) # dialog.telemetry_client = this._telemetry_client; self._dialogs[dialog.id] = dialog return self
[ "Adds", "a", "new", "dialog", "to", "the", "set", "and", "returns", "the", "added", "dialog", ".", ":", "param", "dialog", ":", "The", "dialog", "to", "add", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_set.py#L42-L56
[ "async", "def", "add", "(", "self", ",", "dialog", ":", "Dialog", ")", ":", "if", "dialog", "is", "None", "or", "not", "isinstance", "(", "dialog", ",", "Dialog", ")", ":", "raise", "TypeError", "(", "'DialogSet.add(): dialog cannot be None and must be a Dialog or derived class.'", ")", "if", "dialog", ".", "id", "in", "self", ".", "_dialogs", ":", "raise", "TypeError", "(", "\"DialogSet.add(): A dialog with an id of '%s' already added.\"", "%", "dialog", ".", "id", ")", "# dialog.telemetry_client = this._telemetry_client;", "self", ".", "_dialogs", "[", "dialog", ".", "id", "]", "=", "dialog", "return", "self" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogSet.find
Finds a dialog that was previously added to the set using add(dialog) :param dialog_id: ID of the dialog/prompt to look up. :return: The dialog if found, otherwise null.
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_set.py
async def find(self, dialog_id: str) -> Dialog: """ Finds a dialog that was previously added to the set using add(dialog) :param dialog_id: ID of the dialog/prompt to look up. :return: The dialog if found, otherwise null. """ if (not dialog_id): raise TypeError('DialogContext.find(): dialog_id cannot be None.') if dialog_id in self._dialogs: return self._dialogs[dialog_id] return None
async def find(self, dialog_id: str) -> Dialog: """ Finds a dialog that was previously added to the set using add(dialog) :param dialog_id: ID of the dialog/prompt to look up. :return: The dialog if found, otherwise null. """ if (not dialog_id): raise TypeError('DialogContext.find(): dialog_id cannot be None.') if dialog_id in self._dialogs: return self._dialogs[dialog_id] return None
[ "Finds", "a", "dialog", "that", "was", "previously", "added", "to", "the", "set", "using", "add", "(", "dialog", ")", ":", "param", "dialog_id", ":", "ID", "of", "the", "dialog", "/", "prompt", "to", "look", "up", ".", ":", "return", ":", "The", "dialog", "if", "found", "otherwise", "null", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_set.py#L68-L80
[ "async", "def", "find", "(", "self", ",", "dialog_id", ":", "str", ")", "->", "Dialog", ":", "if", "(", "not", "dialog_id", ")", ":", "raise", "TypeError", "(", "'DialogContext.find(): dialog_id cannot be None.'", ")", "if", "dialog_id", "in", "self", ".", "_dialogs", ":", "return", "self", ".", "_dialogs", "[", "dialog_id", "]", "return", "None" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
UserState.get_storage_key
Returns the storage key for the current user state. :param context: :return:
libraries/botbuilder-core/botbuilder/core/user_state.py
def get_storage_key(self, context: TurnContext) -> str: """ Returns the storage key for the current user state. :param context: :return: """ activity = context.activity channel_id = getattr(activity, 'channel_id', None) user_id = getattr(activity.from_property, 'id', None) if hasattr(activity, 'from_property') else None storage_key = None if channel_id and user_id: storage_key = "%s/users/%s" % (channel_id, user_id) return storage_key
def get_storage_key(self, context: TurnContext) -> str: """ Returns the storage key for the current user state. :param context: :return: """ activity = context.activity channel_id = getattr(activity, 'channel_id', None) user_id = getattr(activity.from_property, 'id', None) if hasattr(activity, 'from_property') else None storage_key = None if channel_id and user_id: storage_key = "%s/users/%s" % (channel_id, user_id) return storage_key
[ "Returns", "the", "storage", "key", "for", "the", "current", "user", "state", ".", ":", "param", "context", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/user_state.py#L33-L46
[ "def", "get_storage_key", "(", "self", ",", "context", ":", "TurnContext", ")", "->", "str", ":", "activity", "=", "context", ".", "activity", "channel_id", "=", "getattr", "(", "activity", ",", "'channel_id'", ",", "None", ")", "user_id", "=", "getattr", "(", "activity", ".", "from_property", ",", "'id'", ",", "None", ")", "if", "hasattr", "(", "activity", ",", "'from_property'", ")", "else", "None", "storage_key", "=", "None", "if", "channel_id", "and", "user_id", ":", "storage_key", "=", "\"%s/users/%s\"", "%", "(", "channel_id", ",", "user_id", ")", "return", "storage_key" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
RecognizerResult.get_top_scoring_intent
Return the top scoring intent and its score. :return: Intent and score. :rtype: TopIntent
libraries/botbuilder-ai/botbuilder/ai/luis/recognizer_result.py
def get_top_scoring_intent(self) -> TopIntent: """Return the top scoring intent and its score. :return: Intent and score. :rtype: TopIntent """ if self.intents is None: raise TypeError("result.intents can't be None") top_intent = TopIntent(intent="", score=0.0) for intent_name, intent_score in self.intents.items(): score = intent_score.score if score > top_intent[1]: top_intent = TopIntent(intent_name, score) return top_intent
def get_top_scoring_intent(self) -> TopIntent: """Return the top scoring intent and its score. :return: Intent and score. :rtype: TopIntent """ if self.intents is None: raise TypeError("result.intents can't be None") top_intent = TopIntent(intent="", score=0.0) for intent_name, intent_score in self.intents.items(): score = intent_score.score if score > top_intent[1]: top_intent = TopIntent(intent_name, score) return top_intent
[ "Return", "the", "top", "scoring", "intent", "and", "its", "score", ".", ":", "return", ":", "Intent", "and", "score", ".", ":", "rtype", ":", "TopIntent" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/luis/recognizer_result.py#L147-L163
[ "def", "get_top_scoring_intent", "(", "self", ")", "->", "TopIntent", ":", "if", "self", ".", "intents", "is", "None", ":", "raise", "TypeError", "(", "\"result.intents can't be None\"", ")", "top_intent", "=", "TopIntent", "(", "intent", "=", "\"\"", ",", "score", "=", "0.0", ")", "for", "intent_name", ",", "intent_score", "in", "self", ".", "intents", ".", "items", "(", ")", ":", "score", "=", "intent_score", ".", "score", "if", "score", ">", "top_intent", "[", "1", "]", ":", "top_intent", "=", "TopIntent", "(", "intent_name", ",", "score", ")", "return", "top_intent" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
Dialog.telemetry_client
Sets the telemetry client for logging events.
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog.py
def telemetry_client(self, value: BotTelemetryClient) -> None: """ Sets the telemetry client for logging events. """ if value is None: self._telemetry_client = NullTelemetryClient() else: self._telemetry_client = value
def telemetry_client(self, value: BotTelemetryClient) -> None: """ Sets the telemetry client for logging events. """ if value is None: self._telemetry_client = NullTelemetryClient() else: self._telemetry_client = value
[ "Sets", "the", "telemetry", "client", "for", "logging", "events", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog.py#L33-L40
[ "def", "telemetry_client", "(", "self", ",", "value", ":", "BotTelemetryClient", ")", "->", "None", ":", "if", "value", "is", "None", ":", "self", ".", "_telemetry_client", "=", "NullTelemetryClient", "(", ")", "else", ":", "self", ".", "_telemetry_client", "=", "value" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
Dialog.resume_dialog
Method called when an instance of the dialog is being returned to from another dialog that was started by the current instance using `begin_dialog()`. If this method is NOT implemented then the dialog will be automatically ended with a call to `end_dialog()`. Any result passed from the called dialog will be passed to the current dialog's parent. :param dc: The dialog context for the current turn of conversation. :param reason: Reason why the dialog resumed. :param result: (Optional) value returned from the dialog that was called. The type of the value returned is dependent on the dialog that was called. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog.py
async def resume_dialog(self, dc, reason: DialogReason, result: object): """ Method called when an instance of the dialog is being returned to from another dialog that was started by the current instance using `begin_dialog()`. If this method is NOT implemented then the dialog will be automatically ended with a call to `end_dialog()`. Any result passed from the called dialog will be passed to the current dialog's parent. :param dc: The dialog context for the current turn of conversation. :param reason: Reason why the dialog resumed. :param result: (Optional) value returned from the dialog that was called. The type of the value returned is dependent on the dialog that was called. :return: """ # By default just end the current dialog. return await dc.EndDialog(result)
async def resume_dialog(self, dc, reason: DialogReason, result: object): """ Method called when an instance of the dialog is being returned to from another dialog that was started by the current instance using `begin_dialog()`. If this method is NOT implemented then the dialog will be automatically ended with a call to `end_dialog()`. Any result passed from the called dialog will be passed to the current dialog's parent. :param dc: The dialog context for the current turn of conversation. :param reason: Reason why the dialog resumed. :param result: (Optional) value returned from the dialog that was called. The type of the value returned is dependent on the dialog that was called. :return: """ # By default just end the current dialog. return await dc.EndDialog(result)
[ "Method", "called", "when", "an", "instance", "of", "the", "dialog", "is", "being", "returned", "to", "from", "another", "dialog", "that", "was", "started", "by", "the", "current", "instance", "using", "begin_dialog", "()", ".", "If", "this", "method", "is", "NOT", "implemented", "then", "the", "dialog", "will", "be", "automatically", "ended", "with", "a", "call", "to", "end_dialog", "()", ".", "Any", "result", "passed", "from", "the", "called", "dialog", "will", "be", "passed", "to", "the", "current", "dialog", "s", "parent", ".", ":", "param", "dc", ":", "The", "dialog", "context", "for", "the", "current", "turn", "of", "conversation", ".", ":", "param", "reason", ":", "Reason", "why", "the", "dialog", "resumed", ".", ":", "param", "result", ":", "(", "Optional", ")", "value", "returned", "from", "the", "dialog", "that", "was", "called", ".", "The", "type", "of", "the", "value", "returned", "is", "dependent", "on", "the", "dialog", "that", "was", "called", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog.py#L63-L76
[ "async", "def", "resume_dialog", "(", "self", ",", "dc", ",", "reason", ":", "DialogReason", ",", "result", ":", "object", ")", ":", "# By default just end the current dialog.", "return", "await", "dc", ".", "EndDialog", "(", "result", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
LuisApplication.from_application_endpoint
Initializes a new instance of the <see cref="LuisApplication"/> class. :param application_endpoint: LUIS application endpoint. :type application_endpoint: str :return: :rtype: LuisApplication
libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py
def from_application_endpoint(cls, application_endpoint: str): """Initializes a new instance of the <see cref="LuisApplication"/> class. :param application_endpoint: LUIS application endpoint. :type application_endpoint: str :return: :rtype: LuisApplication """ (application_id, endpoint_key, endpoint) = LuisApplication._parse( application_endpoint ) return cls(application_id, endpoint_key, endpoint)
def from_application_endpoint(cls, application_endpoint: str): """Initializes a new instance of the <see cref="LuisApplication"/> class. :param application_endpoint: LUIS application endpoint. :type application_endpoint: str :return: :rtype: LuisApplication """ (application_id, endpoint_key, endpoint) = LuisApplication._parse( application_endpoint ) return cls(application_id, endpoint_key, endpoint)
[ "Initializes", "a", "new", "instance", "of", "the", "<see", "cref", "=", "LuisApplication", "/", ">", "class", ".", ":", "param", "application_endpoint", ":", "LUIS", "application", "endpoint", ".", ":", "type", "application_endpoint", ":", "str", ":", "return", ":", ":", "rtype", ":", "LuisApplication" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py#L49-L60
[ "def", "from_application_endpoint", "(", "cls", ",", "application_endpoint", ":", "str", ")", ":", "(", "application_id", ",", "endpoint_key", ",", "endpoint", ")", "=", "LuisApplication", ".", "_parse", "(", "application_endpoint", ")", "return", "cls", "(", "application_id", ",", "endpoint_key", ",", "endpoint", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
LuisRecognizer.top_intent
Returns the name of the top scoring intent from a set of LUIS results. :param results: Result set to be searched. :type results: RecognizerResult :param default_intent: Intent name to return should a top intent be found, defaults to "None" :param default_intent: str, optional :param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the set are below this threshold then the `defaultIntent` will be returned, defaults to 0.0 :param min_score: float, optional :raises TypeError: :return: The top scoring intent name. :rtype: str
libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
def top_intent( results: RecognizerResult, default_intent: str = "None", min_score: float = 0.0 ) -> str: """Returns the name of the top scoring intent from a set of LUIS results. :param results: Result set to be searched. :type results: RecognizerResult :param default_intent: Intent name to return should a top intent be found, defaults to "None" :param default_intent: str, optional :param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the set are below this threshold then the `defaultIntent` will be returned, defaults to 0.0 :param min_score: float, optional :raises TypeError: :return: The top scoring intent name. :rtype: str """ if results is None: raise TypeError("LuisRecognizer.top_intent(): results cannot be None.") top_intent: str = None top_score: float = -1.0 if results.intents: for intent_name, intent_score in results.intents.items(): score = intent_score.score if score > top_score and score >= min_score: top_intent = intent_name top_score = score return top_intent or default_intent
def top_intent( results: RecognizerResult, default_intent: str = "None", min_score: float = 0.0 ) -> str: """Returns the name of the top scoring intent from a set of LUIS results. :param results: Result set to be searched. :type results: RecognizerResult :param default_intent: Intent name to return should a top intent be found, defaults to "None" :param default_intent: str, optional :param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the set are below this threshold then the `defaultIntent` will be returned, defaults to 0.0 :param min_score: float, optional :raises TypeError: :return: The top scoring intent name. :rtype: str """ if results is None: raise TypeError("LuisRecognizer.top_intent(): results cannot be None.") top_intent: str = None top_score: float = -1.0 if results.intents: for intent_name, intent_score in results.intents.items(): score = intent_score.score if score > top_score and score >= min_score: top_intent = intent_name top_score = score return top_intent or default_intent
[ "Returns", "the", "name", "of", "the", "top", "scoring", "intent", "from", "a", "set", "of", "LUIS", "results", ".", ":", "param", "results", ":", "Result", "set", "to", "be", "searched", ".", ":", "type", "results", ":", "RecognizerResult", ":", "param", "default_intent", ":", "Intent", "name", "to", "return", "should", "a", "top", "intent", "be", "found", "defaults", "to", "None", ":", "param", "default_intent", ":", "str", "optional", ":", "param", "min_score", ":", "Minimum", "score", "needed", "for", "an", "intent", "to", "be", "considered", "as", "a", "top", "intent", ".", "If", "all", "intents", "in", "the", "set", "are", "below", "this", "threshold", "then", "the", "defaultIntent", "will", "be", "returned", "defaults", "to", "0", ".", "0", ":", "param", "min_score", ":", "float", "optional", ":", "raises", "TypeError", ":", ":", "return", ":", "The", "top", "scoring", "intent", "name", ".", ":", "rtype", ":", "str" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py#L122-L150
[ "def", "top_intent", "(", "results", ":", "RecognizerResult", ",", "default_intent", ":", "str", "=", "\"None\"", ",", "min_score", ":", "float", "=", "0.0", ")", "->", "str", ":", "if", "results", "is", "None", ":", "raise", "TypeError", "(", "\"LuisRecognizer.top_intent(): results cannot be None.\"", ")", "top_intent", ":", "str", "=", "None", "top_score", ":", "float", "=", "-", "1.0", "if", "results", ".", "intents", ":", "for", "intent_name", ",", "intent_score", "in", "results", ".", "intents", ".", "items", "(", ")", ":", "score", "=", "intent_score", ".", "score", "if", "score", ">", "top_score", "and", "score", ">=", "min_score", ":", "top_intent", "=", "intent_name", "top_score", "=", "score", "return", "top_intent", "or", "default_intent" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
LuisRecognizer.recognize
Return results of the analysis (Suggested actions and intents). :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_metrics: Dict[str, float], optional :return: The LUIS results of the analysis of the current message text in the current turn's context activity. :rtype: RecognizerResult
libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
async def recognize( self, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, ) -> RecognizerResult: """Return results of the analysis (Suggested actions and intents). :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_metrics: Dict[str, float], optional :return: The LUIS results of the analysis of the current message text in the current turn's context activity. :rtype: RecognizerResult """ return await self._recognize_internal( turn_context, telemetry_properties, telemetry_metrics )
async def recognize( self, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, ) -> RecognizerResult: """Return results of the analysis (Suggested actions and intents). :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_metrics: Dict[str, float], optional :return: The LUIS results of the analysis of the current message text in the current turn's context activity. :rtype: RecognizerResult """ return await self._recognize_internal( turn_context, telemetry_properties, telemetry_metrics )
[ "Return", "results", "of", "the", "analysis", "(", "Suggested", "actions", "and", "intents", ")", ".", ":", "param", "turn_context", ":", "Context", "object", "containing", "information", "for", "a", "single", "turn", "of", "conversation", "with", "a", "user", ".", ":", "type", "turn_context", ":", "TurnContext", ":", "param", "telemetry_properties", ":", "Additional", "properties", "to", "be", "logged", "to", "telemetry", "with", "the", "LuisResult", "event", "defaults", "to", "None", ":", "param", "telemetry_properties", ":", "Dict", "[", "str", "str", "]", "optional", ":", "param", "telemetry_metrics", ":", "Additional", "metrics", "to", "be", "logged", "to", "telemetry", "with", "the", "LuisResult", "event", "defaults", "to", "None", ":", "param", "telemetry_metrics", ":", "Dict", "[", "str", "float", "]", "optional", ":", "return", ":", "The", "LUIS", "results", "of", "the", "analysis", "of", "the", "current", "message", "text", "in", "the", "current", "turn", "s", "context", "activity", ".", ":", "rtype", ":", "RecognizerResult" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py#L152-L172
[ "async", "def", "recognize", "(", "self", ",", "turn_context", ":", "TurnContext", ",", "telemetry_properties", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "telemetry_metrics", ":", "Dict", "[", "str", ",", "float", "]", "=", "None", ",", ")", "->", "RecognizerResult", ":", "return", "await", "self", ".", "_recognize_internal", "(", "turn_context", ",", "telemetry_properties", ",", "telemetry_metrics", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
LuisRecognizer.on_recognizer_result
Invoked prior to a LuisResult being logged. :param recognizer_result: The Luis Results for the call. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_metrics: Dict[str, float], optional
libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
def on_recognizer_result( self, recognizer_result: RecognizerResult, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, ): """Invoked prior to a LuisResult being logged. :param recognizer_result: The Luis Results for the call. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_metrics: Dict[str, float], optional """ properties = self.fill_luis_event_properties( recognizer_result, turn_context, telemetry_properties ) # Track the event self.telemetry_client.track_event( LuisTelemetryConstants.luis_result, properties, telemetry_metrics )
def on_recognizer_result( self, recognizer_result: RecognizerResult, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, ): """Invoked prior to a LuisResult being logged. :param recognizer_result: The Luis Results for the call. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_metrics: Dict[str, float], optional """ properties = self.fill_luis_event_properties( recognizer_result, turn_context, telemetry_properties ) # Track the event self.telemetry_client.track_event( LuisTelemetryConstants.luis_result, properties, telemetry_metrics )
[ "Invoked", "prior", "to", "a", "LuisResult", "being", "logged", ".", ":", "param", "recognizer_result", ":", "The", "Luis", "Results", "for", "the", "call", ".", ":", "type", "recognizer_result", ":", "RecognizerResult", ":", "param", "turn_context", ":", "Context", "object", "containing", "information", "for", "a", "single", "turn", "of", "conversation", "with", "a", "user", ".", ":", "type", "turn_context", ":", "TurnContext", ":", "param", "telemetry_properties", ":", "Additional", "properties", "to", "be", "logged", "to", "telemetry", "with", "the", "LuisResult", "event", "defaults", "to", "None", ":", "param", "telemetry_properties", ":", "Dict", "[", "str", "str", "]", "optional", ":", "param", "telemetry_metrics", ":", "Additional", "metrics", "to", "be", "logged", "to", "telemetry", "with", "the", "LuisResult", "event", "defaults", "to", "None", ":", "param", "telemetry_metrics", ":", "Dict", "[", "str", "float", "]", "optional" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py#L174-L200
[ "def", "on_recognizer_result", "(", "self", ",", "recognizer_result", ":", "RecognizerResult", ",", "turn_context", ":", "TurnContext", ",", "telemetry_properties", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "telemetry_metrics", ":", "Dict", "[", "str", ",", "float", "]", "=", "None", ",", ")", ":", "properties", "=", "self", ".", "fill_luis_event_properties", "(", "recognizer_result", ",", "turn_context", ",", "telemetry_properties", ")", "# Track the event", "self", ".", "telemetry_client", ".", "track_event", "(", "LuisTelemetryConstants", ".", "luis_result", ",", "properties", ",", "telemetry_metrics", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
LuisRecognizer.fill_luis_event_properties
Fills the event properties for LuisResult event for telemetry. These properties are logged when the recognizer is called. :param recognizer_result: Last activity sent from user. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event. :rtype: Dict[str, str]
libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py
def fill_luis_event_properties( self, recognizer_result: RecognizerResult, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, ) -> Dict[str, str]: """Fills the event properties for LuisResult event for telemetry. These properties are logged when the recognizer is called. :param recognizer_result: Last activity sent from user. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event. :rtype: Dict[str, str] """ intents = recognizer_result.intents top_two_intents = ( sorted(intents.keys(), key=lambda k: intents[k].score, reverse=True)[:2] if intents else [] ) intent_name, intent_score = LuisRecognizer._get_top_k_intent_score( top_two_intents, intents, index=0 ) intent2_name, intent2_score = LuisRecognizer._get_top_k_intent_score( top_two_intents, intents, index=1 ) # Add the intent score and conversation id properties properties: Dict[str, str] = { LuisTelemetryConstants.application_id_property: self._application.application_id, LuisTelemetryConstants.intent_property: intent_name, LuisTelemetryConstants.intent_score_property: intent_score, LuisTelemetryConstants.intent2_property: intent2_name, LuisTelemetryConstants.intent_score2_property: intent2_score, LuisTelemetryConstants.from_id_property: turn_context.activity.from_property.id, } sentiment = recognizer_result.properties.get("sentiment") if sentiment is not None and isinstance(sentiment, Dict): label = sentiment.get("label") if label is not None: properties[LuisTelemetryConstants.sentiment_label_property] = str(label) score = sentiment.get("score") if score is not None: properties[LuisTelemetryConstants.sentiment_score_property] = str(score) entities = None if recognizer_result.entities is not None: entities = json.dumps(recognizer_result.entities) properties[LuisTelemetryConstants.entities_property] = entities # Use the LogPersonalInformation flag to toggle logging PII data, text is a common example if self.log_personal_information and turn_context.activity.text: properties[ LuisTelemetryConstants.question_property ] = turn_context.activity.text # Additional Properties can override "stock" properties. if telemetry_properties is not None: for key in telemetry_properties: properties[key] = telemetry_properties[key] return properties
def fill_luis_event_properties( self, recognizer_result: RecognizerResult, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, ) -> Dict[str, str]: """Fills the event properties for LuisResult event for telemetry. These properties are logged when the recognizer is called. :param recognizer_result: Last activity sent from user. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None :param telemetry_properties: Dict[str, str], optional :return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event. :rtype: Dict[str, str] """ intents = recognizer_result.intents top_two_intents = ( sorted(intents.keys(), key=lambda k: intents[k].score, reverse=True)[:2] if intents else [] ) intent_name, intent_score = LuisRecognizer._get_top_k_intent_score( top_two_intents, intents, index=0 ) intent2_name, intent2_score = LuisRecognizer._get_top_k_intent_score( top_two_intents, intents, index=1 ) # Add the intent score and conversation id properties properties: Dict[str, str] = { LuisTelemetryConstants.application_id_property: self._application.application_id, LuisTelemetryConstants.intent_property: intent_name, LuisTelemetryConstants.intent_score_property: intent_score, LuisTelemetryConstants.intent2_property: intent2_name, LuisTelemetryConstants.intent_score2_property: intent2_score, LuisTelemetryConstants.from_id_property: turn_context.activity.from_property.id, } sentiment = recognizer_result.properties.get("sentiment") if sentiment is not None and isinstance(sentiment, Dict): label = sentiment.get("label") if label is not None: properties[LuisTelemetryConstants.sentiment_label_property] = str(label) score = sentiment.get("score") if score is not None: properties[LuisTelemetryConstants.sentiment_score_property] = str(score) entities = None if recognizer_result.entities is not None: entities = json.dumps(recognizer_result.entities) properties[LuisTelemetryConstants.entities_property] = entities # Use the LogPersonalInformation flag to toggle logging PII data, text is a common example if self.log_personal_information and turn_context.activity.text: properties[ LuisTelemetryConstants.question_property ] = turn_context.activity.text # Additional Properties can override "stock" properties. if telemetry_properties is not None: for key in telemetry_properties: properties[key] = telemetry_properties[key] return properties
[ "Fills", "the", "event", "properties", "for", "LuisResult", "event", "for", "telemetry", ".", "These", "properties", "are", "logged", "when", "the", "recognizer", "is", "called", ".", ":", "param", "recognizer_result", ":", "Last", "activity", "sent", "from", "user", ".", ":", "type", "recognizer_result", ":", "RecognizerResult", ":", "param", "turn_context", ":", "Context", "object", "containing", "information", "for", "a", "single", "turn", "of", "conversation", "with", "a", "user", ".", ":", "type", "turn_context", ":", "TurnContext", ":", "param", "telemetry_properties", ":", "Additional", "properties", "to", "be", "logged", "to", "telemetry", "with", "the", "LuisResult", "event", "defaults", "to", "None", ":", "param", "telemetry_properties", ":", "Dict", "[", "str", "str", "]", "optional", ":", "return", ":", "A", "dictionary", "that", "is", "sent", "as", "Properties", "to", "IBotTelemetryClient", ".", "TrackEvent", "method", "for", "the", "BotMessageSend", "event", ".", ":", "rtype", ":", "Dict", "[", "str", "str", "]" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py#L215-L284
[ "def", "fill_luis_event_properties", "(", "self", ",", "recognizer_result", ":", "RecognizerResult", ",", "turn_context", ":", "TurnContext", ",", "telemetry_properties", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "intents", "=", "recognizer_result", ".", "intents", "top_two_intents", "=", "(", "sorted", "(", "intents", ".", "keys", "(", ")", ",", "key", "=", "lambda", "k", ":", "intents", "[", "k", "]", ".", "score", ",", "reverse", "=", "True", ")", "[", ":", "2", "]", "if", "intents", "else", "[", "]", ")", "intent_name", ",", "intent_score", "=", "LuisRecognizer", ".", "_get_top_k_intent_score", "(", "top_two_intents", ",", "intents", ",", "index", "=", "0", ")", "intent2_name", ",", "intent2_score", "=", "LuisRecognizer", ".", "_get_top_k_intent_score", "(", "top_two_intents", ",", "intents", ",", "index", "=", "1", ")", "# Add the intent score and conversation id properties", "properties", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "LuisTelemetryConstants", ".", "application_id_property", ":", "self", ".", "_application", ".", "application_id", ",", "LuisTelemetryConstants", ".", "intent_property", ":", "intent_name", ",", "LuisTelemetryConstants", ".", "intent_score_property", ":", "intent_score", ",", "LuisTelemetryConstants", ".", "intent2_property", ":", "intent2_name", ",", "LuisTelemetryConstants", ".", "intent_score2_property", ":", "intent2_score", ",", "LuisTelemetryConstants", ".", "from_id_property", ":", "turn_context", ".", "activity", ".", "from_property", ".", "id", ",", "}", "sentiment", "=", "recognizer_result", ".", "properties", ".", "get", "(", "\"sentiment\"", ")", "if", "sentiment", "is", "not", "None", "and", "isinstance", "(", "sentiment", ",", "Dict", ")", ":", "label", "=", "sentiment", ".", "get", "(", "\"label\"", ")", "if", "label", "is", "not", "None", ":", "properties", "[", "LuisTelemetryConstants", ".", "sentiment_label_property", "]", "=", "str", "(", "label", ")", "score", "=", "sentiment", ".", "get", "(", "\"score\"", ")", "if", "score", "is", "not", "None", ":", "properties", "[", "LuisTelemetryConstants", ".", "sentiment_score_property", "]", "=", "str", "(", "score", ")", "entities", "=", "None", "if", "recognizer_result", ".", "entities", "is", "not", "None", ":", "entities", "=", "json", ".", "dumps", "(", "recognizer_result", ".", "entities", ")", "properties", "[", "LuisTelemetryConstants", ".", "entities_property", "]", "=", "entities", "# Use the LogPersonalInformation flag to toggle logging PII data, text is a common example", "if", "self", ".", "log_personal_information", "and", "turn_context", ".", "activity", ".", "text", ":", "properties", "[", "LuisTelemetryConstants", ".", "question_property", "]", "=", "turn_context", ".", "activity", ".", "text", "# Additional Properties can override \"stock\" properties.", "if", "telemetry_properties", "is", "not", "None", ":", "for", "key", "in", "telemetry_properties", ":", "properties", "[", "key", "]", "=", "telemetry_properties", "[", "key", "]", "return", "properties" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
AsyncServiceClientMixin.async_send_formdata
Send data as a multipart form-data request. We only deal with file-like objects or strings at this point. The requests is not yet streamed. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param dict content: Dictionary of the fields of the formdata. :param config: Any specific config overrides.
libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py
async def async_send_formdata(self, request, headers=None, content=None, **config): """Send data as a multipart form-data request. We only deal with file-like objects or strings at this point. The requests is not yet streamed. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param dict content: Dictionary of the fields of the formdata. :param config: Any specific config overrides. """ files = self._prepare_send_formdata(request, headers, content) return await self.async_send(request, headers, files=files, **config)
async def async_send_formdata(self, request, headers=None, content=None, **config): """Send data as a multipart form-data request. We only deal with file-like objects or strings at this point. The requests is not yet streamed. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param dict content: Dictionary of the fields of the formdata. :param config: Any specific config overrides. """ files = self._prepare_send_formdata(request, headers, content) return await self.async_send(request, headers, files=files, **config)
[ "Send", "data", "as", "a", "multipart", "form", "-", "data", "request", ".", "We", "only", "deal", "with", "file", "-", "like", "objects", "or", "strings", "at", "this", "point", ".", "The", "requests", "is", "not", "yet", "streamed", ".", ":", "param", "ClientRequest", "request", ":", "The", "request", "object", "to", "be", "sent", ".", ":", "param", "dict", "headers", ":", "Any", "headers", "to", "add", "to", "the", "request", ".", ":", "param", "dict", "content", ":", "Dictionary", "of", "the", "fields", "of", "the", "formdata", ".", ":", "param", "config", ":", "Any", "specific", "config", "overrides", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py#L46-L56
[ "async", "def", "async_send_formdata", "(", "self", ",", "request", ",", "headers", "=", "None", ",", "content", "=", "None", ",", "*", "*", "config", ")", ":", "files", "=", "self", ".", "_prepare_send_formdata", "(", "request", ",", "headers", ",", "content", ")", "return", "await", "self", ".", "async_send", "(", "request", ",", "headers", ",", "files", "=", "files", ",", "*", "*", "config", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
AsyncServiceClientMixin.async_send
Prepare and send request object according to configuration. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param content: Any body data to add to the request. :param config: Any specific config overrides
libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py
async def async_send(self, request, headers=None, content=None, **config): """Prepare and send request object according to configuration. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param content: Any body data to add to the request. :param config: Any specific config overrides """ loop = asyncio.get_event_loop() if self.config.keep_alive and self._session is None: self._session = requests.Session() try: session = self.creds.signed_session(self._session) except TypeError: # Credentials does not support session injection session = self.creds.signed_session() if self._session is not None: _LOGGER.warning( "Your credentials class does not support session injection. Performance will not be at the maximum.") kwargs = self._configure_session(session, **config) if headers: request.headers.update(headers) if not kwargs.get('files'): request.add_content(content) if request.data: kwargs['data'] = request.data kwargs['headers'].update(request.headers) response = None try: try: future = loop.run_in_executor( None, functools.partial( session.request, request.method, request.url, **kwargs ) ) return await future except (oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError) as err: error = "Token expired or is invalid. Attempting to refresh." _LOGGER.warning(error) try: session = self.creds.refresh_session() kwargs = self._configure_session(session) if request.data: kwargs['data'] = request.data kwargs['headers'].update(request.headers) future = loop.run_in_executor( None, functools.partial( session.request, request.method, request.url, **kwargs ) ) return await future except (oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError) as err: msg = "Token expired or is invalid." raise_with_traceback(TokenExpiredError, msg, err) except (requests.RequestException, oauth2.rfc6749.errors.OAuth2Error) as err: msg = "Error occurred in request." raise_with_traceback(ClientRequestError, msg, err) finally: self._close_local_session_if_necessary(response, session, kwargs['stream'])
async def async_send(self, request, headers=None, content=None, **config): """Prepare and send request object according to configuration. :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param content: Any body data to add to the request. :param config: Any specific config overrides """ loop = asyncio.get_event_loop() if self.config.keep_alive and self._session is None: self._session = requests.Session() try: session = self.creds.signed_session(self._session) except TypeError: # Credentials does not support session injection session = self.creds.signed_session() if self._session is not None: _LOGGER.warning( "Your credentials class does not support session injection. Performance will not be at the maximum.") kwargs = self._configure_session(session, **config) if headers: request.headers.update(headers) if not kwargs.get('files'): request.add_content(content) if request.data: kwargs['data'] = request.data kwargs['headers'].update(request.headers) response = None try: try: future = loop.run_in_executor( None, functools.partial( session.request, request.method, request.url, **kwargs ) ) return await future except (oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError) as err: error = "Token expired or is invalid. Attempting to refresh." _LOGGER.warning(error) try: session = self.creds.refresh_session() kwargs = self._configure_session(session) if request.data: kwargs['data'] = request.data kwargs['headers'].update(request.headers) future = loop.run_in_executor( None, functools.partial( session.request, request.method, request.url, **kwargs ) ) return await future except (oauth2.rfc6749.errors.InvalidGrantError, oauth2.rfc6749.errors.TokenExpiredError) as err: msg = "Token expired or is invalid." raise_with_traceback(TokenExpiredError, msg, err) except (requests.RequestException, oauth2.rfc6749.errors.OAuth2Error) as err: msg = "Error occurred in request." raise_with_traceback(ClientRequestError, msg, err) finally: self._close_local_session_if_necessary(response, session, kwargs['stream'])
[ "Prepare", "and", "send", "request", "object", "according", "to", "configuration", ".", ":", "param", "ClientRequest", "request", ":", "The", "request", "object", "to", "be", "sent", ".", ":", "param", "dict", "headers", ":", "Any", "headers", "to", "add", "to", "the", "request", ".", ":", "param", "content", ":", "Any", "body", "data", "to", "add", "to", "the", "request", ".", ":", "param", "config", ":", "Any", "specific", "config", "overrides" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py#L58-L133
[ "async", "def", "async_send", "(", "self", ",", "request", ",", "headers", "=", "None", ",", "content", "=", "None", ",", "*", "*", "config", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "if", "self", ".", "config", ".", "keep_alive", "and", "self", ".", "_session", "is", "None", ":", "self", ".", "_session", "=", "requests", ".", "Session", "(", ")", "try", ":", "session", "=", "self", ".", "creds", ".", "signed_session", "(", "self", ".", "_session", ")", "except", "TypeError", ":", "# Credentials does not support session injection", "session", "=", "self", ".", "creds", ".", "signed_session", "(", ")", "if", "self", ".", "_session", "is", "not", "None", ":", "_LOGGER", ".", "warning", "(", "\"Your credentials class does not support session injection. Performance will not be at the maximum.\"", ")", "kwargs", "=", "self", ".", "_configure_session", "(", "session", ",", "*", "*", "config", ")", "if", "headers", ":", "request", ".", "headers", ".", "update", "(", "headers", ")", "if", "not", "kwargs", ".", "get", "(", "'files'", ")", ":", "request", ".", "add_content", "(", "content", ")", "if", "request", ".", "data", ":", "kwargs", "[", "'data'", "]", "=", "request", ".", "data", "kwargs", "[", "'headers'", "]", ".", "update", "(", "request", ".", "headers", ")", "response", "=", "None", "try", ":", "try", ":", "future", "=", "loop", ".", "run_in_executor", "(", "None", ",", "functools", ".", "partial", "(", "session", ".", "request", ",", "request", ".", "method", ",", "request", ".", "url", ",", "*", "*", "kwargs", ")", ")", "return", "await", "future", "except", "(", "oauth2", ".", "rfc6749", ".", "errors", ".", "InvalidGrantError", ",", "oauth2", ".", "rfc6749", ".", "errors", ".", "TokenExpiredError", ")", "as", "err", ":", "error", "=", "\"Token expired or is invalid. Attempting to refresh.\"", "_LOGGER", ".", "warning", "(", "error", ")", "try", ":", "session", "=", "self", ".", "creds", ".", "refresh_session", "(", ")", "kwargs", "=", "self", ".", "_configure_session", "(", "session", ")", "if", "request", ".", "data", ":", "kwargs", "[", "'data'", "]", "=", "request", ".", "data", "kwargs", "[", "'headers'", "]", ".", "update", "(", "request", ".", "headers", ")", "future", "=", "loop", ".", "run_in_executor", "(", "None", ",", "functools", ".", "partial", "(", "session", ".", "request", ",", "request", ".", "method", ",", "request", ".", "url", ",", "*", "*", "kwargs", ")", ")", "return", "await", "future", "except", "(", "oauth2", ".", "rfc6749", ".", "errors", ".", "InvalidGrantError", ",", "oauth2", ".", "rfc6749", ".", "errors", ".", "TokenExpiredError", ")", "as", "err", ":", "msg", "=", "\"Token expired or is invalid.\"", "raise_with_traceback", "(", "TokenExpiredError", ",", "msg", ",", "err", ")", "except", "(", "requests", ".", "RequestException", ",", "oauth2", ".", "rfc6749", ".", "errors", ".", "OAuth2Error", ")", "as", "err", ":", "msg", "=", "\"Error occurred in request.\"", "raise_with_traceback", "(", "ClientRequestError", ",", "msg", ",", "err", ")", "finally", ":", "self", ".", "_close_local_session_if_necessary", "(", "response", ",", "session", ",", "kwargs", "[", "'stream'", "]", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
AsyncServiceClientMixin.stream_download_async
Async Generator for streaming request body data. :param response: The initial response :param user_callback: Custom callback for monitoring progress.
libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py
def stream_download_async(self, response, user_callback): """Async Generator for streaming request body data. :param response: The initial response :param user_callback: Custom callback for monitoring progress. """ block = self.config.connection.data_block_size return StreamDownloadGenerator(response, user_callback, block)
def stream_download_async(self, response, user_callback): """Async Generator for streaming request body data. :param response: The initial response :param user_callback: Custom callback for monitoring progress. """ block = self.config.connection.data_block_size return StreamDownloadGenerator(response, user_callback, block)
[ "Async", "Generator", "for", "streaming", "request", "body", "data", ".", ":", "param", "response", ":", "The", "initial", "response", ":", "param", "user_callback", ":", "Custom", "callback", "for", "monitoring", "progress", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py#L135-L141
[ "def", "stream_download_async", "(", "self", ",", "response", ",", "user_callback", ")", ":", "block", "=", "self", ".", "config", ".", "connection", ".", "data_block_size", "return", "StreamDownloadGenerator", "(", "response", ",", "user_callback", ",", "block", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.read
Read storeitems from storage. :param keys: :return dict:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
async def read(self, keys: List[str]) -> dict: """Read storeitems from storage. :param keys: :return dict: """ try: # check if the database and container exists and if not create if not self.__container_exists: self.__create_db_and_container() if len(keys) > 0: # create the parameters object parameters = [ {'name': f'@id{i}', 'value': f'{self.__sanitize_key(key)}'} for i, key in enumerate(keys) ] # get the names of the params parameter_sequence = ','.join(param.get('name') for param in parameters) # create the query query = { "query": f"SELECT c.id, c.realId, c.document, c._etag \ FROM c WHERE c.id in ({parameter_sequence})", "parameters": parameters } options = {'enableCrossPartitionQuery': True} # run the query and store the results as a list results = list( self.client.QueryItems( self.__container_link, query, options) ) # return a dict with a key and a StoreItem return { r.get('realId'): self.__create_si(r) for r in results } else: raise Exception('cosmosdb_storage.read(): \ provide at least one key') except TypeError as e: raise e
async def read(self, keys: List[str]) -> dict: """Read storeitems from storage. :param keys: :return dict: """ try: # check if the database and container exists and if not create if not self.__container_exists: self.__create_db_and_container() if len(keys) > 0: # create the parameters object parameters = [ {'name': f'@id{i}', 'value': f'{self.__sanitize_key(key)}'} for i, key in enumerate(keys) ] # get the names of the params parameter_sequence = ','.join(param.get('name') for param in parameters) # create the query query = { "query": f"SELECT c.id, c.realId, c.document, c._etag \ FROM c WHERE c.id in ({parameter_sequence})", "parameters": parameters } options = {'enableCrossPartitionQuery': True} # run the query and store the results as a list results = list( self.client.QueryItems( self.__container_link, query, options) ) # return a dict with a key and a StoreItem return { r.get('realId'): self.__create_si(r) for r in results } else: raise Exception('cosmosdb_storage.read(): \ provide at least one key') except TypeError as e: raise e
[ "Read", "storeitems", "from", "storage", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L58-L98
[ "async", "def", "read", "(", "self", ",", "keys", ":", "List", "[", "str", "]", ")", "->", "dict", ":", "try", ":", "# check if the database and container exists and if not create", "if", "not", "self", ".", "__container_exists", ":", "self", ".", "__create_db_and_container", "(", ")", "if", "len", "(", "keys", ")", ">", "0", ":", "# create the parameters object", "parameters", "=", "[", "{", "'name'", ":", "f'@id{i}'", ",", "'value'", ":", "f'{self.__sanitize_key(key)}'", "}", "for", "i", ",", "key", "in", "enumerate", "(", "keys", ")", "]", "# get the names of the params", "parameter_sequence", "=", "','", ".", "join", "(", "param", ".", "get", "(", "'name'", ")", "for", "param", "in", "parameters", ")", "# create the query", "query", "=", "{", "\"query\"", ":", "f\"SELECT c.id, c.realId, c.document, c._etag \\\nFROM c WHERE c.id in ({parameter_sequence})\"", ",", "\"parameters\"", ":", "parameters", "}", "options", "=", "{", "'enableCrossPartitionQuery'", ":", "True", "}", "# run the query and store the results as a list", "results", "=", "list", "(", "self", ".", "client", ".", "QueryItems", "(", "self", ".", "__container_link", ",", "query", ",", "options", ")", ")", "# return a dict with a key and a StoreItem", "return", "{", "r", ".", "get", "(", "'realId'", ")", ":", "self", ".", "__create_si", "(", "r", ")", "for", "r", "in", "results", "}", "else", ":", "raise", "Exception", "(", "'cosmosdb_storage.read(): \\\nprovide at least one key'", ")", "except", "TypeError", "as", "e", ":", "raise", "e" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.write
Save storeitems to storage. :param changes: :return:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
async def write(self, changes: Dict[str, StoreItem]): """Save storeitems to storage. :param changes: :return: """ try: # check if the database and container exists and if not create if not self.__container_exists: self.__create_db_and_container() # iterate over the changes for (key, change) in changes.items(): # store the e_tag e_tag = change.e_tag # create the new document doc = {'id': self.__sanitize_key(key), 'realId': key, 'document': self.__create_dict(change) } # the e_tag will be * for new docs so do an insert if (e_tag == '*' or not e_tag): self.client.UpsertItem( database_or_Container_link=self.__container_link, document=doc, options={'disableAutomaticIdGeneration': True} ) # if we have an etag, do opt. concurrency replace elif(len(e_tag) > 0): access_condition = {'type': 'IfMatch', 'condition': e_tag} self.client.ReplaceItem( document_link=self.__item_link( self.__sanitize_key(key)), new_document=doc, options={'accessCondition': access_condition} ) # error when there is no e_tag else: raise Exception('cosmosdb_storage.write(): etag missing') except Exception as e: raise e
async def write(self, changes: Dict[str, StoreItem]): """Save storeitems to storage. :param changes: :return: """ try: # check if the database and container exists and if not create if not self.__container_exists: self.__create_db_and_container() # iterate over the changes for (key, change) in changes.items(): # store the e_tag e_tag = change.e_tag # create the new document doc = {'id': self.__sanitize_key(key), 'realId': key, 'document': self.__create_dict(change) } # the e_tag will be * for new docs so do an insert if (e_tag == '*' or not e_tag): self.client.UpsertItem( database_or_Container_link=self.__container_link, document=doc, options={'disableAutomaticIdGeneration': True} ) # if we have an etag, do opt. concurrency replace elif(len(e_tag) > 0): access_condition = {'type': 'IfMatch', 'condition': e_tag} self.client.ReplaceItem( document_link=self.__item_link( self.__sanitize_key(key)), new_document=doc, options={'accessCondition': access_condition} ) # error when there is no e_tag else: raise Exception('cosmosdb_storage.write(): etag missing') except Exception as e: raise e
[ "Save", "storeitems", "to", "storage", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L100-L139
[ "async", "def", "write", "(", "self", ",", "changes", ":", "Dict", "[", "str", ",", "StoreItem", "]", ")", ":", "try", ":", "# check if the database and container exists and if not create", "if", "not", "self", ".", "__container_exists", ":", "self", ".", "__create_db_and_container", "(", ")", "# iterate over the changes", "for", "(", "key", ",", "change", ")", "in", "changes", ".", "items", "(", ")", ":", "# store the e_tag", "e_tag", "=", "change", ".", "e_tag", "# create the new document", "doc", "=", "{", "'id'", ":", "self", ".", "__sanitize_key", "(", "key", ")", ",", "'realId'", ":", "key", ",", "'document'", ":", "self", ".", "__create_dict", "(", "change", ")", "}", "# the e_tag will be * for new docs so do an insert", "if", "(", "e_tag", "==", "'*'", "or", "not", "e_tag", ")", ":", "self", ".", "client", ".", "UpsertItem", "(", "database_or_Container_link", "=", "self", ".", "__container_link", ",", "document", "=", "doc", ",", "options", "=", "{", "'disableAutomaticIdGeneration'", ":", "True", "}", ")", "# if we have an etag, do opt. concurrency replace", "elif", "(", "len", "(", "e_tag", ")", ">", "0", ")", ":", "access_condition", "=", "{", "'type'", ":", "'IfMatch'", ",", "'condition'", ":", "e_tag", "}", "self", ".", "client", ".", "ReplaceItem", "(", "document_link", "=", "self", ".", "__item_link", "(", "self", ".", "__sanitize_key", "(", "key", ")", ")", ",", "new_document", "=", "doc", ",", "options", "=", "{", "'accessCondition'", ":", "access_condition", "}", ")", "# error when there is no e_tag", "else", ":", "raise", "Exception", "(", "'cosmosdb_storage.write(): etag missing'", ")", "except", "Exception", "as", "e", ":", "raise", "e" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.delete
Remove storeitems from storage. :param keys: :return:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
async def delete(self, keys: List[str]): """Remove storeitems from storage. :param keys: :return: """ try: # check if the database and container exists and if not create if not self.__container_exists: self.__create_db_and_container() # call the function for each key for k in keys: self.client.DeleteItem( document_link=self.__item_link(self.__sanitize_key(k))) # print(res) except cosmos_errors.HTTPFailure as h: # print(h.status_code) if h.status_code != 404: raise h except TypeError as e: raise e
async def delete(self, keys: List[str]): """Remove storeitems from storage. :param keys: :return: """ try: # check if the database and container exists and if not create if not self.__container_exists: self.__create_db_and_container() # call the function for each key for k in keys: self.client.DeleteItem( document_link=self.__item_link(self.__sanitize_key(k))) # print(res) except cosmos_errors.HTTPFailure as h: # print(h.status_code) if h.status_code != 404: raise h except TypeError as e: raise e
[ "Remove", "storeitems", "from", "storage", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L141-L161
[ "async", "def", "delete", "(", "self", ",", "keys", ":", "List", "[", "str", "]", ")", ":", "try", ":", "# check if the database and container exists and if not create", "if", "not", "self", ".", "__container_exists", ":", "self", ".", "__create_db_and_container", "(", ")", "# call the function for each key", "for", "k", "in", "keys", ":", "self", ".", "client", ".", "DeleteItem", "(", "document_link", "=", "self", ".", "__item_link", "(", "self", ".", "__sanitize_key", "(", "k", ")", ")", ")", "# print(res)", "except", "cosmos_errors", ".", "HTTPFailure", "as", "h", ":", "# print(h.status_code)", "if", "h", ".", "status_code", "!=", "404", ":", "raise", "h", "except", "TypeError", "as", "e", ":", "raise", "e" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.__create_si
Create a StoreItem from a result out of CosmosDB. :param result: :return StoreItem:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
def __create_si(self, result) -> StoreItem: """Create a StoreItem from a result out of CosmosDB. :param result: :return StoreItem: """ # get the document item from the result and turn into a dict doc = result.get('document') # readd the e_tag from Cosmos doc['e_tag'] = result.get('_etag') # create and return the StoreItem return StoreItem(**doc)
def __create_si(self, result) -> StoreItem: """Create a StoreItem from a result out of CosmosDB. :param result: :return StoreItem: """ # get the document item from the result and turn into a dict doc = result.get('document') # readd the e_tag from Cosmos doc['e_tag'] = result.get('_etag') # create and return the StoreItem return StoreItem(**doc)
[ "Create", "a", "StoreItem", "from", "a", "result", "out", "of", "CosmosDB", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L163-L174
[ "def", "__create_si", "(", "self", ",", "result", ")", "->", "StoreItem", ":", "# get the document item from the result and turn into a dict", "doc", "=", "result", ".", "get", "(", "'document'", ")", "# readd the e_tag from Cosmos", "doc", "[", "'e_tag'", "]", "=", "result", ".", "get", "(", "'_etag'", ")", "# create and return the StoreItem", "return", "StoreItem", "(", "*", "*", "doc", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.__create_dict
Return the dict of a StoreItem. This eliminates non_magic attributes and the e_tag. :param si: :return dict:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
def __create_dict(self, si: StoreItem) -> Dict: """Return the dict of a StoreItem. This eliminates non_magic attributes and the e_tag. :param si: :return dict: """ # read the content non_magic_attr = ([attr for attr in dir(si) if not attr.startswith('_') or attr.__eq__('e_tag')]) # loop through attributes and write and return a dict return ({attr: getattr(si, attr) for attr in non_magic_attr})
def __create_dict(self, si: StoreItem) -> Dict: """Return the dict of a StoreItem. This eliminates non_magic attributes and the e_tag. :param si: :return dict: """ # read the content non_magic_attr = ([attr for attr in dir(si) if not attr.startswith('_') or attr.__eq__('e_tag')]) # loop through attributes and write and return a dict return ({attr: getattr(si, attr) for attr in non_magic_attr})
[ "Return", "the", "dict", "of", "a", "StoreItem", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L176-L189
[ "def", "__create_dict", "(", "self", ",", "si", ":", "StoreItem", ")", "->", "Dict", ":", "# read the content", "non_magic_attr", "=", "(", "[", "attr", "for", "attr", "in", "dir", "(", "si", ")", "if", "not", "attr", ".", "startswith", "(", "'_'", ")", "or", "attr", ".", "__eq__", "(", "'e_tag'", ")", "]", ")", "# loop through attributes and write and return a dict", "return", "(", "{", "attr", ":", "getattr", "(", "si", ",", "attr", ")", "for", "attr", "in", "non_magic_attr", "}", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.__sanitize_key
Return the sanitized key. Replace characters that are not allowed in keys in Cosmos. :param key: :return str:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
def __sanitize_key(self, key) -> str: """Return the sanitized key. Replace characters that are not allowed in keys in Cosmos. :param key: :return str: """ # forbidden characters bad_chars = ['\\', '?', '/', '#', '\t', '\n', '\r'] # replace those with with '*' and the # Unicode code point of the character and return the new string return ''.join( map( lambda x: '*'+str(ord(x)) if x in bad_chars else x, key ) )
def __sanitize_key(self, key) -> str: """Return the sanitized key. Replace characters that are not allowed in keys in Cosmos. :param key: :return str: """ # forbidden characters bad_chars = ['\\', '?', '/', '#', '\t', '\n', '\r'] # replace those with with '*' and the # Unicode code point of the character and return the new string return ''.join( map( lambda x: '*'+str(ord(x)) if x in bad_chars else x, key ) )
[ "Return", "the", "sanitized", "key", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L191-L207
[ "def", "__sanitize_key", "(", "self", ",", "key", ")", "->", "str", ":", "# forbidden characters", "bad_chars", "=", "[", "'\\\\'", ",", "'?'", ",", "'/'", ",", "'#'", ",", "'\\t'", ",", "'\\n'", ",", "'\\r'", "]", "# replace those with with '*' and the", "# Unicode code point of the character and return the new string", "return", "''", ".", "join", "(", "map", "(", "lambda", "x", ":", "'*'", "+", "str", "(", "ord", "(", "x", ")", ")", "if", "x", "in", "bad_chars", "else", "x", ",", "key", ")", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.__create_db_and_container
Call the get or create methods.
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
def __create_db_and_container(self): """Call the get or create methods.""" db_id = self.config.database container_name = self.config.container self.db = self.__get_or_create_database(self.client, db_id) self.container = self.__get_or_create_container( self.client, container_name )
def __create_db_and_container(self): """Call the get or create methods.""" db_id = self.config.database container_name = self.config.container self.db = self.__get_or_create_database(self.client, db_id) self.container = self.__get_or_create_container( self.client, container_name )
[ "Call", "the", "get", "or", "create", "methods", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L242-L249
[ "def", "__create_db_and_container", "(", "self", ")", ":", "db_id", "=", "self", ".", "config", ".", "database", "container_name", "=", "self", ".", "config", ".", "container", "self", ".", "db", "=", "self", ".", "__get_or_create_database", "(", "self", ".", "client", ",", "db_id", ")", "self", ".", "container", "=", "self", ".", "__get_or_create_container", "(", "self", ".", "client", ",", "container_name", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.__get_or_create_database
Return the database link. Check if the database exists or create the db. :param doc_client: :param id: :return str:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
def __get_or_create_database(self, doc_client, id) -> str: """Return the database link. Check if the database exists or create the db. :param doc_client: :param id: :return str: """ # query CosmosDB for a database with that name/id dbs = list(doc_client.QueryDatabases({ "query": "SELECT * FROM r WHERE r.id=@id", "parameters": [ {"name": "@id", "value": id} ] })) # if there are results, return the first (db names are unique) if len(dbs) > 0: return dbs[0]['id'] else: # create the database if it didn't exist res = doc_client.CreateDatabase({'id': id}) return res['id']
def __get_or_create_database(self, doc_client, id) -> str: """Return the database link. Check if the database exists or create the db. :param doc_client: :param id: :return str: """ # query CosmosDB for a database with that name/id dbs = list(doc_client.QueryDatabases({ "query": "SELECT * FROM r WHERE r.id=@id", "parameters": [ {"name": "@id", "value": id} ] })) # if there are results, return the first (db names are unique) if len(dbs) > 0: return dbs[0]['id'] else: # create the database if it didn't exist res = doc_client.CreateDatabase({'id': id}) return res['id']
[ "Return", "the", "database", "link", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L251-L273
[ "def", "__get_or_create_database", "(", "self", ",", "doc_client", ",", "id", ")", "->", "str", ":", "# query CosmosDB for a database with that name/id", "dbs", "=", "list", "(", "doc_client", ".", "QueryDatabases", "(", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.id=@id\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@id\"", ",", "\"value\"", ":", "id", "}", "]", "}", ")", ")", "# if there are results, return the first (db names are unique)", "if", "len", "(", "dbs", ")", ">", "0", ":", "return", "dbs", "[", "0", "]", "[", "'id'", "]", "else", ":", "# create the database if it didn't exist", "res", "=", "doc_client", ".", "CreateDatabase", "(", "{", "'id'", ":", "id", "}", ")", "return", "res", "[", "'id'", "]" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CosmosDbStorage.__get_or_create_container
Return the container link. Check if the container exists or create the container. :param doc_client: :param container: :return str:
libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py
def __get_or_create_container(self, doc_client, container) -> str: """Return the container link. Check if the container exists or create the container. :param doc_client: :param container: :return str: """ # query CosmosDB for a container in the database with that name containers = list(doc_client.QueryContainers( self.__database_link, { "query": "SELECT * FROM r WHERE r.id=@id", "parameters": [ {"name": "@id", "value": container} ] } )) # if there are results, return the first (container names are unique) if len(containers) > 0: return containers[0]['id'] else: # Create a container if it didn't exist res = doc_client.CreateContainer( self.__database_link, {'id': container}) return res['id']
def __get_or_create_container(self, doc_client, container) -> str: """Return the container link. Check if the container exists or create the container. :param doc_client: :param container: :return str: """ # query CosmosDB for a container in the database with that name containers = list(doc_client.QueryContainers( self.__database_link, { "query": "SELECT * FROM r WHERE r.id=@id", "parameters": [ {"name": "@id", "value": container} ] } )) # if there are results, return the first (container names are unique) if len(containers) > 0: return containers[0]['id'] else: # Create a container if it didn't exist res = doc_client.CreateContainer( self.__database_link, {'id': container}) return res['id']
[ "Return", "the", "container", "link", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py#L275-L301
[ "def", "__get_or_create_container", "(", "self", ",", "doc_client", ",", "container", ")", "->", "str", ":", "# query CosmosDB for a container in the database with that name", "containers", "=", "list", "(", "doc_client", ".", "QueryContainers", "(", "self", ".", "__database_link", ",", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.id=@id\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@id\"", ",", "\"value\"", ":", "container", "}", "]", "}", ")", ")", "# if there are results, return the first (container names are unique)", "if", "len", "(", "containers", ")", ">", "0", ":", "return", "containers", "[", "0", "]", "[", "'id'", "]", "else", ":", "# Create a container if it didn't exist", "res", "=", "doc_client", ".", "CreateContainer", "(", "self", ".", "__database_link", ",", "{", "'id'", ":", "container", "}", ")", "return", "res", "[", "'id'", "]" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
QnAMaker.fill_qna_event
Fills the event properties and metrics for the QnaMessage event for telemetry. :return: A tuple of event data properties and metrics that will be sent to the BotTelemetryClient.track_event() method for the QnAMessage event. The properties and metrics returned the standard properties logged with any properties passed from the get_answers() method. :rtype: EventData
libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py
def fill_qna_event( self, query_results: [QueryResult], turn_context: TurnContext, telemetry_properties: Dict[str,str] = None, telemetry_metrics: Dict[str,float] = None ) -> EventData: """ Fills the event properties and metrics for the QnaMessage event for telemetry. :return: A tuple of event data properties and metrics that will be sent to the BotTelemetryClient.track_event() method for the QnAMessage event. The properties and metrics returned the standard properties logged with any properties passed from the get_answers() method. :rtype: EventData """ properties: Dict[str,str] = dict() metrics: Dict[str, float] = dict() properties[QnATelemetryConstants.knowledge_base_id_property] = self._endpoint.knowledge_base_id text: str = turn_context.activity.text userName: str = turn_context.activity.from_property.name # Use the LogPersonalInformation flag to toggle logging PII data; text and username are common examples. if self.log_personal_information: if text: properties[QnATelemetryConstants.question_property] = text if userName: properties[QnATelemetryConstants.username_property] = userName # Fill in Qna Results (found or not). if len(query_results) > 0: query_result = query_results[0] result_properties = { QnATelemetryConstants.matched_question_property: json.dumps(query_result.questions), QnATelemetryConstants.question_id_property: str(query_result.id), QnATelemetryConstants.answer_property: query_result.answer, QnATelemetryConstants.score_metric: query_result.score, QnATelemetryConstants.article_found_property: 'true' } properties.update(result_properties) else: no_match_properties = { QnATelemetryConstants.matched_question_property : 'No Qna Question matched', QnATelemetryConstants.question_id_property : 'No Qna Question Id matched', QnATelemetryConstants.answer_property : 'No Qna Answer matched', QnATelemetryConstants.article_found_property : 'false' } properties.update(no_match_properties) # Additional Properties can override "stock" properties. if telemetry_properties: properties.update(telemetry_properties) # Additional Metrics can override "stock" metrics. if telemetry_metrics: metrics.update(telemetry_metrics) return EventData(properties=properties, metrics=metrics)
def fill_qna_event( self, query_results: [QueryResult], turn_context: TurnContext, telemetry_properties: Dict[str,str] = None, telemetry_metrics: Dict[str,float] = None ) -> EventData: """ Fills the event properties and metrics for the QnaMessage event for telemetry. :return: A tuple of event data properties and metrics that will be sent to the BotTelemetryClient.track_event() method for the QnAMessage event. The properties and metrics returned the standard properties logged with any properties passed from the get_answers() method. :rtype: EventData """ properties: Dict[str,str] = dict() metrics: Dict[str, float] = dict() properties[QnATelemetryConstants.knowledge_base_id_property] = self._endpoint.knowledge_base_id text: str = turn_context.activity.text userName: str = turn_context.activity.from_property.name # Use the LogPersonalInformation flag to toggle logging PII data; text and username are common examples. if self.log_personal_information: if text: properties[QnATelemetryConstants.question_property] = text if userName: properties[QnATelemetryConstants.username_property] = userName # Fill in Qna Results (found or not). if len(query_results) > 0: query_result = query_results[0] result_properties = { QnATelemetryConstants.matched_question_property: json.dumps(query_result.questions), QnATelemetryConstants.question_id_property: str(query_result.id), QnATelemetryConstants.answer_property: query_result.answer, QnATelemetryConstants.score_metric: query_result.score, QnATelemetryConstants.article_found_property: 'true' } properties.update(result_properties) else: no_match_properties = { QnATelemetryConstants.matched_question_property : 'No Qna Question matched', QnATelemetryConstants.question_id_property : 'No Qna Question Id matched', QnATelemetryConstants.answer_property : 'No Qna Answer matched', QnATelemetryConstants.article_found_property : 'false' } properties.update(no_match_properties) # Additional Properties can override "stock" properties. if telemetry_properties: properties.update(telemetry_properties) # Additional Metrics can override "stock" metrics. if telemetry_metrics: metrics.update(telemetry_metrics) return EventData(properties=properties, metrics=metrics)
[ "Fills", "the", "event", "properties", "and", "metrics", "for", "the", "QnaMessage", "event", "for", "telemetry", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py#L110-L172
[ "def", "fill_qna_event", "(", "self", ",", "query_results", ":", "[", "QueryResult", "]", ",", "turn_context", ":", "TurnContext", ",", "telemetry_properties", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "telemetry_metrics", ":", "Dict", "[", "str", ",", "float", "]", "=", "None", ")", "->", "EventData", ":", "properties", ":", "Dict", "[", "str", ",", "str", "]", "=", "dict", "(", ")", "metrics", ":", "Dict", "[", "str", ",", "float", "]", "=", "dict", "(", ")", "properties", "[", "QnATelemetryConstants", ".", "knowledge_base_id_property", "]", "=", "self", ".", "_endpoint", ".", "knowledge_base_id", "text", ":", "str", "=", "turn_context", ".", "activity", ".", "text", "userName", ":", "str", "=", "turn_context", ".", "activity", ".", "from_property", ".", "name", "# Use the LogPersonalInformation flag to toggle logging PII data; text and username are common examples.", "if", "self", ".", "log_personal_information", ":", "if", "text", ":", "properties", "[", "QnATelemetryConstants", ".", "question_property", "]", "=", "text", "if", "userName", ":", "properties", "[", "QnATelemetryConstants", ".", "username_property", "]", "=", "userName", "# Fill in Qna Results (found or not).", "if", "len", "(", "query_results", ")", ">", "0", ":", "query_result", "=", "query_results", "[", "0", "]", "result_properties", "=", "{", "QnATelemetryConstants", ".", "matched_question_property", ":", "json", ".", "dumps", "(", "query_result", ".", "questions", ")", ",", "QnATelemetryConstants", ".", "question_id_property", ":", "str", "(", "query_result", ".", "id", ")", ",", "QnATelemetryConstants", ".", "answer_property", ":", "query_result", ".", "answer", ",", "QnATelemetryConstants", ".", "score_metric", ":", "query_result", ".", "score", ",", "QnATelemetryConstants", ".", "article_found_property", ":", "'true'", "}", "properties", ".", "update", "(", "result_properties", ")", "else", ":", "no_match_properties", "=", "{", "QnATelemetryConstants", ".", "matched_question_property", ":", "'No Qna Question matched'", ",", "QnATelemetryConstants", ".", "question_id_property", ":", "'No Qna Question Id matched'", ",", "QnATelemetryConstants", ".", "answer_property", ":", "'No Qna Answer matched'", ",", "QnATelemetryConstants", ".", "article_found_property", ":", "'false'", "}", "properties", ".", "update", "(", "no_match_properties", ")", "# Additional Properties can override \"stock\" properties.", "if", "telemetry_properties", ":", "properties", ".", "update", "(", "telemetry_properties", ")", "# Additional Metrics can override \"stock\" metrics.", "if", "telemetry_metrics", ":", "metrics", ".", "update", "(", "telemetry_metrics", ")", "return", "EventData", "(", "properties", "=", "properties", ",", "metrics", "=", "metrics", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
QnAMaker.get_answers
Generates answers from the knowledge base. :return: A list of answers for the user's query, sorted in decreasing order of ranking score. :rtype: [QueryResult]
libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py
async def get_answers( self, context: TurnContext, options: QnAMakerOptions = None, telemetry_properties: Dict[str,str] = None, telemetry_metrics: Dict[str,int] = None ) -> [QueryResult]: """ Generates answers from the knowledge base. :return: A list of answers for the user's query, sorted in decreasing order of ranking score. :rtype: [QueryResult] """ hydrated_options = self._hydrate_options(options) self._validate_options(hydrated_options) result = self._query_qna_service(context.activity, hydrated_options) await self._emit_trace_info(context, result, hydrated_options) return result
async def get_answers( self, context: TurnContext, options: QnAMakerOptions = None, telemetry_properties: Dict[str,str] = None, telemetry_metrics: Dict[str,int] = None ) -> [QueryResult]: """ Generates answers from the knowledge base. :return: A list of answers for the user's query, sorted in decreasing order of ranking score. :rtype: [QueryResult] """ hydrated_options = self._hydrate_options(options) self._validate_options(hydrated_options) result = self._query_qna_service(context.activity, hydrated_options) await self._emit_trace_info(context, result, hydrated_options) return result
[ "Generates", "answers", "from", "the", "knowledge", "base", ".", ":", "return", ":", "A", "list", "of", "answers", "for", "the", "user", "s", "query", "sorted", "in", "decreasing", "order", "of", "ranking", "score", ".", ":", "rtype", ":", "[", "QueryResult", "]" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py#L174-L197
[ "async", "def", "get_answers", "(", "self", ",", "context", ":", "TurnContext", ",", "options", ":", "QnAMakerOptions", "=", "None", ",", "telemetry_properties", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "telemetry_metrics", ":", "Dict", "[", "str", ",", "int", "]", "=", "None", ")", "->", "[", "QueryResult", "]", ":", "hydrated_options", "=", "self", ".", "_hydrate_options", "(", "options", ")", "self", ".", "_validate_options", "(", "hydrated_options", ")", "result", "=", "self", ".", "_query_qna_service", "(", "context", ".", "activity", ",", "hydrated_options", ")", "await", "self", ".", "_emit_trace_info", "(", "context", ",", "result", ",", "hydrated_options", ")", "return", "result" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
QnAMaker._hydrate_options
Combines QnAMakerOptions passed into the QnAMaker constructor with the options passed as arguments into get_answers(). :return: QnAMakerOptions with options passed into constructor overwritten by new options passed into get_answers() :rtype: QnAMakerOptions
libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py
def _hydrate_options(self, query_options: QnAMakerOptions) -> QnAMakerOptions: """ Combines QnAMakerOptions passed into the QnAMaker constructor with the options passed as arguments into get_answers(). :return: QnAMakerOptions with options passed into constructor overwritten by new options passed into get_answers() :rtype: QnAMakerOptions """ hydrated_options = copy(self._options) if query_options: if ( query_options.score_threshold != hydrated_options.score_threshold and query_options.score_threshold ): hydrated_options.score_threshold = query_options.score_threshold if (query_options.top != hydrated_options.top and query_options.top != 0): hydrated_options.top = query_options.top if (len(query_options.strict_filters) > 0): hydrated_options.strict_filters = query_options.strict_filters return hydrated_options
def _hydrate_options(self, query_options: QnAMakerOptions) -> QnAMakerOptions: """ Combines QnAMakerOptions passed into the QnAMaker constructor with the options passed as arguments into get_answers(). :return: QnAMakerOptions with options passed into constructor overwritten by new options passed into get_answers() :rtype: QnAMakerOptions """ hydrated_options = copy(self._options) if query_options: if ( query_options.score_threshold != hydrated_options.score_threshold and query_options.score_threshold ): hydrated_options.score_threshold = query_options.score_threshold if (query_options.top != hydrated_options.top and query_options.top != 0): hydrated_options.top = query_options.top if (len(query_options.strict_filters) > 0): hydrated_options.strict_filters = query_options.strict_filters return hydrated_options
[ "Combines", "QnAMakerOptions", "passed", "into", "the", "QnAMaker", "constructor", "with", "the", "options", "passed", "as", "arguments", "into", "get_answers", "()", ".", ":", "return", ":", "QnAMakerOptions", "with", "options", "passed", "into", "constructor", "overwritten", "by", "new", "options", "passed", "into", "get_answers", "()" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py#L215-L239
[ "def", "_hydrate_options", "(", "self", ",", "query_options", ":", "QnAMakerOptions", ")", "->", "QnAMakerOptions", ":", "hydrated_options", "=", "copy", "(", "self", ".", "_options", ")", "if", "query_options", ":", "if", "(", "query_options", ".", "score_threshold", "!=", "hydrated_options", ".", "score_threshold", "and", "query_options", ".", "score_threshold", ")", ":", "hydrated_options", ".", "score_threshold", "=", "query_options", ".", "score_threshold", "if", "(", "query_options", ".", "top", "!=", "hydrated_options", ".", "top", "and", "query_options", ".", "top", "!=", "0", ")", ":", "hydrated_options", ".", "top", "=", "query_options", ".", "top", "if", "(", "len", "(", "query_options", ".", "strict_filters", ")", ">", "0", ")", ":", "hydrated_options", ".", "strict_filters", "=", "query_options", ".", "strict_filters", "return", "hydrated_options" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.copy_to
Called when this TurnContext instance is passed into the constructor of a new TurnContext instance. Can be overridden in derived classes. :param context: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
def copy_to(self, context: 'TurnContext') -> None: """ Called when this TurnContext instance is passed into the constructor of a new TurnContext instance. Can be overridden in derived classes. :param context: :return: """ for attribute in ['adapter', 'activity', '_responded', '_services', '_on_send_activities', '_on_update_activity', '_on_delete_activity']: setattr(context, attribute, getattr(self, attribute))
def copy_to(self, context: 'TurnContext') -> None: """ Called when this TurnContext instance is passed into the constructor of a new TurnContext instance. Can be overridden in derived classes. :param context: :return: """ for attribute in ['adapter', 'activity', '_responded', '_services', '_on_send_activities', '_on_update_activity', '_on_delete_activity']: setattr(context, attribute, getattr(self, attribute))
[ "Called", "when", "this", "TurnContext", "instance", "is", "passed", "into", "the", "constructor", "of", "a", "new", "TurnContext", "instance", ".", "Can", "be", "overridden", "in", "derived", "classes", ".", ":", "param", "context", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L48-L57
[ "def", "copy_to", "(", "self", ",", "context", ":", "'TurnContext'", ")", "->", "None", ":", "for", "attribute", "in", "[", "'adapter'", ",", "'activity'", ",", "'_responded'", ",", "'_services'", ",", "'_on_send_activities'", ",", "'_on_update_activity'", ",", "'_on_delete_activity'", "]", ":", "setattr", "(", "context", ",", "attribute", ",", "getattr", "(", "self", ",", "attribute", ")", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.activity
Used to set TurnContext._activity when a context object is created. Only takes instances of Activities. :param value: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
def activity(self, value): """ Used to set TurnContext._activity when a context object is created. Only takes instances of Activities. :param value: :return: """ if not isinstance(value, Activity): raise TypeError('TurnContext: cannot set `activity` to a type other than Activity.') else: self._activity = value
def activity(self, value): """ Used to set TurnContext._activity when a context object is created. Only takes instances of Activities. :param value: :return: """ if not isinstance(value, Activity): raise TypeError('TurnContext: cannot set `activity` to a type other than Activity.') else: self._activity = value
[ "Used", "to", "set", "TurnContext", ".", "_activity", "when", "a", "context", "object", "is", "created", ".", "Only", "takes", "instances", "of", "Activities", ".", ":", "param", "value", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L68-L77
[ "def", "activity", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Activity", ")", ":", "raise", "TypeError", "(", "'TurnContext: cannot set `activity` to a type other than Activity.'", ")", "else", ":", "self", ".", "_activity", "=", "value" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.has
Returns True is set() has been called for a key. The cached value may be of type 'None'. :param key: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
def has(self, key: str) -> bool: """ Returns True is set() has been called for a key. The cached value may be of type 'None'. :param key: :return: """ if key in self._services: return True return False
def has(self, key: str) -> bool: """ Returns True is set() has been called for a key. The cached value may be of type 'None'. :param key: :return: """ if key in self._services: return True return False
[ "Returns", "True", "is", "set", "()", "has", "been", "called", "for", "a", "key", ".", "The", "cached", "value", "may", "be", "of", "type", "None", ".", ":", "param", "key", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L110-L118
[ "def", "has", "(", "self", ",", "key", ":", "str", ")", "->", "bool", ":", "if", "key", "in", "self", ".", "_services", ":", "return", "True", "return", "False" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.set
Caches a value for the lifetime of the current turn. :param key: :param value: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
def set(self, key: str, value: object) -> None: """ Caches a value for the lifetime of the current turn. :param key: :param value: :return: """ if not key or not isinstance(key, str): raise KeyError('"key" must be a valid string.') self._services[key] = value
def set(self, key: str, value: object) -> None: """ Caches a value for the lifetime of the current turn. :param key: :param value: :return: """ if not key or not isinstance(key, str): raise KeyError('"key" must be a valid string.') self._services[key] = value
[ "Caches", "a", "value", "for", "the", "lifetime", "of", "the", "current", "turn", ".", ":", "param", "key", ":", ":", "param", "value", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L120-L130
[ "def", "set", "(", "self", ",", "key", ":", "str", ",", "value", ":", "object", ")", "->", "None", ":", "if", "not", "key", "or", "not", "isinstance", "(", "key", ",", "str", ")", ":", "raise", "KeyError", "(", "'\"key\" must be a valid string.'", ")", "self", ".", "_services", "[", "key", "]", "=", "value" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.send_activity
Sends a single activity or message to the user. :param activity_or_text: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
async def send_activity(self, *activity_or_text: Union[Activity, str]) -> ResourceResponse: """ Sends a single activity or message to the user. :param activity_or_text: :return: """ reference = TurnContext.get_conversation_reference(self.activity) output = [TurnContext.apply_conversation_reference( Activity(text=a, type='message') if isinstance(a, str) else a, reference) for a in activity_or_text] for activity in output: activity.input_hint = 'acceptingInput' async def callback(context: 'TurnContext', output): responses = await context.adapter.send_activities(context, output) context._responded = True return responses await self._emit(self._on_send_activities, output, callback(self, output))
async def send_activity(self, *activity_or_text: Union[Activity, str]) -> ResourceResponse: """ Sends a single activity or message to the user. :param activity_or_text: :return: """ reference = TurnContext.get_conversation_reference(self.activity) output = [TurnContext.apply_conversation_reference( Activity(text=a, type='message') if isinstance(a, str) else a, reference) for a in activity_or_text] for activity in output: activity.input_hint = 'acceptingInput' async def callback(context: 'TurnContext', output): responses = await context.adapter.send_activities(context, output) context._responded = True return responses await self._emit(self._on_send_activities, output, callback(self, output))
[ "Sends", "a", "single", "activity", "or", "message", "to", "the", "user", ".", ":", "param", "activity_or_text", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L132-L151
[ "async", "def", "send_activity", "(", "self", ",", "*", "activity_or_text", ":", "Union", "[", "Activity", ",", "str", "]", ")", "->", "ResourceResponse", ":", "reference", "=", "TurnContext", ".", "get_conversation_reference", "(", "self", ".", "activity", ")", "output", "=", "[", "TurnContext", ".", "apply_conversation_reference", "(", "Activity", "(", "text", "=", "a", ",", "type", "=", "'message'", ")", "if", "isinstance", "(", "a", ",", "str", ")", "else", "a", ",", "reference", ")", "for", "a", "in", "activity_or_text", "]", "for", "activity", "in", "output", ":", "activity", ".", "input_hint", "=", "'acceptingInput'", "async", "def", "callback", "(", "context", ":", "'TurnContext'", ",", "output", ")", ":", "responses", "=", "await", "context", ".", "adapter", ".", "send_activities", "(", "context", ",", "output", ")", "context", ".", "_responded", "=", "True", "return", "responses", "await", "self", ".", "_emit", "(", "self", ".", "_on_send_activities", ",", "output", ",", "callback", "(", "self", ",", "output", ")", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.update_activity
Replaces an existing activity. :param activity: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
async def update_activity(self, activity: Activity): """ Replaces an existing activity. :param activity: :return: """ return await self._emit(self._on_update_activity, activity, self.adapter.update_activity(self, activity))
async def update_activity(self, activity: Activity): """ Replaces an existing activity. :param activity: :return: """ return await self._emit(self._on_update_activity, activity, self.adapter.update_activity(self, activity))
[ "Replaces", "an", "existing", "activity", ".", ":", "param", "activity", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L153-L159
[ "async", "def", "update_activity", "(", "self", ",", "activity", ":", "Activity", ")", ":", "return", "await", "self", ".", "_emit", "(", "self", ".", "_on_update_activity", ",", "activity", ",", "self", ".", "adapter", ".", "update_activity", "(", "self", ",", "activity", ")", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.delete_activity
Deletes an existing activity. :param id_or_reference: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
async def delete_activity(self, id_or_reference: Union[str, ConversationReference]): """ Deletes an existing activity. :param id_or_reference: :return: """ if type(id_or_reference) == str: reference = TurnContext.get_conversation_reference(self.activity) reference.activity_id = id_or_reference else: reference = id_or_reference return await self._emit(self._on_delete_activity, reference, self.adapter.delete_activity(self, reference))
async def delete_activity(self, id_or_reference: Union[str, ConversationReference]): """ Deletes an existing activity. :param id_or_reference: :return: """ if type(id_or_reference) == str: reference = TurnContext.get_conversation_reference(self.activity) reference.activity_id = id_or_reference else: reference = id_or_reference return await self._emit(self._on_delete_activity, reference, self.adapter.delete_activity(self, reference))
[ "Deletes", "an", "existing", "activity", ".", ":", "param", "id_or_reference", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L161-L172
[ "async", "def", "delete_activity", "(", "self", ",", "id_or_reference", ":", "Union", "[", "str", ",", "ConversationReference", "]", ")", ":", "if", "type", "(", "id_or_reference", ")", "==", "str", ":", "reference", "=", "TurnContext", ".", "get_conversation_reference", "(", "self", ".", "activity", ")", "reference", ".", "activity_id", "=", "id_or_reference", "else", ":", "reference", "=", "id_or_reference", "return", "await", "self", ".", "_emit", "(", "self", ".", "_on_delete_activity", ",", "reference", ",", "self", ".", "adapter", ".", "delete_activity", "(", "self", ",", "reference", ")", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.get_conversation_reference
Returns the conversation reference for an activity. This can be saved as a plain old JSON object and then later used to message the user proactively. Usage Example: reference = TurnContext.get_conversation_reference(context.request) :param activity: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
def get_conversation_reference(activity: Activity) -> ConversationReference: """ Returns the conversation reference for an activity. This can be saved as a plain old JSON object and then later used to message the user proactively. Usage Example: reference = TurnContext.get_conversation_reference(context.request) :param activity: :return: """ return ConversationReference(activity_id=activity.id, user=copy(activity.from_property), bot=copy(activity.recipient), conversation=copy(activity.conversation), channel_id=activity.channel_id, service_url=activity.service_url)
def get_conversation_reference(activity: Activity) -> ConversationReference: """ Returns the conversation reference for an activity. This can be saved as a plain old JSON object and then later used to message the user proactively. Usage Example: reference = TurnContext.get_conversation_reference(context.request) :param activity: :return: """ return ConversationReference(activity_id=activity.id, user=copy(activity.from_property), bot=copy(activity.recipient), conversation=copy(activity.conversation), channel_id=activity.channel_id, service_url=activity.service_url)
[ "Returns", "the", "conversation", "reference", "for", "an", "activity", ".", "This", "can", "be", "saved", "as", "a", "plain", "old", "JSON", "object", "and", "then", "later", "used", "to", "message", "the", "user", "proactively", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L219-L234
[ "def", "get_conversation_reference", "(", "activity", ":", "Activity", ")", "->", "ConversationReference", ":", "return", "ConversationReference", "(", "activity_id", "=", "activity", ".", "id", ",", "user", "=", "copy", "(", "activity", ".", "from_property", ")", ",", "bot", "=", "copy", "(", "activity", ".", "recipient", ")", ",", "conversation", "=", "copy", "(", "activity", ".", "conversation", ")", ",", "channel_id", "=", "activity", ".", "channel_id", ",", "service_url", "=", "activity", ".", "service_url", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
TurnContext.apply_conversation_reference
Updates an activity with the delivery information from a conversation reference. Calling this after get_conversation_reference on an incoming activity will properly address the reply to a received activity. :param activity: :param reference: :param is_incoming: :return:
libraries/botbuilder-core/botbuilder/core/turn_context.py
def apply_conversation_reference(activity: Activity, reference: ConversationReference, is_incoming: bool=False) -> Activity: """ Updates an activity with the delivery information from a conversation reference. Calling this after get_conversation_reference on an incoming activity will properly address the reply to a received activity. :param activity: :param reference: :param is_incoming: :return: """ activity.channel_id = reference.channel_id activity.service_url = reference.service_url activity.conversation = reference.conversation if is_incoming: activity.from_property = reference.user activity.recipient = reference.bot if reference.activity_id: activity.id = reference.activity_id else: activity.from_property = reference.bot activity.recipient = reference.user if reference.activity_id: activity.reply_to_id = reference.activity_id return activity
def apply_conversation_reference(activity: Activity, reference: ConversationReference, is_incoming: bool=False) -> Activity: """ Updates an activity with the delivery information from a conversation reference. Calling this after get_conversation_reference on an incoming activity will properly address the reply to a received activity. :param activity: :param reference: :param is_incoming: :return: """ activity.channel_id = reference.channel_id activity.service_url = reference.service_url activity.conversation = reference.conversation if is_incoming: activity.from_property = reference.user activity.recipient = reference.bot if reference.activity_id: activity.id = reference.activity_id else: activity.from_property = reference.bot activity.recipient = reference.user if reference.activity_id: activity.reply_to_id = reference.activity_id return activity
[ "Updates", "an", "activity", "with", "the", "delivery", "information", "from", "a", "conversation", "reference", ".", "Calling", "this", "after", "get_conversation_reference", "on", "an", "incoming", "activity", "will", "properly", "address", "the", "reply", "to", "a", "received", "activity", ".", ":", "param", "activity", ":", ":", "param", "reference", ":", ":", "param", "is_incoming", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/turn_context.py#L237-L263
[ "def", "apply_conversation_reference", "(", "activity", ":", "Activity", ",", "reference", ":", "ConversationReference", ",", "is_incoming", ":", "bool", "=", "False", ")", "->", "Activity", ":", "activity", ".", "channel_id", "=", "reference", ".", "channel_id", "activity", ".", "service_url", "=", "reference", ".", "service_url", "activity", ".", "conversation", "=", "reference", ".", "conversation", "if", "is_incoming", ":", "activity", ".", "from_property", "=", "reference", ".", "user", "activity", ".", "recipient", "=", "reference", ".", "bot", "if", "reference", ".", "activity_id", ":", "activity", ".", "id", "=", "reference", ".", "activity_id", "else", ":", "activity", ".", "from_property", "=", "reference", ".", "bot", "activity", ".", "recipient", "=", "reference", ".", "user", "if", "reference", ".", "activity_id", ":", "activity", ".", "reply_to_id", "=", "reference", ".", "activity_id", "return", "activity" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
WaterfallDialog.add_step
Adds a new step to the waterfall. :param step: Step to add :return: Waterfall dialog for fluent calls to `add_step()`.
libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py
def add_step(self, step): """ Adds a new step to the waterfall. :param step: Step to add :return: Waterfall dialog for fluent calls to `add_step()`. """ if not step: raise TypeError('WaterfallDialog.add_step(): step cannot be None.') self._steps.append(step) return self
def add_step(self, step): """ Adds a new step to the waterfall. :param step: Step to add :return: Waterfall dialog for fluent calls to `add_step()`. """ if not step: raise TypeError('WaterfallDialog.add_step(): step cannot be None.') self._steps.append(step) return self
[ "Adds", "a", "new", "step", "to", "the", "waterfall", ".", ":", "param", "step", ":", "Step", "to", "add", ":", "return", ":", "Waterfall", "dialog", "for", "fluent", "calls", "to", "add_step", "()", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py#L36-L47
[ "def", "add_step", "(", "self", ",", "step", ")", ":", "if", "not", "step", ":", "raise", "TypeError", "(", "'WaterfallDialog.add_step(): step cannot be None.'", ")", "self", ".", "_steps", ".", "append", "(", "step", ")", "return", "self" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
WaterfallDialog.get_step_name
Give the waterfall step a unique name
libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py
def get_step_name(self, index: int) -> str: """ Give the waterfall step a unique name """ step_name = self._steps[index].__qualname__ if not step_name or ">" in step_name : step_name = f"Step{index + 1}of{len(self._steps)}" return step_name
def get_step_name(self, index: int) -> str: """ Give the waterfall step a unique name """ step_name = self._steps[index].__qualname__ if not step_name or ">" in step_name : step_name = f"Step{index + 1}of{len(self._steps)}" return step_name
[ "Give", "the", "waterfall", "step", "a", "unique", "name" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py#L141-L150
[ "def", "get_step_name", "(", "self", ",", "index", ":", "int", ")", "->", "str", ":", "step_name", "=", "self", ".", "_steps", "[", "index", "]", ".", "__qualname__", "if", "not", "step_name", "or", "\">\"", "in", "step_name", ":", "step_name", "=", "f\"Step{index + 1}of{len(self._steps)}\"", "return", "step_name" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
NullTelemetryClient.track_event
Send information about a single event that has occurred in the context of the application. :param name: the data to associate to this event. :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None)
libraries/botbuilder-core/botbuilder/core/null_telemetry_client.py
def track_event(self, name: str, properties: Dict[str, object] = None, measurements: Dict[str, object] = None) -> None: """ Send information about a single event that has occurred in the context of the application. :param name: the data to associate to this event. :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ pass
def track_event(self, name: str, properties: Dict[str, object] = None, measurements: Dict[str, object] = None) -> None: """ Send information about a single event that has occurred in the context of the application. :param name: the data to associate to this event. :param properties: the set of custom properties the client wants attached to this data item. (defaults to: None) :param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to: None) """ pass
[ "Send", "information", "about", "a", "single", "event", "that", "has", "occurred", "in", "the", "context", "of", "the", "application", ".", ":", "param", "name", ":", "the", "data", "to", "associate", "to", "this", "event", ".", ":", "param", "properties", ":", "the", "set", "of", "custom", "properties", "the", "client", "wants", "attached", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")", ":", "param", "measurements", ":", "the", "set", "of", "custom", "measurements", "the", "client", "wants", "to", "attach", "to", "this", "data", "item", ".", "(", "defaults", "to", ":", "None", ")" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/null_telemetry_client.py#L37-L45
[ "def", "track_event", "(", "self", ",", "name", ":", "str", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "measurements", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ")", "->", "None", ":", "pass" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
calculate_change_hash
Utility function to calculate a change hash for a `StoreItem`. :param item: :return:
libraries/botbuilder-core/botbuilder/core/storage.py
def calculate_change_hash(item: StoreItem) -> str: """ Utility function to calculate a change hash for a `StoreItem`. :param item: :return: """ cpy = copy(item) if cpy.e_tag is not None: del cpy.e_tag return str(cpy)
def calculate_change_hash(item: StoreItem) -> str: """ Utility function to calculate a change hash for a `StoreItem`. :param item: :return: """ cpy = copy(item) if cpy.e_tag is not None: del cpy.e_tag return str(cpy)
[ "Utility", "function", "to", "calculate", "a", "change", "hash", "for", "a", "StoreItem", ".", ":", "param", "item", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/storage.py#L62-L71
[ "def", "calculate_change_hash", "(", "item", ":", "StoreItem", ")", "->", "str", ":", "cpy", "=", "copy", "(", "item", ")", "if", "cpy", ".", "e_tag", "is", "not", "None", ":", "del", "cpy", ".", "e_tag", "return", "str", "(", "cpy", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.begin_dialog
Pushes a new dialog onto the dialog stack. :param dialog_id: ID of the dialog to start.. :param options: (Optional) additional argument(s) to pass to the dialog being started.
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def begin_dialog(self, dialog_id: str, options: object = None): """ Pushes a new dialog onto the dialog stack. :param dialog_id: ID of the dialog to start.. :param options: (Optional) additional argument(s) to pass to the dialog being started. """ if (not dialog_id): raise TypeError('Dialog(): dialogId cannot be None.') # Look up dialog dialog = await self.find_dialog(dialog_id) if dialog is None: raise Exception("'DialogContext.begin_dialog(): A dialog with an id of '%s' wasn't found." " The dialog must be included in the current or parent DialogSet." " For example, if subclassing a ComponentDialog you can call add_dialog() within your constructor." % dialog_id) # Push new instance onto stack instance = DialogInstance() instance.id = dialog_id instance.state = {} self._stack.append(instance) # Call dialog's begin_dialog() method return await dialog.begin_dialog(self, options)
async def begin_dialog(self, dialog_id: str, options: object = None): """ Pushes a new dialog onto the dialog stack. :param dialog_id: ID of the dialog to start.. :param options: (Optional) additional argument(s) to pass to the dialog being started. """ if (not dialog_id): raise TypeError('Dialog(): dialogId cannot be None.') # Look up dialog dialog = await self.find_dialog(dialog_id) if dialog is None: raise Exception("'DialogContext.begin_dialog(): A dialog with an id of '%s' wasn't found." " The dialog must be included in the current or parent DialogSet." " For example, if subclassing a ComponentDialog you can call add_dialog() within your constructor." % dialog_id) # Push new instance onto stack instance = DialogInstance() instance.id = dialog_id instance.state = {} self._stack.append(instance) # Call dialog's begin_dialog() method return await dialog.begin_dialog(self, options)
[ "Pushes", "a", "new", "dialog", "onto", "the", "dialog", "stack", ".", ":", "param", "dialog_id", ":", "ID", "of", "the", "dialog", "to", "start", "..", ":", "param", "options", ":", "(", "Optional", ")", "additional", "argument", "(", "s", ")", "to", "pass", "to", "the", "dialog", "being", "started", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L87-L109
[ "async", "def", "begin_dialog", "(", "self", ",", "dialog_id", ":", "str", ",", "options", ":", "object", "=", "None", ")", ":", "if", "(", "not", "dialog_id", ")", ":", "raise", "TypeError", "(", "'Dialog(): dialogId cannot be None.'", ")", "# Look up dialog", "dialog", "=", "await", "self", ".", "find_dialog", "(", "dialog_id", ")", "if", "dialog", "is", "None", ":", "raise", "Exception", "(", "\"'DialogContext.begin_dialog(): A dialog with an id of '%s' wasn't found.\"", "\" The dialog must be included in the current or parent DialogSet.\"", "\" For example, if subclassing a ComponentDialog you can call add_dialog() within your constructor.\"", "%", "dialog_id", ")", "# Push new instance onto stack", "instance", "=", "DialogInstance", "(", ")", "instance", ".", "id", "=", "dialog_id", "instance", ".", "state", "=", "{", "}", "self", ".", "_stack", ".", "append", "(", "instance", ")", "# Call dialog's begin_dialog() method", "return", "await", "dialog", ".", "begin_dialog", "(", "self", ",", "options", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.prompt
Helper function to simplify formatting the options for calling a prompt dialog. This helper will take a `PromptOptions` argument and then call. :param dialog_id: ID of the prompt to start. :param options: Contains a Prompt, potentially a RetryPrompt and if using ChoicePrompt, Choices. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def prompt(self, dialog_id: str, options) -> DialogTurnResult: """ Helper function to simplify formatting the options for calling a prompt dialog. This helper will take a `PromptOptions` argument and then call. :param dialog_id: ID of the prompt to start. :param options: Contains a Prompt, potentially a RetryPrompt and if using ChoicePrompt, Choices. :return: """ if (not dialog_id): raise TypeError('DialogContext.prompt(): dialogId cannot be None.') if (not options): raise TypeError('DialogContext.prompt(): options cannot be None.') return await self.begin_dialog(dialog_id, options)
async def prompt(self, dialog_id: str, options) -> DialogTurnResult: """ Helper function to simplify formatting the options for calling a prompt dialog. This helper will take a `PromptOptions` argument and then call. :param dialog_id: ID of the prompt to start. :param options: Contains a Prompt, potentially a RetryPrompt and if using ChoicePrompt, Choices. :return: """ if (not dialog_id): raise TypeError('DialogContext.prompt(): dialogId cannot be None.') if (not options): raise TypeError('DialogContext.prompt(): options cannot be None.') return await self.begin_dialog(dialog_id, options)
[ "Helper", "function", "to", "simplify", "formatting", "the", "options", "for", "calling", "a", "prompt", "dialog", ".", "This", "helper", "will", "take", "a", "PromptOptions", "argument", "and", "then", "call", ".", ":", "param", "dialog_id", ":", "ID", "of", "the", "prompt", "to", "start", ".", ":", "param", "options", ":", "Contains", "a", "Prompt", "potentially", "a", "RetryPrompt", "and", "if", "using", "ChoicePrompt", "Choices", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L112-L126
[ "async", "def", "prompt", "(", "self", ",", "dialog_id", ":", "str", ",", "options", ")", "->", "DialogTurnResult", ":", "if", "(", "not", "dialog_id", ")", ":", "raise", "TypeError", "(", "'DialogContext.prompt(): dialogId cannot be None.'", ")", "if", "(", "not", "options", ")", ":", "raise", "TypeError", "(", "'DialogContext.prompt(): options cannot be None.'", ")", "return", "await", "self", ".", "begin_dialog", "(", "dialog_id", ",", "options", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.continue_dialog
Continues execution of the active dialog, if there is one, by passing the context object to its `Dialog.continue_dialog()` method. You can check `turn_context.responded` after the call completes to determine if a dialog was run and a reply was sent to the user. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def continue_dialog(self): """ Continues execution of the active dialog, if there is one, by passing the context object to its `Dialog.continue_dialog()` method. You can check `turn_context.responded` after the call completes to determine if a dialog was run and a reply was sent to the user. :return: """ # Check for a dialog on the stack if self.active_dialog != None: # Look up dialog dialog = await self.find_dialog(self.active_dialog.id) if not dialog: raise Exception("DialogContext.continue_dialog(): Can't continue dialog. A dialog with an id of '%s' wasn't found." % active_dialog.id) # Continue execution of dialog return await dialog.continue_dialog(self) else: return DialogTurnResult(DialogTurnStatus.Empty)
async def continue_dialog(self): """ Continues execution of the active dialog, if there is one, by passing the context object to its `Dialog.continue_dialog()` method. You can check `turn_context.responded` after the call completes to determine if a dialog was run and a reply was sent to the user. :return: """ # Check for a dialog on the stack if self.active_dialog != None: # Look up dialog dialog = await self.find_dialog(self.active_dialog.id) if not dialog: raise Exception("DialogContext.continue_dialog(): Can't continue dialog. A dialog with an id of '%s' wasn't found." % active_dialog.id) # Continue execution of dialog return await dialog.continue_dialog(self) else: return DialogTurnResult(DialogTurnStatus.Empty)
[ "Continues", "execution", "of", "the", "active", "dialog", "if", "there", "is", "one", "by", "passing", "the", "context", "object", "to", "its", "Dialog", ".", "continue_dialog", "()", "method", ".", "You", "can", "check", "turn_context", ".", "responded", "after", "the", "call", "completes", "to", "determine", "if", "a", "dialog", "was", "run", "and", "a", "reply", "was", "sent", "to", "the", "user", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L129-L146
[ "async", "def", "continue_dialog", "(", "self", ")", ":", "# Check for a dialog on the stack", "if", "self", ".", "active_dialog", "!=", "None", ":", "# Look up dialog", "dialog", "=", "await", "self", ".", "find_dialog", "(", "self", ".", "active_dialog", ".", "id", ")", "if", "not", "dialog", ":", "raise", "Exception", "(", "\"DialogContext.continue_dialog(): Can't continue dialog. A dialog with an id of '%s' wasn't found.\"", "%", "active_dialog", ".", "id", ")", "# Continue execution of dialog", "return", "await", "dialog", ".", "continue_dialog", "(", "self", ")", "else", ":", "return", "DialogTurnResult", "(", "DialogTurnStatus", ".", "Empty", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.end_dialog
Ends a dialog by popping it off the stack and returns an optional result to the dialog's parent. The parent dialog is the dialog that started the dialog being ended via a call to either "begin_dialog" or "prompt". The parent dialog will have its `Dialog.resume_dialog()` method invoked with any returned result. If the parent dialog hasn't implemented a `resume_dialog()` method then it will be automatically ended as well and the result passed to its parent. If there are no more parent dialogs on the stack then processing of the turn will end. :param result: (Optional) result to pass to the parent dialogs. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def end_dialog(self, result: object = None): """ Ends a dialog by popping it off the stack and returns an optional result to the dialog's parent. The parent dialog is the dialog that started the dialog being ended via a call to either "begin_dialog" or "prompt". The parent dialog will have its `Dialog.resume_dialog()` method invoked with any returned result. If the parent dialog hasn't implemented a `resume_dialog()` method then it will be automatically ended as well and the result passed to its parent. If there are no more parent dialogs on the stack then processing of the turn will end. :param result: (Optional) result to pass to the parent dialogs. :return: """ await self.end_active_dialog(DialogReason.EndCalled) # Resume previous dialog if self.active_dialog != None: # Look up dialog dialog = await self.find_dialog(self.active_dialog.id) if not dialog: raise Exception("DialogContext.EndDialogAsync(): Can't resume previous dialog. A dialog with an id of '%s' wasn't found." % self.active_dialog.id) # Return result to previous dialog return await dialog.resume_dialog(self, DialogReason.EndCalled, result) else: return DialogTurnResult(DialogTurnStatus.Complete, result)
async def end_dialog(self, result: object = None): """ Ends a dialog by popping it off the stack and returns an optional result to the dialog's parent. The parent dialog is the dialog that started the dialog being ended via a call to either "begin_dialog" or "prompt". The parent dialog will have its `Dialog.resume_dialog()` method invoked with any returned result. If the parent dialog hasn't implemented a `resume_dialog()` method then it will be automatically ended as well and the result passed to its parent. If there are no more parent dialogs on the stack then processing of the turn will end. :param result: (Optional) result to pass to the parent dialogs. :return: """ await self.end_active_dialog(DialogReason.EndCalled) # Resume previous dialog if self.active_dialog != None: # Look up dialog dialog = await self.find_dialog(self.active_dialog.id) if not dialog: raise Exception("DialogContext.EndDialogAsync(): Can't resume previous dialog. A dialog with an id of '%s' wasn't found." % self.active_dialog.id) # Return result to previous dialog return await dialog.resume_dialog(self, DialogReason.EndCalled, result) else: return DialogTurnResult(DialogTurnStatus.Complete, result)
[ "Ends", "a", "dialog", "by", "popping", "it", "off", "the", "stack", "and", "returns", "an", "optional", "result", "to", "the", "dialog", "s", "parent", ".", "The", "parent", "dialog", "is", "the", "dialog", "that", "started", "the", "dialog", "being", "ended", "via", "a", "call", "to", "either", "begin_dialog", "or", "prompt", ".", "The", "parent", "dialog", "will", "have", "its", "Dialog", ".", "resume_dialog", "()", "method", "invoked", "with", "any", "returned", "result", ".", "If", "the", "parent", "dialog", "hasn", "t", "implemented", "a", "resume_dialog", "()", "method", "then", "it", "will", "be", "automatically", "ended", "as", "well", "and", "the", "result", "passed", "to", "its", "parent", ".", "If", "there", "are", "no", "more", "parent", "dialogs", "on", "the", "stack", "then", "processing", "of", "the", "turn", "will", "end", ".", ":", "param", "result", ":", "(", "Optional", ")", "result", "to", "pass", "to", "the", "parent", "dialogs", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L149-L173
[ "async", "def", "end_dialog", "(", "self", ",", "result", ":", "object", "=", "None", ")", ":", "await", "self", ".", "end_active_dialog", "(", "DialogReason", ".", "EndCalled", ")", "# Resume previous dialog", "if", "self", ".", "active_dialog", "!=", "None", ":", "# Look up dialog", "dialog", "=", "await", "self", ".", "find_dialog", "(", "self", ".", "active_dialog", ".", "id", ")", "if", "not", "dialog", ":", "raise", "Exception", "(", "\"DialogContext.EndDialogAsync(): Can't resume previous dialog. A dialog with an id of '%s' wasn't found.\"", "%", "self", ".", "active_dialog", ".", "id", ")", "# Return result to previous dialog", "return", "await", "dialog", ".", "resume_dialog", "(", "self", ",", "DialogReason", ".", "EndCalled", ",", "result", ")", "else", ":", "return", "DialogTurnResult", "(", "DialogTurnStatus", ".", "Complete", ",", "result", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.cancel_all_dialogs
Deletes any existing dialog stack thus cancelling all dialogs on the stack. :param result: (Optional) result to pass to the parent dialogs. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def cancel_all_dialogs(self): """ Deletes any existing dialog stack thus cancelling all dialogs on the stack. :param result: (Optional) result to pass to the parent dialogs. :return: """ if (len(self.stack) > 0): while (len(self.stack) > 0): await self.end_active_dialog(DialogReason.CancelCalled) return DialogTurnResult(DialogTurnStatus.Cancelled) else: return DialogTurnResult(DialogTurnStatus.Empty)
async def cancel_all_dialogs(self): """ Deletes any existing dialog stack thus cancelling all dialogs on the stack. :param result: (Optional) result to pass to the parent dialogs. :return: """ if (len(self.stack) > 0): while (len(self.stack) > 0): await self.end_active_dialog(DialogReason.CancelCalled) return DialogTurnResult(DialogTurnStatus.Cancelled) else: return DialogTurnResult(DialogTurnStatus.Empty)
[ "Deletes", "any", "existing", "dialog", "stack", "thus", "cancelling", "all", "dialogs", "on", "the", "stack", ".", ":", "param", "result", ":", "(", "Optional", ")", "result", "to", "pass", "to", "the", "parent", "dialogs", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L176-L187
[ "async", "def", "cancel_all_dialogs", "(", "self", ")", ":", "if", "(", "len", "(", "self", ".", "stack", ")", ">", "0", ")", ":", "while", "(", "len", "(", "self", ".", "stack", ")", ">", "0", ")", ":", "await", "self", ".", "end_active_dialog", "(", "DialogReason", ".", "CancelCalled", ")", "return", "DialogTurnResult", "(", "DialogTurnStatus", ".", "Cancelled", ")", "else", ":", "return", "DialogTurnResult", "(", "DialogTurnStatus", ".", "Empty", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.find_dialog
If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext` will be searched if there is one. :param dialog_id: ID of the dialog to search for. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def find_dialog(self, dialog_id: str) -> Dialog: """ If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext` will be searched if there is one. :param dialog_id: ID of the dialog to search for. :return: """ dialog = await self.dialogs.find(dialog_id) if (dialog == None and self.parent != None): dialog = self.parent.find_dialog(dialog_id) return dialog
async def find_dialog(self, dialog_id: str) -> Dialog: """ If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext` will be searched if there is one. :param dialog_id: ID of the dialog to search for. :return: """ dialog = await self.dialogs.find(dialog_id) if (dialog == None and self.parent != None): dialog = self.parent.find_dialog(dialog_id) return dialog
[ "If", "the", "dialog", "cannot", "be", "found", "within", "the", "current", "DialogSet", "the", "parent", "DialogContext", "will", "be", "searched", "if", "there", "is", "one", ".", ":", "param", "dialog_id", ":", "ID", "of", "the", "dialog", "to", "search", "for", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L189-L200
[ "async", "def", "find_dialog", "(", "self", ",", "dialog_id", ":", "str", ")", "->", "Dialog", ":", "dialog", "=", "await", "self", ".", "dialogs", ".", "find", "(", "dialog_id", ")", "if", "(", "dialog", "==", "None", "and", "self", ".", "parent", "!=", "None", ")", ":", "dialog", "=", "self", ".", "parent", ".", "find_dialog", "(", "dialog_id", ")", "return", "dialog" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.replace_dialog
Ends the active dialog and starts a new dialog in its place. This is particularly useful for creating loops or redirecting to another dialog. :param dialog_id: ID of the dialog to search for. :param options: (Optional) additional argument(s) to pass to the new dialog. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def replace_dialog(self, dialog_id: str, options: object = None) -> DialogTurnResult: """ Ends the active dialog and starts a new dialog in its place. This is particularly useful for creating loops or redirecting to another dialog. :param dialog_id: ID of the dialog to search for. :param options: (Optional) additional argument(s) to pass to the new dialog. :return: """ # End the current dialog and giving the reason. await self.end_active_dialog(DialogReason.ReplaceCalled) # Start replacement dialog return await self.begin_dialog(dialog_id, options)
async def replace_dialog(self, dialog_id: str, options: object = None) -> DialogTurnResult: """ Ends the active dialog and starts a new dialog in its place. This is particularly useful for creating loops or redirecting to another dialog. :param dialog_id: ID of the dialog to search for. :param options: (Optional) additional argument(s) to pass to the new dialog. :return: """ # End the current dialog and giving the reason. await self.end_active_dialog(DialogReason.ReplaceCalled) # Start replacement dialog return await self.begin_dialog(dialog_id, options)
[ "Ends", "the", "active", "dialog", "and", "starts", "a", "new", "dialog", "in", "its", "place", ".", "This", "is", "particularly", "useful", "for", "creating", "loops", "or", "redirecting", "to", "another", "dialog", ".", ":", "param", "dialog_id", ":", "ID", "of", "the", "dialog", "to", "search", "for", ".", ":", "param", "options", ":", "(", "Optional", ")", "additional", "argument", "(", "s", ")", "to", "pass", "to", "the", "new", "dialog", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L202-L214
[ "async", "def", "replace_dialog", "(", "self", ",", "dialog_id", ":", "str", ",", "options", ":", "object", "=", "None", ")", "->", "DialogTurnResult", ":", "# End the current dialog and giving the reason.", "await", "self", ".", "end_active_dialog", "(", "DialogReason", ".", "ReplaceCalled", ")", "# Start replacement dialog", "return", "await", "self", ".", "begin_dialog", "(", "dialog_id", ",", "options", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
DialogContext.reprompt_dialog
Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior. :return:
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
async def reprompt_dialog(self): """ Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior. :return: """ # Check for a dialog on the stack if self.active_dialog != None: # Look up dialog dialog = await self.find_dialog(self.active_dialog.id) if not dialog: raise Exception("DialogSet.reprompt_dialog(): Can't find A dialog with an id of '%s'." % self.active_dialog.id) # Ask dialog to re-prompt if supported await dialog.reprompt_dialog(self.context, self.active_dialog)
async def reprompt_dialog(self): """ Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior. :return: """ # Check for a dialog on the stack if self.active_dialog != None: # Look up dialog dialog = await self.find_dialog(self.active_dialog.id) if not dialog: raise Exception("DialogSet.reprompt_dialog(): Can't find A dialog with an id of '%s'." % self.active_dialog.id) # Ask dialog to re-prompt if supported await dialog.reprompt_dialog(self.context, self.active_dialog)
[ "Calls", "reprompt", "on", "the", "currently", "active", "dialog", "if", "there", "is", "one", ".", "Used", "with", "Prompts", "that", "have", "a", "reprompt", "behavior", ".", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L216-L229
[ "async", "def", "reprompt_dialog", "(", "self", ")", ":", "# Check for a dialog on the stack", "if", "self", ".", "active_dialog", "!=", "None", ":", "# Look up dialog", "dialog", "=", "await", "self", ".", "find_dialog", "(", "self", ".", "active_dialog", ".", "id", ")", "if", "not", "dialog", ":", "raise", "Exception", "(", "\"DialogSet.reprompt_dialog(): Can't find A dialog with an id of '%s'.\"", "%", "self", ".", "active_dialog", ".", "id", ")", "# Ask dialog to re-prompt if supported", "await", "dialog", ".", "reprompt_dialog", "(", "self", ".", "context", ",", "self", ".", "active_dialog", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
Channel.supports_suggested_actions
Determine if a number of Suggested Actions are supported by a Channel. Args: channel_id (str): The Channel to check the if Suggested Actions are supported in. button_cnt (int, optional): Defaults to 100. The number of Suggested Actions to check for the Channel. Returns: bool: True if the Channel supports the button_cnt total Suggested Actions, False if the Channel does not support that number of Suggested Actions.
libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py
def supports_suggested_actions(channel_id: str, button_cnt: int = 100) -> bool: """Determine if a number of Suggested Actions are supported by a Channel. Args: channel_id (str): The Channel to check the if Suggested Actions are supported in. button_cnt (int, optional): Defaults to 100. The number of Suggested Actions to check for the Channel. Returns: bool: True if the Channel supports the button_cnt total Suggested Actions, False if the Channel does not support that number of Suggested Actions. """ max_actions = { # https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies Channels.facebook: 10, Channels.skype: 10, # https://developers.line.biz/en/reference/messaging-api/#items-object Channels.line: 13, # https://dev.kik.com/#/docs/messaging#text-response-object Channels.kik: 20, Channels.telegram: 100, Channels.slack: 100, Channels.emulator: 100, Channels.direct_line: 100, Channels.webchat: 100, } return button_cnt <= max_actions[channel_id] if channel_id in max_actions else False
def supports_suggested_actions(channel_id: str, button_cnt: int = 100) -> bool: """Determine if a number of Suggested Actions are supported by a Channel. Args: channel_id (str): The Channel to check the if Suggested Actions are supported in. button_cnt (int, optional): Defaults to 100. The number of Suggested Actions to check for the Channel. Returns: bool: True if the Channel supports the button_cnt total Suggested Actions, False if the Channel does not support that number of Suggested Actions. """ max_actions = { # https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies Channels.facebook: 10, Channels.skype: 10, # https://developers.line.biz/en/reference/messaging-api/#items-object Channels.line: 13, # https://dev.kik.com/#/docs/messaging#text-response-object Channels.kik: 20, Channels.telegram: 100, Channels.slack: 100, Channels.emulator: 100, Channels.direct_line: 100, Channels.webchat: 100, } return button_cnt <= max_actions[channel_id] if channel_id in max_actions else False
[ "Determine", "if", "a", "number", "of", "Suggested", "Actions", "are", "supported", "by", "a", "Channel", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py#L14-L39
[ "def", "supports_suggested_actions", "(", "channel_id", ":", "str", ",", "button_cnt", ":", "int", "=", "100", ")", "->", "bool", ":", "max_actions", "=", "{", "# https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies", "Channels", ".", "facebook", ":", "10", ",", "Channels", ".", "skype", ":", "10", ",", "# https://developers.line.biz/en/reference/messaging-api/#items-object", "Channels", ".", "line", ":", "13", ",", "# https://dev.kik.com/#/docs/messaging#text-response-object", "Channels", ".", "kik", ":", "20", ",", "Channels", ".", "telegram", ":", "100", ",", "Channels", ".", "slack", ":", "100", ",", "Channels", ".", "emulator", ":", "100", ",", "Channels", ".", "direct_line", ":", "100", ",", "Channels", ".", "webchat", ":", "100", ",", "}", "return", "button_cnt", "<=", "max_actions", "[", "channel_id", "]", "if", "channel_id", "in", "max_actions", "else", "False" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
Channel.supports_card_actions
Determine if a number of Card Actions are supported by a Channel. Args: channel_id (str): The Channel to check if the Card Actions are supported in. button_cnt (int, optional): Defaults to 100. The number of Card Actions to check for the Channel. Returns: bool: True if the Channel supports the button_cnt total Card Actions, False if the Channel does not support that number of Card Actions.
libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py
def supports_card_actions(channel_id: str, button_cnt: int = 100) -> bool: """Determine if a number of Card Actions are supported by a Channel. Args: channel_id (str): The Channel to check if the Card Actions are supported in. button_cnt (int, optional): Defaults to 100. The number of Card Actions to check for the Channel. Returns: bool: True if the Channel supports the button_cnt total Card Actions, False if the Channel does not support that number of Card Actions. """ max_actions = { Channels.facebook: 3, Channels.skype: 3, Channels.ms_teams: 3, Channels.line: 99, Channels.slack: 100, Channels.emulator: 100, Channels.direct_line: 100, Channels.webchat: 100, Channels.cortana: 100, } return button_cnt <= max_actions[channel_id] if channel_id in max_actions else False
def supports_card_actions(channel_id: str, button_cnt: int = 100) -> bool: """Determine if a number of Card Actions are supported by a Channel. Args: channel_id (str): The Channel to check if the Card Actions are supported in. button_cnt (int, optional): Defaults to 100. The number of Card Actions to check for the Channel. Returns: bool: True if the Channel supports the button_cnt total Card Actions, False if the Channel does not support that number of Card Actions. """ max_actions = { Channels.facebook: 3, Channels.skype: 3, Channels.ms_teams: 3, Channels.line: 99, Channels.slack: 100, Channels.emulator: 100, Channels.direct_line: 100, Channels.webchat: 100, Channels.cortana: 100, } return button_cnt <= max_actions[channel_id] if channel_id in max_actions else False
[ "Determine", "if", "a", "number", "of", "Card", "Actions", "are", "supported", "by", "a", "Channel", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py#L42-L64
[ "def", "supports_card_actions", "(", "channel_id", ":", "str", ",", "button_cnt", ":", "int", "=", "100", ")", "->", "bool", ":", "max_actions", "=", "{", "Channels", ".", "facebook", ":", "3", ",", "Channels", ".", "skype", ":", "3", ",", "Channels", ".", "ms_teams", ":", "3", ",", "Channels", ".", "line", ":", "99", ",", "Channels", ".", "slack", ":", "100", ",", "Channels", ".", "emulator", ":", "100", ",", "Channels", ".", "direct_line", ":", "100", ",", "Channels", ".", "webchat", ":", "100", ",", "Channels", ".", "cortana", ":", "100", ",", "}", "return", "button_cnt", "<=", "max_actions", "[", "channel_id", "]", "if", "channel_id", "in", "max_actions", "else", "False" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
Channel.get_channel_id
Get the Channel Id from the current Activity on the Turn Context. Args: turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from. Returns: str: The Channel Id from the Turn Context's Activity.
libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py
def get_channel_id(turn_context: TurnContext) -> str: """Get the Channel Id from the current Activity on the Turn Context. Args: turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from. Returns: str: The Channel Id from the Turn Context's Activity. """ if turn_context.activity.channel_id is None: return "" else: return turn_context.activity.channel_id
def get_channel_id(turn_context: TurnContext) -> str: """Get the Channel Id from the current Activity on the Turn Context. Args: turn_context (TurnContext): The Turn Context to retrieve the Activity's Channel Id from. Returns: str: The Channel Id from the Turn Context's Activity. """ if turn_context.activity.channel_id is None: return "" else: return turn_context.activity.channel_id
[ "Get", "the", "Channel", "Id", "from", "the", "current", "Activity", "on", "the", "Turn", "Context", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py#L93-L106
[ "def", "get_channel_id", "(", "turn_context", ":", "TurnContext", ")", "->", "str", ":", "if", "turn_context", ".", "activity", ".", "channel_id", "is", "None", ":", "return", "\"\"", "else", ":", "return", "turn_context", ".", "activity", ".", "channel_id" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ConsoleAdapter.process_activity
Begins listening to console input. :param logic: :return:
samples/Console-EchoBot/adapter/console_adapter.py
async def process_activity(self, logic: Callable): """ Begins listening to console input. :param logic: :return: """ while True: msg = input() if msg is None: pass else: self._next_id += 1 activity = Activity(text=msg, channel_id='console', from_property=ChannelAccount(id='user', name='User1'), recipient=ChannelAccount(id='bot', name='Bot'), conversation=ConversationAccount(id='Convo1'), type=ActivityTypes.message, timestamp=datetime.datetime.now(), id=str(self._next_id)) activity = TurnContext.apply_conversation_reference(activity, self.reference, True) context = TurnContext(self, activity) await self.run_middleware(context, logic)
async def process_activity(self, logic: Callable): """ Begins listening to console input. :param logic: :return: """ while True: msg = input() if msg is None: pass else: self._next_id += 1 activity = Activity(text=msg, channel_id='console', from_property=ChannelAccount(id='user', name='User1'), recipient=ChannelAccount(id='bot', name='Bot'), conversation=ConversationAccount(id='Convo1'), type=ActivityTypes.message, timestamp=datetime.datetime.now(), id=str(self._next_id)) activity = TurnContext.apply_conversation_reference(activity, self.reference, True) context = TurnContext(self, activity) await self.run_middleware(context, logic)
[ "Begins", "listening", "to", "console", "input", ".", ":", "param", "logic", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/samples/Console-EchoBot/adapter/console_adapter.py#L63-L86
[ "async", "def", "process_activity", "(", "self", ",", "logic", ":", "Callable", ")", ":", "while", "True", ":", "msg", "=", "input", "(", ")", "if", "msg", "is", "None", ":", "pass", "else", ":", "self", ".", "_next_id", "+=", "1", "activity", "=", "Activity", "(", "text", "=", "msg", ",", "channel_id", "=", "'console'", ",", "from_property", "=", "ChannelAccount", "(", "id", "=", "'user'", ",", "name", "=", "'User1'", ")", ",", "recipient", "=", "ChannelAccount", "(", "id", "=", "'bot'", ",", "name", "=", "'Bot'", ")", ",", "conversation", "=", "ConversationAccount", "(", "id", "=", "'Convo1'", ")", ",", "type", "=", "ActivityTypes", ".", "message", ",", "timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "id", "=", "str", "(", "self", ".", "_next_id", ")", ")", "activity", "=", "TurnContext", ".", "apply_conversation_reference", "(", "activity", ",", "self", ".", "reference", ",", "True", ")", "context", "=", "TurnContext", "(", "self", ",", "activity", ")", "await", "self", ".", "run_middleware", "(", "context", ",", "logic", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
ConsoleAdapter.send_activities
Logs a series of activities to the console. :param context: :param activities: :return:
samples/Console-EchoBot/adapter/console_adapter.py
async def send_activities(self, context: TurnContext, activities: List[Activity]): """ Logs a series of activities to the console. :param context: :param activities: :return: """ if context is None: raise TypeError('ConsoleAdapter.send_activities(): `context` argument cannot be None.') if type(activities) != list: raise TypeError('ConsoleAdapter.send_activities(): `activities` argument must be a list.') if len(activities) == 0: raise ValueError('ConsoleAdapter.send_activities(): `activities` argument cannot have a length of 0.') async def next_activity(i: int): responses = [] if i < len(activities): responses.append(ResourceResponse()) a = activities[i] if a.type == 'delay': await asyncio.sleep(a.delay) await next_activity(i + 1) elif a.type == ActivityTypes.message: if a.attachments is not None and len(a.attachments) > 0: append = '(1 attachment)' if len(a.attachments) == 1 else f'({len(a.attachments)} attachments)' print(f'{a.text} {append}') else: print(a.text) await next_activity(i + 1) else: print(f'[{a.type}]') await next_activity(i + 1) else: return responses await next_activity(0)
async def send_activities(self, context: TurnContext, activities: List[Activity]): """ Logs a series of activities to the console. :param context: :param activities: :return: """ if context is None: raise TypeError('ConsoleAdapter.send_activities(): `context` argument cannot be None.') if type(activities) != list: raise TypeError('ConsoleAdapter.send_activities(): `activities` argument must be a list.') if len(activities) == 0: raise ValueError('ConsoleAdapter.send_activities(): `activities` argument cannot have a length of 0.') async def next_activity(i: int): responses = [] if i < len(activities): responses.append(ResourceResponse()) a = activities[i] if a.type == 'delay': await asyncio.sleep(a.delay) await next_activity(i + 1) elif a.type == ActivityTypes.message: if a.attachments is not None and len(a.attachments) > 0: append = '(1 attachment)' if len(a.attachments) == 1 else f'({len(a.attachments)} attachments)' print(f'{a.text} {append}') else: print(a.text) await next_activity(i + 1) else: print(f'[{a.type}]') await next_activity(i + 1) else: return responses await next_activity(0)
[ "Logs", "a", "series", "of", "activities", "to", "the", "console", ".", ":", "param", "context", ":", ":", "param", "activities", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/samples/Console-EchoBot/adapter/console_adapter.py#L88-L125
[ "async", "def", "send_activities", "(", "self", ",", "context", ":", "TurnContext", ",", "activities", ":", "List", "[", "Activity", "]", ")", ":", "if", "context", "is", "None", ":", "raise", "TypeError", "(", "'ConsoleAdapter.send_activities(): `context` argument cannot be None.'", ")", "if", "type", "(", "activities", ")", "!=", "list", ":", "raise", "TypeError", "(", "'ConsoleAdapter.send_activities(): `activities` argument must be a list.'", ")", "if", "len", "(", "activities", ")", "==", "0", ":", "raise", "ValueError", "(", "'ConsoleAdapter.send_activities(): `activities` argument cannot have a length of 0.'", ")", "async", "def", "next_activity", "(", "i", ":", "int", ")", ":", "responses", "=", "[", "]", "if", "i", "<", "len", "(", "activities", ")", ":", "responses", ".", "append", "(", "ResourceResponse", "(", ")", ")", "a", "=", "activities", "[", "i", "]", "if", "a", ".", "type", "==", "'delay'", ":", "await", "asyncio", ".", "sleep", "(", "a", ".", "delay", ")", "await", "next_activity", "(", "i", "+", "1", ")", "elif", "a", ".", "type", "==", "ActivityTypes", ".", "message", ":", "if", "a", ".", "attachments", "is", "not", "None", "and", "len", "(", "a", ".", "attachments", ")", ">", "0", ":", "append", "=", "'(1 attachment)'", "if", "len", "(", "a", ".", "attachments", ")", "==", "1", "else", "f'({len(a.attachments)} attachments)'", "print", "(", "f'{a.text} {append}'", ")", "else", ":", "print", "(", "a", ".", "text", ")", "await", "next_activity", "(", "i", "+", "1", ")", "else", ":", "print", "(", "f'[{a.type}]'", ")", "await", "next_activity", "(", "i", "+", "1", ")", "else", ":", "return", "responses", "await", "next_activity", "(", "0", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
EmulatorValidation.is_token_from_emulator
Determines if a given Auth header is from the Bot Framework Emulator :param auth_header: Bearer Token, in the 'Bearer [Long String]' Format. :type auth_header: str :return: True, if the token was issued by the Emulator. Otherwise, false.
libraries/botframework-connector/botframework/connector/auth/emulator_validation.py
def is_token_from_emulator(auth_header: str) -> bool: """ Determines if a given Auth header is from the Bot Framework Emulator :param auth_header: Bearer Token, in the 'Bearer [Long String]' Format. :type auth_header: str :return: True, if the token was issued by the Emulator. Otherwise, false. """ # The Auth Header generally looks like this: # "Bearer eyJ0e[...Big Long String...]XAiO" if not auth_header: # No token. Can't be an emulator token. return False parts = auth_header.split(' ') if len(parts) != 2: # Emulator tokens MUST have exactly 2 parts. # If we don't have 2 parts, it's not an emulator token return False auth_scheme = parts[0] bearer_token = parts[1] # We now have an array that should be: # [0] = "Bearer" # [1] = "[Big Long String]" if auth_scheme != 'Bearer': # The scheme from the emulator MUST be "Bearer" return False # Parse the Big Long String into an actual token. token = jwt.decode(bearer_token, verify=False) if not token: return False # Is there an Issuer? issuer = token['iss'] if not issuer: # No Issuer, means it's not from the Emulator. return False # Is the token issues by a source we consider to be the emulator? issuer_list = EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS.issuer if issuer_list and not issuer in issuer_list: # Not a Valid Issuer. This is NOT a Bot Framework Emulator Token. return False # The Token is from the Bot Framework Emulator. Success! return True
def is_token_from_emulator(auth_header: str) -> bool: """ Determines if a given Auth header is from the Bot Framework Emulator :param auth_header: Bearer Token, in the 'Bearer [Long String]' Format. :type auth_header: str :return: True, if the token was issued by the Emulator. Otherwise, false. """ # The Auth Header generally looks like this: # "Bearer eyJ0e[...Big Long String...]XAiO" if not auth_header: # No token. Can't be an emulator token. return False parts = auth_header.split(' ') if len(parts) != 2: # Emulator tokens MUST have exactly 2 parts. # If we don't have 2 parts, it's not an emulator token return False auth_scheme = parts[0] bearer_token = parts[1] # We now have an array that should be: # [0] = "Bearer" # [1] = "[Big Long String]" if auth_scheme != 'Bearer': # The scheme from the emulator MUST be "Bearer" return False # Parse the Big Long String into an actual token. token = jwt.decode(bearer_token, verify=False) if not token: return False # Is there an Issuer? issuer = token['iss'] if not issuer: # No Issuer, means it's not from the Emulator. return False # Is the token issues by a source we consider to be the emulator? issuer_list = EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS.issuer if issuer_list and not issuer in issuer_list: # Not a Valid Issuer. This is NOT a Bot Framework Emulator Token. return False # The Token is from the Bot Framework Emulator. Success! return True
[ "Determines", "if", "a", "given", "Auth", "header", "is", "from", "the", "Bot", "Framework", "Emulator" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py#L33-L81
[ "def", "is_token_from_emulator", "(", "auth_header", ":", "str", ")", "->", "bool", ":", "# The Auth Header generally looks like this:", "# \"Bearer eyJ0e[...Big Long String...]XAiO\"", "if", "not", "auth_header", ":", "# No token. Can't be an emulator token.", "return", "False", "parts", "=", "auth_header", ".", "split", "(", "' '", ")", "if", "len", "(", "parts", ")", "!=", "2", ":", "# Emulator tokens MUST have exactly 2 parts.", "# If we don't have 2 parts, it's not an emulator token", "return", "False", "auth_scheme", "=", "parts", "[", "0", "]", "bearer_token", "=", "parts", "[", "1", "]", "# We now have an array that should be:", "# [0] = \"Bearer\"", "# [1] = \"[Big Long String]\"", "if", "auth_scheme", "!=", "'Bearer'", ":", "# The scheme from the emulator MUST be \"Bearer\"", "return", "False", "# Parse the Big Long String into an actual token.", "token", "=", "jwt", ".", "decode", "(", "bearer_token", ",", "verify", "=", "False", ")", "if", "not", "token", ":", "return", "False", "# Is there an Issuer?", "issuer", "=", "token", "[", "'iss'", "]", "if", "not", "issuer", ":", "# No Issuer, means it's not from the Emulator.", "return", "False", "# Is the token issues by a source we consider to be the emulator?", "issuer_list", "=", "EmulatorValidation", ".", "TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS", ".", "issuer", "if", "issuer_list", "and", "not", "issuer", "in", "issuer_list", ":", "# Not a Valid Issuer. This is NOT a Bot Framework Emulator Token.", "return", "False", "# The Token is from the Bot Framework Emulator. Success!", "return", "True" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
EmulatorValidation.authenticate_emulator_token
Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :return: A valid ClaimsIdentity. :raises Exception:
libraries/botframework-connector/botframework/connector/auth/emulator_validation.py
async def authenticate_emulator_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity: """ Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :return: A valid ClaimsIdentity. :raises Exception: """ token_extractor = JwtTokenExtractor( EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS, Constants.TO_BOT_FROM_EMULATOR_OPEN_ID_METADATA_URL, Constants.ALLOWED_SIGNING_ALGORITHMS) identity = await asyncio.ensure_future( token_extractor.get_identity_from_auth_header(auth_header, channel_id)) if not identity: # No valid identity. Not Authorized. raise Exception('Unauthorized. No valid identity.') if not identity.isAuthenticated: # The token is in some way invalid. Not Authorized. raise Exception('Unauthorized. Is not authenticated') # Now check that the AppID in the claimset matches # what we're looking for. Note that in a multi-tenant bot, this value # comes from developer code that may be reaching out to a service, hence the # Async validation. version_claim = identity.get_claim_value(EmulatorValidation.VERSION_CLAIM) if version_claim is None: raise Exception('Unauthorized. "ver" claim is required on Emulator Tokens.') app_id = '' # The Emulator, depending on Version, sends the AppId via either the # appid claim (Version 1) or the Authorized Party claim (Version 2). if not version_claim or version_claim == '1.0': # either no Version or a version of "1.0" means we should look for # the claim in the "appid" claim. app_id_claim = identity.get_claim_value(EmulatorValidation.APP_ID_CLAIM) if not app_id_claim: # No claim around AppID. Not Authorized. raise Exception('Unauthorized. ' '"appid" claim is required on Emulator Token version "1.0".') app_id = app_id_claim elif version_claim == '2.0': # Emulator, "2.0" puts the AppId in the "azp" claim. app_authz_claim = identity.get_claim_value(Constants.AUTHORIZED_PARTY) if not app_authz_claim: # No claim around AppID. Not Authorized. raise Exception('Unauthorized. ' '"azp" claim is required on Emulator Token version "2.0".') app_id = app_authz_claim else: # Unknown Version. Not Authorized. raise Exception('Unauthorized. Unknown Emulator Token version ', version_claim, '.') is_valid_app_id = await asyncio.ensure_future(credentials.is_valid_appid(app_id)) if not is_valid_app_id: raise Exception('Unauthorized. Invalid AppId passed on token: ', app_id) return identity
async def authenticate_emulator_token(auth_header: str, credentials: CredentialProvider, channel_id: str) -> ClaimsIdentity: """ Validate the incoming Auth Header Validate the incoming Auth Header as a token sent from the Bot Framework Service. A token issued by the Bot Framework emulator will FAIL this check. :param auth_header: The raw HTTP header in the format: 'Bearer [longString]' :type auth_header: str :param credentials: The user defined set of valid credentials, such as the AppId. :type credentials: CredentialProvider :return: A valid ClaimsIdentity. :raises Exception: """ token_extractor = JwtTokenExtractor( EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS, Constants.TO_BOT_FROM_EMULATOR_OPEN_ID_METADATA_URL, Constants.ALLOWED_SIGNING_ALGORITHMS) identity = await asyncio.ensure_future( token_extractor.get_identity_from_auth_header(auth_header, channel_id)) if not identity: # No valid identity. Not Authorized. raise Exception('Unauthorized. No valid identity.') if not identity.isAuthenticated: # The token is in some way invalid. Not Authorized. raise Exception('Unauthorized. Is not authenticated') # Now check that the AppID in the claimset matches # what we're looking for. Note that in a multi-tenant bot, this value # comes from developer code that may be reaching out to a service, hence the # Async validation. version_claim = identity.get_claim_value(EmulatorValidation.VERSION_CLAIM) if version_claim is None: raise Exception('Unauthorized. "ver" claim is required on Emulator Tokens.') app_id = '' # The Emulator, depending on Version, sends the AppId via either the # appid claim (Version 1) or the Authorized Party claim (Version 2). if not version_claim or version_claim == '1.0': # either no Version or a version of "1.0" means we should look for # the claim in the "appid" claim. app_id_claim = identity.get_claim_value(EmulatorValidation.APP_ID_CLAIM) if not app_id_claim: # No claim around AppID. Not Authorized. raise Exception('Unauthorized. ' '"appid" claim is required on Emulator Token version "1.0".') app_id = app_id_claim elif version_claim == '2.0': # Emulator, "2.0" puts the AppId in the "azp" claim. app_authz_claim = identity.get_claim_value(Constants.AUTHORIZED_PARTY) if not app_authz_claim: # No claim around AppID. Not Authorized. raise Exception('Unauthorized. ' '"azp" claim is required on Emulator Token version "2.0".') app_id = app_authz_claim else: # Unknown Version. Not Authorized. raise Exception('Unauthorized. Unknown Emulator Token version ', version_claim, '.') is_valid_app_id = await asyncio.ensure_future(credentials.is_valid_appid(app_id)) if not is_valid_app_id: raise Exception('Unauthorized. Invalid AppId passed on token: ', app_id) return identity
[ "Validate", "the", "incoming", "Auth", "Header" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/auth/emulator_validation.py#L84-L152
[ "async", "def", "authenticate_emulator_token", "(", "auth_header", ":", "str", ",", "credentials", ":", "CredentialProvider", ",", "channel_id", ":", "str", ")", "->", "ClaimsIdentity", ":", "token_extractor", "=", "JwtTokenExtractor", "(", "EmulatorValidation", ".", "TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS", ",", "Constants", ".", "TO_BOT_FROM_EMULATOR_OPEN_ID_METADATA_URL", ",", "Constants", ".", "ALLOWED_SIGNING_ALGORITHMS", ")", "identity", "=", "await", "asyncio", ".", "ensure_future", "(", "token_extractor", ".", "get_identity_from_auth_header", "(", "auth_header", ",", "channel_id", ")", ")", "if", "not", "identity", ":", "# No valid identity. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. No valid identity.'", ")", "if", "not", "identity", ".", "isAuthenticated", ":", "# The token is in some way invalid. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. Is not authenticated'", ")", "# Now check that the AppID in the claimset matches", "# what we're looking for. Note that in a multi-tenant bot, this value", "# comes from developer code that may be reaching out to a service, hence the", "# Async validation.", "version_claim", "=", "identity", ".", "get_claim_value", "(", "EmulatorValidation", ".", "VERSION_CLAIM", ")", "if", "version_claim", "is", "None", ":", "raise", "Exception", "(", "'Unauthorized. \"ver\" claim is required on Emulator Tokens.'", ")", "app_id", "=", "''", "# The Emulator, depending on Version, sends the AppId via either the", "# appid claim (Version 1) or the Authorized Party claim (Version 2).", "if", "not", "version_claim", "or", "version_claim", "==", "'1.0'", ":", "# either no Version or a version of \"1.0\" means we should look for", "# the claim in the \"appid\" claim.", "app_id_claim", "=", "identity", ".", "get_claim_value", "(", "EmulatorValidation", ".", "APP_ID_CLAIM", ")", "if", "not", "app_id_claim", ":", "# No claim around AppID. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. '", "'\"appid\" claim is required on Emulator Token version \"1.0\".'", ")", "app_id", "=", "app_id_claim", "elif", "version_claim", "==", "'2.0'", ":", "# Emulator, \"2.0\" puts the AppId in the \"azp\" claim.", "app_authz_claim", "=", "identity", ".", "get_claim_value", "(", "Constants", ".", "AUTHORIZED_PARTY", ")", "if", "not", "app_authz_claim", ":", "# No claim around AppID. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. '", "'\"azp\" claim is required on Emulator Token version \"2.0\".'", ")", "app_id", "=", "app_authz_claim", "else", ":", "# Unknown Version. Not Authorized.", "raise", "Exception", "(", "'Unauthorized. Unknown Emulator Token version '", ",", "version_claim", ",", "'.'", ")", "is_valid_app_id", "=", "await", "asyncio", ".", "ensure_future", "(", "credentials", ".", "is_valid_appid", "(", "app_id", ")", ")", "if", "not", "is_valid_app_id", ":", "raise", "Exception", "(", "'Unauthorized. Invalid AppId passed on token: '", ",", "app_id", ")", "return", "identity" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.adaptive_card
Returns an attachment for an adaptive card. The attachment will contain the card and the appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an dict. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def adaptive_card(card: dict) -> Attachment: """ Returns an attachment for an adaptive card. The attachment will contain the card and the appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an dict. :param card: :return: """ if not type(card) == dict: raise TypeError('CardFactory.adaptive_card(): `card` argument is not of type dict, unable to prepare ' 'attachment.') return Attachment(content_type=CardFactory.content_types.adaptive_card, content=card)
def adaptive_card(card: dict) -> Attachment: """ Returns an attachment for an adaptive card. The attachment will contain the card and the appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an dict. :param card: :return: """ if not type(card) == dict: raise TypeError('CardFactory.adaptive_card(): `card` argument is not of type dict, unable to prepare ' 'attachment.') return Attachment(content_type=CardFactory.content_types.adaptive_card, content=card)
[ "Returns", "an", "attachment", "for", "an", "adaptive", "card", ".", "The", "attachment", "will", "contain", "the", "card", "and", "the", "appropriate", "contentType", ".", "Will", "raise", "a", "TypeError", "if", "the", "card", "argument", "is", "not", "an", "dict", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L25-L38
[ "def", "adaptive_card", "(", "card", ":", "dict", ")", "->", "Attachment", ":", "if", "not", "type", "(", "card", ")", "==", "dict", ":", "raise", "TypeError", "(", "'CardFactory.adaptive_card(): `card` argument is not of type dict, unable to prepare '", "'attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "adaptive_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.animation_card
Returns an attachment for an animation card. Will raise a TypeError if the 'card' argument is not an AnimationCard. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def animation_card(card: AnimationCard) -> Attachment: """ Returns an attachment for an animation card. Will raise a TypeError if the 'card' argument is not an AnimationCard. :param card: :return: """ if not isinstance(card, AnimationCard): raise TypeError('CardFactory.animation_card(): `card` argument is not an instance of an AnimationCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.animation_card, content=card)
def animation_card(card: AnimationCard) -> Attachment: """ Returns an attachment for an animation card. Will raise a TypeError if the 'card' argument is not an AnimationCard. :param card: :return: """ if not isinstance(card, AnimationCard): raise TypeError('CardFactory.animation_card(): `card` argument is not an instance of an AnimationCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.animation_card, content=card)
[ "Returns", "an", "attachment", "for", "an", "animation", "card", ".", "Will", "raise", "a", "TypeError", "if", "the", "card", "argument", "is", "not", "an", "AnimationCard", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L41-L53
[ "def", "animation_card", "(", "card", ":", "AnimationCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "AnimationCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.animation_card(): `card` argument is not an instance of an AnimationCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "animation_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.audio_card
Returns an attachment for an audio card. Will raise a TypeError if 'card' argument is not an AudioCard. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def audio_card(card: AudioCard) -> Attachment: """ Returns an attachment for an audio card. Will raise a TypeError if 'card' argument is not an AudioCard. :param card: :return: """ if not isinstance(card, AudioCard): raise TypeError('CardFactory.audio_card(): `card` argument is not an instance of an AudioCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.audio_card, content=card)
def audio_card(card: AudioCard) -> Attachment: """ Returns an attachment for an audio card. Will raise a TypeError if 'card' argument is not an AudioCard. :param card: :return: """ if not isinstance(card, AudioCard): raise TypeError('CardFactory.audio_card(): `card` argument is not an instance of an AudioCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.audio_card, content=card)
[ "Returns", "an", "attachment", "for", "an", "audio", "card", ".", "Will", "raise", "a", "TypeError", "if", "card", "argument", "is", "not", "an", "AudioCard", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L56-L67
[ "def", "audio_card", "(", "card", ":", "AudioCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "AudioCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.audio_card(): `card` argument is not an instance of an AudioCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "audio_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.hero_card
Returns an attachment for a hero card. Will raise a TypeError if 'card' argument is not a HeroCard. Hero cards tend to have one dominant full width image and the cards text & buttons can usually be found below the image. :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def hero_card(card: HeroCard) -> Attachment: """ Returns an attachment for a hero card. Will raise a TypeError if 'card' argument is not a HeroCard. Hero cards tend to have one dominant full width image and the cards text & buttons can usually be found below the image. :return: """ if not isinstance(card, HeroCard): raise TypeError('CardFactory.hero_card(): `card` argument is not an instance of an HeroCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.hero_card, content=card)
def hero_card(card: HeroCard) -> Attachment: """ Returns an attachment for a hero card. Will raise a TypeError if 'card' argument is not a HeroCard. Hero cards tend to have one dominant full width image and the cards text & buttons can usually be found below the image. :return: """ if not isinstance(card, HeroCard): raise TypeError('CardFactory.hero_card(): `card` argument is not an instance of an HeroCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.hero_card, content=card)
[ "Returns", "an", "attachment", "for", "a", "hero", "card", ".", "Will", "raise", "a", "TypeError", "if", "card", "argument", "is", "not", "a", "HeroCard", "." ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L70-L83
[ "def", "hero_card", "(", "card", ":", "HeroCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "HeroCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.hero_card(): `card` argument is not an instance of an HeroCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "hero_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.oauth_card
Returns an attachment for an OAuth card used by the Bot Frameworks Single Sign On (SSO) service. Will raise a TypeError if 'card' argument is not a OAuthCard. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def oauth_card(card: OAuthCard) -> Attachment: """ Returns an attachment for an OAuth card used by the Bot Frameworks Single Sign On (SSO) service. Will raise a TypeError if 'card' argument is not a OAuthCard. :param card: :return: """ if not isinstance(card, OAuthCard): raise TypeError('CardFactory.oauth_card(): `card` argument is not an instance of an OAuthCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.oauth_card, content=card)
def oauth_card(card: OAuthCard) -> Attachment: """ Returns an attachment for an OAuth card used by the Bot Frameworks Single Sign On (SSO) service. Will raise a TypeError if 'card' argument is not a OAuthCard. :param card: :return: """ if not isinstance(card, OAuthCard): raise TypeError('CardFactory.oauth_card(): `card` argument is not an instance of an OAuthCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.oauth_card, content=card)
[ "Returns", "an", "attachment", "for", "an", "OAuth", "card", "used", "by", "the", "Bot", "Frameworks", "Single", "Sign", "On", "(", "SSO", ")", "service", ".", "Will", "raise", "a", "TypeError", "if", "card", "argument", "is", "not", "a", "OAuthCard", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L86-L98
[ "def", "oauth_card", "(", "card", ":", "OAuthCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "OAuthCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.oauth_card(): `card` argument is not an instance of an OAuthCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "oauth_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.receipt_card
Returns an attachment for a receipt card. Will raise a TypeError if 'card' argument is not a ReceiptCard. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def receipt_card(card: ReceiptCard) -> Attachment: """ Returns an attachment for a receipt card. Will raise a TypeError if 'card' argument is not a ReceiptCard. :param card: :return: """ if not isinstance(card, ReceiptCard): raise TypeError('CardFactory.receipt_card(): `card` argument is not an instance of an ReceiptCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.receipt_card, content=card)
def receipt_card(card: ReceiptCard) -> Attachment: """ Returns an attachment for a receipt card. Will raise a TypeError if 'card' argument is not a ReceiptCard. :param card: :return: """ if not isinstance(card, ReceiptCard): raise TypeError('CardFactory.receipt_card(): `card` argument is not an instance of an ReceiptCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.receipt_card, content=card)
[ "Returns", "an", "attachment", "for", "a", "receipt", "card", ".", "Will", "raise", "a", "TypeError", "if", "card", "argument", "is", "not", "a", "ReceiptCard", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L101-L112
[ "def", "receipt_card", "(", "card", ":", "ReceiptCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "ReceiptCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.receipt_card(): `card` argument is not an instance of an ReceiptCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "receipt_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.signin_card
Returns an attachment for a signin card. For channels that don't natively support signin cards an alternative message will be rendered. Will raise a TypeError if 'card' argument is not a SigninCard. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def signin_card(card: SigninCard) -> Attachment: """ Returns an attachment for a signin card. For channels that don't natively support signin cards an alternative message will be rendered. Will raise a TypeError if 'card' argument is not a SigninCard. :param card: :return: """ if not isinstance(card, SigninCard): raise TypeError('CardFactory.signin_card(): `card` argument is not an instance of an SigninCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.signin_card, content=card)
def signin_card(card: SigninCard) -> Attachment: """ Returns an attachment for a signin card. For channels that don't natively support signin cards an alternative message will be rendered. Will raise a TypeError if 'card' argument is not a SigninCard. :param card: :return: """ if not isinstance(card, SigninCard): raise TypeError('CardFactory.signin_card(): `card` argument is not an instance of an SigninCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.signin_card, content=card)
[ "Returns", "an", "attachment", "for", "a", "signin", "card", ".", "For", "channels", "that", "don", "t", "natively", "support", "signin", "cards", "an", "alternative", "message", "will", "be", "rendered", ".", "Will", "raise", "a", "TypeError", "if", "card", "argument", "is", "not", "a", "SigninCard", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L115-L127
[ "def", "signin_card", "(", "card", ":", "SigninCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "SigninCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.signin_card(): `card` argument is not an instance of an SigninCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "signin_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.thumbnail_card
Returns an attachment for a thumbnail card. Thumbnail cards are similar to but instead of a full width image, they're typically rendered with a smaller thumbnail version of the image on either side and the text will be rendered in column next to the image. Any buttons will typically show up under the card. Will raise a TypeError if 'card' argument is not a ThumbnailCard. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def thumbnail_card(card: ThumbnailCard) -> Attachment: """ Returns an attachment for a thumbnail card. Thumbnail cards are similar to but instead of a full width image, they're typically rendered with a smaller thumbnail version of the image on either side and the text will be rendered in column next to the image. Any buttons will typically show up under the card. Will raise a TypeError if 'card' argument is not a ThumbnailCard. :param card: :return: """ if not isinstance(card, ThumbnailCard): raise TypeError('CardFactory.thumbnail_card(): `card` argument is not an instance of an ThumbnailCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.thumbnail_card, content=card)
def thumbnail_card(card: ThumbnailCard) -> Attachment: """ Returns an attachment for a thumbnail card. Thumbnail cards are similar to but instead of a full width image, they're typically rendered with a smaller thumbnail version of the image on either side and the text will be rendered in column next to the image. Any buttons will typically show up under the card. Will raise a TypeError if 'card' argument is not a ThumbnailCard. :param card: :return: """ if not isinstance(card, ThumbnailCard): raise TypeError('CardFactory.thumbnail_card(): `card` argument is not an instance of an ThumbnailCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.thumbnail_card, content=card)
[ "Returns", "an", "attachment", "for", "a", "thumbnail", "card", ".", "Thumbnail", "cards", "are", "similar", "to", "but", "instead", "of", "a", "full", "width", "image", "they", "re", "typically", "rendered", "with", "a", "smaller", "thumbnail", "version", "of", "the", "image", "on", "either", "side", "and", "the", "text", "will", "be", "rendered", "in", "column", "next", "to", "the", "image", ".", "Any", "buttons", "will", "typically", "show", "up", "under", "the", "card", ".", "Will", "raise", "a", "TypeError", "if", "card", "argument", "is", "not", "a", "ThumbnailCard", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L130-L144
[ "def", "thumbnail_card", "(", "card", ":", "ThumbnailCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "ThumbnailCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.thumbnail_card(): `card` argument is not an instance of an ThumbnailCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "thumbnail_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
CardFactory.video_card
Returns an attachment for a video card. Will raise a TypeError if 'card' argument is not a VideoCard. :param card: :return:
libraries/botbuilder-core/botbuilder/core/card_factory.py
def video_card(card: VideoCard) -> Attachment: """ Returns an attachment for a video card. Will raise a TypeError if 'card' argument is not a VideoCard. :param card: :return: """ if not isinstance(card, VideoCard): raise TypeError('CardFactory.video_card(): `card` argument is not an instance of an VideoCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.video_card, content=card)
def video_card(card: VideoCard) -> Attachment: """ Returns an attachment for a video card. Will raise a TypeError if 'card' argument is not a VideoCard. :param card: :return: """ if not isinstance(card, VideoCard): raise TypeError('CardFactory.video_card(): `card` argument is not an instance of an VideoCard, ' 'unable to prepare attachment.') return Attachment(content_type=CardFactory.content_types.video_card, content=card)
[ "Returns", "an", "attachment", "for", "a", "video", "card", ".", "Will", "raise", "a", "TypeError", "if", "card", "argument", "is", "not", "a", "VideoCard", ".", ":", "param", "card", ":", ":", "return", ":" ]
Microsoft/botbuilder-python
python
https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-core/botbuilder/core/card_factory.py#L147-L158
[ "def", "video_card", "(", "card", ":", "VideoCard", ")", "->", "Attachment", ":", "if", "not", "isinstance", "(", "card", ",", "VideoCard", ")", ":", "raise", "TypeError", "(", "'CardFactory.video_card(): `card` argument is not an instance of an VideoCard, '", "'unable to prepare attachment.'", ")", "return", "Attachment", "(", "content_type", "=", "CardFactory", ".", "content_types", ".", "video_card", ",", "content", "=", "card", ")" ]
274663dd91c811bae6ac4488915ba5880771b0a7
test
Instruction.params
return instruction params
qiskit/circuit/instruction.py
def params(self): """return instruction params""" # if params already defined don't attempt to get them from definition if self._definition and not self._params: self._params = [] for sub_instr, _, _ in self._definition: self._params.extend(sub_instr.params) # recursive call return self._params else: return self._params
def params(self): """return instruction params""" # if params already defined don't attempt to get them from definition if self._definition and not self._params: self._params = [] for sub_instr, _, _ in self._definition: self._params.extend(sub_instr.params) # recursive call return self._params else: return self._params
[ "return", "instruction", "params" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L112-L121
[ "def", "params", "(", "self", ")", ":", "# if params already defined don't attempt to get them from definition", "if", "self", ".", "_definition", "and", "not", "self", ".", "_params", ":", "self", ".", "_params", "=", "[", "]", "for", "sub_instr", ",", "_", ",", "_", "in", "self", ".", "_definition", ":", "self", ".", "_params", ".", "extend", "(", "sub_instr", ".", "params", ")", "# recursive call", "return", "self", ".", "_params", "else", ":", "return", "self", ".", "_params" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction.assemble
Assemble a QasmQobjInstruction
qiskit/circuit/instruction.py
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = QasmQobjInstruction(name=self.name) # Evaluate parameters if self.params: params = [ x.evalf() if hasattr(x, 'evalf') else x for x in self.params ] params = [ sympy.matrix2numpy(x, dtype=complex) if isinstance( x, sympy.Matrix) else x for x in params ] instruction.params = params # Add placeholder for qarg and carg params if self.num_qubits: instruction.qubits = list(range(self.num_qubits)) if self.num_clbits: instruction.memory = list(range(self.num_clbits)) # Add control parameters for assembler. This is needed to convert # to a qobj conditional instruction at assemble time and after # conversion will be deleted by the assembler. if self.control: instruction._control = self.control return instruction
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = QasmQobjInstruction(name=self.name) # Evaluate parameters if self.params: params = [ x.evalf() if hasattr(x, 'evalf') else x for x in self.params ] params = [ sympy.matrix2numpy(x, dtype=complex) if isinstance( x, sympy.Matrix) else x for x in params ] instruction.params = params # Add placeholder for qarg and carg params if self.num_qubits: instruction.qubits = list(range(self.num_qubits)) if self.num_clbits: instruction.memory = list(range(self.num_clbits)) # Add control parameters for assembler. This is needed to convert # to a qobj conditional instruction at assemble time and after # conversion will be deleted by the assembler. if self.control: instruction._control = self.control return instruction
[ "Assemble", "a", "QasmQobjInstruction" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L169-L192
[ "def", "assemble", "(", "self", ")", ":", "instruction", "=", "QasmQobjInstruction", "(", "name", "=", "self", ".", "name", ")", "# Evaluate parameters", "if", "self", ".", "params", ":", "params", "=", "[", "x", ".", "evalf", "(", ")", "if", "hasattr", "(", "x", ",", "'evalf'", ")", "else", "x", "for", "x", "in", "self", ".", "params", "]", "params", "=", "[", "sympy", ".", "matrix2numpy", "(", "x", ",", "dtype", "=", "complex", ")", "if", "isinstance", "(", "x", ",", "sympy", ".", "Matrix", ")", "else", "x", "for", "x", "in", "params", "]", "instruction", ".", "params", "=", "params", "# Add placeholder for qarg and carg params", "if", "self", ".", "num_qubits", ":", "instruction", ".", "qubits", "=", "list", "(", "range", "(", "self", ".", "num_qubits", ")", ")", "if", "self", ".", "num_clbits", ":", "instruction", ".", "memory", "=", "list", "(", "range", "(", "self", ".", "num_clbits", ")", ")", "# Add control parameters for assembler. This is needed to convert", "# to a qobj conditional instruction at assemble time and after", "# conversion will be deleted by the assembler.", "if", "self", ".", "control", ":", "instruction", ".", "_control", "=", "self", ".", "control", "return", "instruction" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction.mirror
For a composite instruction, reverse the order of sub-gates. This is done by recursively mirroring all sub-instructions. It does not invert any gate. Returns: Instruction: a fresh gate with sub-gates reversed
qiskit/circuit/instruction.py
def mirror(self): """For a composite instruction, reverse the order of sub-gates. This is done by recursively mirroring all sub-instructions. It does not invert any gate. Returns: Instruction: a fresh gate with sub-gates reversed """ if not self._definition: return self.copy() reverse_inst = self.copy(name=self.name + '_mirror') reverse_inst.definition = [] for inst, qargs, cargs in reversed(self._definition): reverse_inst._definition.append((inst.mirror(), qargs, cargs)) return reverse_inst
def mirror(self): """For a composite instruction, reverse the order of sub-gates. This is done by recursively mirroring all sub-instructions. It does not invert any gate. Returns: Instruction: a fresh gate with sub-gates reversed """ if not self._definition: return self.copy() reverse_inst = self.copy(name=self.name + '_mirror') reverse_inst.definition = [] for inst, qargs, cargs in reversed(self._definition): reverse_inst._definition.append((inst.mirror(), qargs, cargs)) return reverse_inst
[ "For", "a", "composite", "instruction", "reverse", "the", "order", "of", "sub", "-", "gates", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L194-L210
[ "def", "mirror", "(", "self", ")", ":", "if", "not", "self", ".", "_definition", ":", "return", "self", ".", "copy", "(", ")", "reverse_inst", "=", "self", ".", "copy", "(", "name", "=", "self", ".", "name", "+", "'_mirror'", ")", "reverse_inst", ".", "definition", "=", "[", "]", "for", "inst", ",", "qargs", ",", "cargs", "in", "reversed", "(", "self", ".", "_definition", ")", ":", "reverse_inst", ".", "_definition", ".", "append", "(", "(", "inst", ".", "mirror", "(", ")", ",", "qargs", ",", "cargs", ")", ")", "return", "reverse_inst" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction.inverse
Invert this instruction. If the instruction is composite (i.e. has a definition), then its definition will be recursively inverted. Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) Returns: Instruction: a fresh instruction for the inverse Raises: QiskitError: if the instruction is not composite and an inverse has not been implemented for it.
qiskit/circuit/instruction.py
def inverse(self): """Invert this instruction. If the instruction is composite (i.e. has a definition), then its definition will be recursively inverted. Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) Returns: Instruction: a fresh instruction for the inverse Raises: QiskitError: if the instruction is not composite and an inverse has not been implemented for it. """ if not self.definition: raise QiskitError("inverse() not implemented for %s." % self.name) inverse_gate = self.copy(name=self.name + '_dg') inverse_gate._definition = [] for inst, qargs, cargs in reversed(self._definition): inverse_gate._definition.append((inst.inverse(), qargs, cargs)) return inverse_gate
def inverse(self): """Invert this instruction. If the instruction is composite (i.e. has a definition), then its definition will be recursively inverted. Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) Returns: Instruction: a fresh instruction for the inverse Raises: QiskitError: if the instruction is not composite and an inverse has not been implemented for it. """ if not self.definition: raise QiskitError("inverse() not implemented for %s." % self.name) inverse_gate = self.copy(name=self.name + '_dg') inverse_gate._definition = [] for inst, qargs, cargs in reversed(self._definition): inverse_gate._definition.append((inst.inverse(), qargs, cargs)) return inverse_gate
[ "Invert", "this", "instruction", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L212-L234
[ "def", "inverse", "(", "self", ")", ":", "if", "not", "self", ".", "definition", ":", "raise", "QiskitError", "(", "\"inverse() not implemented for %s.\"", "%", "self", ".", "name", ")", "inverse_gate", "=", "self", ".", "copy", "(", "name", "=", "self", ".", "name", "+", "'_dg'", ")", "inverse_gate", ".", "_definition", "=", "[", "]", "for", "inst", ",", "qargs", ",", "cargs", "in", "reversed", "(", "self", ".", "_definition", ")", ":", "inverse_gate", ".", "_definition", ".", "append", "(", "(", "inst", ".", "inverse", "(", ")", ",", "qargs", ",", "cargs", ")", ")", "return", "inverse_gate" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction.c_if
Add classical control on register classical and value val.
qiskit/circuit/instruction.py
def c_if(self, classical, val): """Add classical control on register classical and value val.""" if not isinstance(classical, ClassicalRegister): raise QiskitError("c_if must be used with a classical register") if val < 0: raise QiskitError("control value should be non-negative") self.control = (classical, val) return self
def c_if(self, classical, val): """Add classical control on register classical and value val.""" if not isinstance(classical, ClassicalRegister): raise QiskitError("c_if must be used with a classical register") if val < 0: raise QiskitError("control value should be non-negative") self.control = (classical, val) return self
[ "Add", "classical", "control", "on", "register", "classical", "and", "value", "val", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L236-L243
[ "def", "c_if", "(", "self", ",", "classical", ",", "val", ")", ":", "if", "not", "isinstance", "(", "classical", ",", "ClassicalRegister", ")", ":", "raise", "QiskitError", "(", "\"c_if must be used with a classical register\"", ")", "if", "val", "<", "0", ":", "raise", "QiskitError", "(", "\"control value should be non-negative\"", ")", "self", ".", "control", "=", "(", "classical", ",", "val", ")", "return", "self" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction.copy
shallow copy of the instruction. Args: name (str): name to be given to the copied circuit, if None then the name stays the same Returns: Instruction: a shallow copy of the current instruction, with the name updated if it was provided
qiskit/circuit/instruction.py
def copy(self, name=None): """ shallow copy of the instruction. Args: name (str): name to be given to the copied circuit, if None then the name stays the same Returns: Instruction: a shallow copy of the current instruction, with the name updated if it was provided """ cpy = copy.copy(self) if name: cpy.name = name return cpy
def copy(self, name=None): """ shallow copy of the instruction. Args: name (str): name to be given to the copied circuit, if None then the name stays the same Returns: Instruction: a shallow copy of the current instruction, with the name updated if it was provided """ cpy = copy.copy(self) if name: cpy.name = name return cpy
[ "shallow", "copy", "of", "the", "instruction", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L245-L260
[ "def", "copy", "(", "self", ",", "name", "=", "None", ")", ":", "cpy", "=", "copy", ".", "copy", "(", "self", ")", "if", "name", ":", "cpy", ".", "name", "=", "name", "return", "cpy" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction._qasmif
Print an if statement if needed.
qiskit/circuit/instruction.py
def _qasmif(self, string): """Print an if statement if needed.""" if self.control is None: return string return "if(%s==%d) " % (self.control[0].name, self.control[1]) + string
def _qasmif(self, string): """Print an if statement if needed.""" if self.control is None: return string return "if(%s==%d) " % (self.control[0].name, self.control[1]) + string
[ "Print", "an", "if", "statement", "if", "needed", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L262-L266
[ "def", "_qasmif", "(", "self", ",", "string", ")", ":", "if", "self", ".", "control", "is", "None", ":", "return", "string", "return", "\"if(%s==%d) \"", "%", "(", "self", ".", "control", "[", "0", "]", ".", "name", ",", "self", ".", "control", "[", "1", "]", ")", "+", "string" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
Instruction.qasm
Return a default OpenQASM string for the instruction. Derived instructions may override this to print in a different format (e.g. measure q[0] -> c[0];).
qiskit/circuit/instruction.py
def qasm(self): """Return a default OpenQASM string for the instruction. Derived instructions may override this to print in a different format (e.g. measure q[0] -> c[0];). """ name_param = self.name if self.params: name_param = "%s(%s)" % (name_param, ",".join( [str(i) for i in self.params])) return self._qasmif(name_param)
def qasm(self): """Return a default OpenQASM string for the instruction. Derived instructions may override this to print in a different format (e.g. measure q[0] -> c[0];). """ name_param = self.name if self.params: name_param = "%s(%s)" % (name_param, ",".join( [str(i) for i in self.params])) return self._qasmif(name_param)
[ "Return", "a", "default", "OpenQASM", "string", "for", "the", "instruction", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/circuit/instruction.py#L268-L279
[ "def", "qasm", "(", "self", ")", ":", "name_param", "=", "self", ".", "name", "if", "self", ".", "params", ":", "name_param", "=", "\"%s(%s)\"", "%", "(", "name_param", ",", "\",\"", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "self", ".", "params", "]", ")", ")", "return", "self", ".", "_qasmif", "(", "name_param", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
PassManager._join_options
Set the options of each passset, based on precedence rules: passset options (set via ``PassManager.append()``) override passmanager options (set via ``PassManager.__init__()``), which override Default. .
qiskit/transpiler/passmanager.py
def _join_options(self, passset_options): """Set the options of each passset, based on precedence rules: passset options (set via ``PassManager.append()``) override passmanager options (set via ``PassManager.__init__()``), which override Default. . """ default = {'ignore_preserves': False, # Ignore preserves for this pass 'ignore_requires': False, # Ignore requires for this pass 'max_iteration': 1000} # Maximum allowed iteration on this pass passmanager_level = {k: v for k, v in self.passmanager_options.items() if v is not None} passset_level = {k: v for k, v in passset_options.items() if v is not None} return {**default, **passmanager_level, **passset_level}
def _join_options(self, passset_options): """Set the options of each passset, based on precedence rules: passset options (set via ``PassManager.append()``) override passmanager options (set via ``PassManager.__init__()``), which override Default. . """ default = {'ignore_preserves': False, # Ignore preserves for this pass 'ignore_requires': False, # Ignore requires for this pass 'max_iteration': 1000} # Maximum allowed iteration on this pass passmanager_level = {k: v for k, v in self.passmanager_options.items() if v is not None} passset_level = {k: v for k, v in passset_options.items() if v is not None} return {**default, **passmanager_level, **passset_level}
[ "Set", "the", "options", "of", "each", "passset", "based", "on", "precedence", "rules", ":", "passset", "options", "(", "set", "via", "PassManager", ".", "append", "()", ")", "override", "passmanager", "options", "(", "set", "via", "PassManager", ".", "__init__", "()", ")", "which", "override", "Default", ".", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L59-L71
[ "def", "_join_options", "(", "self", ",", "passset_options", ")", ":", "default", "=", "{", "'ignore_preserves'", ":", "False", ",", "# Ignore preserves for this pass", "'ignore_requires'", ":", "False", ",", "# Ignore requires for this pass", "'max_iteration'", ":", "1000", "}", "# Maximum allowed iteration on this pass", "passmanager_level", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "passmanager_options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "passset_level", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "passset_options", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "return", "{", "*", "*", "default", ",", "*", "*", "passmanager_level", ",", "*", "*", "passset_level", "}" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
PassManager.append
Args: passes (list[BasePass] or BasePass): pass(es) to be added to schedule ignore_preserves (bool): ignore the preserves claim of passes. Default: False ignore_requires (bool): ignore the requires need of passes. Default: False max_iteration (int): max number of iterations of passes. Default: 1000 flow_controller_conditions (kwargs): See add_flow_controller(): Dictionary of control flow plugins. Default: * do_while (callable property_set -> boolean): The passes repeat until the callable returns False. Default: `lambda x: False # i.e. passes run once` * condition (callable property_set -> boolean): The passes run only if the callable returns True. Default: `lambda x: True # i.e. passes run` Raises: TranspilerError: if a pass in passes is not a proper pass.
qiskit/transpiler/passmanager.py
def append(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None, **flow_controller_conditions): """ Args: passes (list[BasePass] or BasePass): pass(es) to be added to schedule ignore_preserves (bool): ignore the preserves claim of passes. Default: False ignore_requires (bool): ignore the requires need of passes. Default: False max_iteration (int): max number of iterations of passes. Default: 1000 flow_controller_conditions (kwargs): See add_flow_controller(): Dictionary of control flow plugins. Default: * do_while (callable property_set -> boolean): The passes repeat until the callable returns False. Default: `lambda x: False # i.e. passes run once` * condition (callable property_set -> boolean): The passes run only if the callable returns True. Default: `lambda x: True # i.e. passes run` Raises: TranspilerError: if a pass in passes is not a proper pass. """ passset_options = {'ignore_requires': ignore_requires, 'ignore_preserves': ignore_preserves, 'max_iteration': max_iteration} options = self._join_options(passset_options) if isinstance(passes, BasePass): passes = [passes] for pass_ in passes: if not isinstance(pass_, BasePass): raise TranspilerError('%s is not a pass instance' % pass_.__class__) for name, param in flow_controller_conditions.items(): if callable(param): flow_controller_conditions[name] = partial(param, self.fenced_property_set) else: raise TranspilerError('The flow controller parameter %s is not callable' % name) self.working_list.append( FlowController.controller_factory(passes, options, **flow_controller_conditions))
def append(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None, **flow_controller_conditions): """ Args: passes (list[BasePass] or BasePass): pass(es) to be added to schedule ignore_preserves (bool): ignore the preserves claim of passes. Default: False ignore_requires (bool): ignore the requires need of passes. Default: False max_iteration (int): max number of iterations of passes. Default: 1000 flow_controller_conditions (kwargs): See add_flow_controller(): Dictionary of control flow plugins. Default: * do_while (callable property_set -> boolean): The passes repeat until the callable returns False. Default: `lambda x: False # i.e. passes run once` * condition (callable property_set -> boolean): The passes run only if the callable returns True. Default: `lambda x: True # i.e. passes run` Raises: TranspilerError: if a pass in passes is not a proper pass. """ passset_options = {'ignore_requires': ignore_requires, 'ignore_preserves': ignore_preserves, 'max_iteration': max_iteration} options = self._join_options(passset_options) if isinstance(passes, BasePass): passes = [passes] for pass_ in passes: if not isinstance(pass_, BasePass): raise TranspilerError('%s is not a pass instance' % pass_.__class__) for name, param in flow_controller_conditions.items(): if callable(param): flow_controller_conditions[name] = partial(param, self.fenced_property_set) else: raise TranspilerError('The flow controller parameter %s is not callable' % name) self.working_list.append( FlowController.controller_factory(passes, options, **flow_controller_conditions))
[ "Args", ":", "passes", "(", "list", "[", "BasePass", "]", "or", "BasePass", ")", ":", "pass", "(", "es", ")", "to", "be", "added", "to", "schedule", "ignore_preserves", "(", "bool", ")", ":", "ignore", "the", "preserves", "claim", "of", "passes", ".", "Default", ":", "False", "ignore_requires", "(", "bool", ")", ":", "ignore", "the", "requires", "need", "of", "passes", ".", "Default", ":", "False", "max_iteration", "(", "int", ")", ":", "max", "number", "of", "iterations", "of", "passes", ".", "Default", ":", "1000", "flow_controller_conditions", "(", "kwargs", ")", ":", "See", "add_flow_controller", "()", ":", "Dictionary", "of", "control", "flow", "plugins", ".", "Default", ":" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L73-L116
[ "def", "append", "(", "self", ",", "passes", ",", "ignore_requires", "=", "None", ",", "ignore_preserves", "=", "None", ",", "max_iteration", "=", "None", ",", "*", "*", "flow_controller_conditions", ")", ":", "passset_options", "=", "{", "'ignore_requires'", ":", "ignore_requires", ",", "'ignore_preserves'", ":", "ignore_preserves", ",", "'max_iteration'", ":", "max_iteration", "}", "options", "=", "self", ".", "_join_options", "(", "passset_options", ")", "if", "isinstance", "(", "passes", ",", "BasePass", ")", ":", "passes", "=", "[", "passes", "]", "for", "pass_", "in", "passes", ":", "if", "not", "isinstance", "(", "pass_", ",", "BasePass", ")", ":", "raise", "TranspilerError", "(", "'%s is not a pass instance'", "%", "pass_", ".", "__class__", ")", "for", "name", ",", "param", "in", "flow_controller_conditions", ".", "items", "(", ")", ":", "if", "callable", "(", "param", ")", ":", "flow_controller_conditions", "[", "name", "]", "=", "partial", "(", "param", ",", "self", ".", "fenced_property_set", ")", "else", ":", "raise", "TranspilerError", "(", "'The flow controller parameter %s is not callable'", "%", "name", ")", "self", ".", "working_list", ".", "append", "(", "FlowController", ".", "controller_factory", "(", "passes", ",", "options", ",", "*", "*", "flow_controller_conditions", ")", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
PassManager.run
Run all the passes on a QuantumCircuit Args: circuit (QuantumCircuit): circuit to transform via all the registered passes Returns: QuantumCircuit: Transformed circuit.
qiskit/transpiler/passmanager.py
def run(self, circuit): """Run all the passes on a QuantumCircuit Args: circuit (QuantumCircuit): circuit to transform via all the registered passes Returns: QuantumCircuit: Transformed circuit. """ name = circuit.name dag = circuit_to_dag(circuit) del circuit for passset in self.working_list: for pass_ in passset: dag = self._do_pass(pass_, dag, passset.options) circuit = dag_to_circuit(dag) circuit.name = name return circuit
def run(self, circuit): """Run all the passes on a QuantumCircuit Args: circuit (QuantumCircuit): circuit to transform via all the registered passes Returns: QuantumCircuit: Transformed circuit. """ name = circuit.name dag = circuit_to_dag(circuit) del circuit for passset in self.working_list: for pass_ in passset: dag = self._do_pass(pass_, dag, passset.options) circuit = dag_to_circuit(dag) circuit.name = name return circuit
[ "Run", "all", "the", "passes", "on", "a", "QuantumCircuit" ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L118-L135
[ "def", "run", "(", "self", ",", "circuit", ")", ":", "name", "=", "circuit", ".", "name", "dag", "=", "circuit_to_dag", "(", "circuit", ")", "del", "circuit", "for", "passset", "in", "self", ".", "working_list", ":", "for", "pass_", "in", "passset", ":", "dag", "=", "self", ".", "_do_pass", "(", "pass_", ",", "dag", ",", "passset", ".", "options", ")", "circuit", "=", "dag_to_circuit", "(", "dag", ")", "circuit", ".", "name", "=", "name", "return", "circuit" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
PassManager._do_pass
Do a pass and its "requires". Args: pass_ (BasePass): Pass to do. dag (DAGCircuit): The dag on which the pass is ran. options (dict): PassManager options. Returns: DAGCircuit: The transformed dag in case of a transformation pass. The same input dag in case of an analysis pass. Raises: TranspilerError: If the pass is not a proper pass instance.
qiskit/transpiler/passmanager.py
def _do_pass(self, pass_, dag, options): """Do a pass and its "requires". Args: pass_ (BasePass): Pass to do. dag (DAGCircuit): The dag on which the pass is ran. options (dict): PassManager options. Returns: DAGCircuit: The transformed dag in case of a transformation pass. The same input dag in case of an analysis pass. Raises: TranspilerError: If the pass is not a proper pass instance. """ # First, do the requires of pass_ if not options["ignore_requires"]: for required_pass in pass_.requires: dag = self._do_pass(required_pass, dag, options) # Run the pass itself, if not already run if pass_ not in self.valid_passes: if pass_.is_transformation_pass: pass_.property_set = self.fenced_property_set new_dag = pass_.run(dag) if not isinstance(new_dag, DAGCircuit): raise TranspilerError("Transformation passes should return a transformed dag." "The pass %s is returning a %s" % (type(pass_).__name__, type(new_dag))) dag = new_dag elif pass_.is_analysis_pass: pass_.property_set = self.property_set pass_.run(FencedDAGCircuit(dag)) else: raise TranspilerError("I dont know how to handle this type of pass") # update the valid_passes property self._update_valid_passes(pass_, options['ignore_preserves']) return dag
def _do_pass(self, pass_, dag, options): """Do a pass and its "requires". Args: pass_ (BasePass): Pass to do. dag (DAGCircuit): The dag on which the pass is ran. options (dict): PassManager options. Returns: DAGCircuit: The transformed dag in case of a transformation pass. The same input dag in case of an analysis pass. Raises: TranspilerError: If the pass is not a proper pass instance. """ # First, do the requires of pass_ if not options["ignore_requires"]: for required_pass in pass_.requires: dag = self._do_pass(required_pass, dag, options) # Run the pass itself, if not already run if pass_ not in self.valid_passes: if pass_.is_transformation_pass: pass_.property_set = self.fenced_property_set new_dag = pass_.run(dag) if not isinstance(new_dag, DAGCircuit): raise TranspilerError("Transformation passes should return a transformed dag." "The pass %s is returning a %s" % (type(pass_).__name__, type(new_dag))) dag = new_dag elif pass_.is_analysis_pass: pass_.property_set = self.property_set pass_.run(FencedDAGCircuit(dag)) else: raise TranspilerError("I dont know how to handle this type of pass") # update the valid_passes property self._update_valid_passes(pass_, options['ignore_preserves']) return dag
[ "Do", "a", "pass", "and", "its", "requires", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L137-L175
[ "def", "_do_pass", "(", "self", ",", "pass_", ",", "dag", ",", "options", ")", ":", "# First, do the requires of pass_", "if", "not", "options", "[", "\"ignore_requires\"", "]", ":", "for", "required_pass", "in", "pass_", ".", "requires", ":", "dag", "=", "self", ".", "_do_pass", "(", "required_pass", ",", "dag", ",", "options", ")", "# Run the pass itself, if not already run", "if", "pass_", "not", "in", "self", ".", "valid_passes", ":", "if", "pass_", ".", "is_transformation_pass", ":", "pass_", ".", "property_set", "=", "self", ".", "fenced_property_set", "new_dag", "=", "pass_", ".", "run", "(", "dag", ")", "if", "not", "isinstance", "(", "new_dag", ",", "DAGCircuit", ")", ":", "raise", "TranspilerError", "(", "\"Transformation passes should return a transformed dag.\"", "\"The pass %s is returning a %s\"", "%", "(", "type", "(", "pass_", ")", ".", "__name__", ",", "type", "(", "new_dag", ")", ")", ")", "dag", "=", "new_dag", "elif", "pass_", ".", "is_analysis_pass", ":", "pass_", ".", "property_set", "=", "self", ".", "property_set", "pass_", ".", "run", "(", "FencedDAGCircuit", "(", "dag", ")", ")", "else", ":", "raise", "TranspilerError", "(", "\"I dont know how to handle this type of pass\"", ")", "# update the valid_passes property", "self", ".", "_update_valid_passes", "(", "pass_", ",", "options", "[", "'ignore_preserves'", "]", ")", "return", "dag" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
PassManager.passes
Returns a list structure of the appended passes and its options. Returns (list): The appended passes.
qiskit/transpiler/passmanager.py
def passes(self): """ Returns a list structure of the appended passes and its options. Returns (list): The appended passes. """ ret = [] for pass_ in self.working_list: ret.append(pass_.dump_passes()) return ret
def passes(self): """ Returns a list structure of the appended passes and its options. Returns (list): The appended passes. """ ret = [] for pass_ in self.working_list: ret.append(pass_.dump_passes()) return ret
[ "Returns", "a", "list", "structure", "of", "the", "appended", "passes", "and", "its", "options", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L185-L194
[ "def", "passes", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "pass_", "in", "self", ".", "working_list", ":", "ret", ".", "append", "(", "pass_", ".", "dump_passes", "(", ")", ")", "return", "ret" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
FlowController.dump_passes
Fetches the passes added to this flow controller. Returns (dict): {'options': self.options, 'passes': [passes], 'type': type(self)}
qiskit/transpiler/passmanager.py
def dump_passes(self): """ Fetches the passes added to this flow controller. Returns (dict): {'options': self.options, 'passes': [passes], 'type': type(self)} """ ret = {'options': self.options, 'passes': [], 'type': type(self)} for pass_ in self._passes: if isinstance(pass_, FlowController): ret['passes'].append(pass_.dump_passes()) else: ret['passes'].append(pass_) return ret
def dump_passes(self): """ Fetches the passes added to this flow controller. Returns (dict): {'options': self.options, 'passes': [passes], 'type': type(self)} """ ret = {'options': self.options, 'passes': [], 'type': type(self)} for pass_ in self._passes: if isinstance(pass_, FlowController): ret['passes'].append(pass_.dump_passes()) else: ret['passes'].append(pass_) return ret
[ "Fetches", "the", "passes", "added", "to", "this", "flow", "controller", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L212-L224
[ "def", "dump_passes", "(", "self", ")", ":", "ret", "=", "{", "'options'", ":", "self", ".", "options", ",", "'passes'", ":", "[", "]", ",", "'type'", ":", "type", "(", "self", ")", "}", "for", "pass_", "in", "self", ".", "_passes", ":", "if", "isinstance", "(", "pass_", ",", "FlowController", ")", ":", "ret", "[", "'passes'", "]", ".", "append", "(", "pass_", ".", "dump_passes", "(", ")", ")", "else", ":", "ret", "[", "'passes'", "]", ".", "append", "(", "pass_", ")", "return", "ret" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
FlowController.remove_flow_controller
Removes a flow controller. Args: name (string): Name of the controller to remove. Raises: KeyError: If the controller to remove was not registered.
qiskit/transpiler/passmanager.py
def remove_flow_controller(cls, name): """ Removes a flow controller. Args: name (string): Name of the controller to remove. Raises: KeyError: If the controller to remove was not registered. """ if name not in cls.registered_controllers: raise KeyError("Flow controller not found: %s" % name) del cls.registered_controllers[name]
def remove_flow_controller(cls, name): """ Removes a flow controller. Args: name (string): Name of the controller to remove. Raises: KeyError: If the controller to remove was not registered. """ if name not in cls.registered_controllers: raise KeyError("Flow controller not found: %s" % name) del cls.registered_controllers[name]
[ "Removes", "a", "flow", "controller", ".", "Args", ":", "name", "(", "string", ")", ":", "Name", "of", "the", "controller", "to", "remove", ".", "Raises", ":", "KeyError", ":", "If", "the", "controller", "to", "remove", "was", "not", "registered", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L237-L247
[ "def", "remove_flow_controller", "(", "cls", ",", "name", ")", ":", "if", "name", "not", "in", "cls", ".", "registered_controllers", ":", "raise", "KeyError", "(", "\"Flow controller not found: %s\"", "%", "name", ")", "del", "cls", ".", "registered_controllers", "[", "name", "]" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
FlowController.controller_factory
Constructs a flow controller based on the partially evaluated controller arguments. Args: passes (list[BasePass]): passes to add to the flow controller. options (dict): PassManager options. **partial_controller (dict): Partially evaluated controller arguments in the form `{name:partial}` Raises: TranspilerError: When partial_controller is not well-formed. Returns: FlowController: A FlowController instance.
qiskit/transpiler/passmanager.py
def controller_factory(cls, passes, options, **partial_controller): """ Constructs a flow controller based on the partially evaluated controller arguments. Args: passes (list[BasePass]): passes to add to the flow controller. options (dict): PassManager options. **partial_controller (dict): Partially evaluated controller arguments in the form `{name:partial}` Raises: TranspilerError: When partial_controller is not well-formed. Returns: FlowController: A FlowController instance. """ if None in partial_controller.values(): raise TranspilerError('The controller needs a condition.') if partial_controller: for registered_controller in cls.registered_controllers.keys(): if registered_controller in partial_controller: return cls.registered_controllers[registered_controller](passes, options, **partial_controller) raise TranspilerError("The controllers for %s are not registered" % partial_controller) else: return FlowControllerLinear(passes, options)
def controller_factory(cls, passes, options, **partial_controller): """ Constructs a flow controller based on the partially evaluated controller arguments. Args: passes (list[BasePass]): passes to add to the flow controller. options (dict): PassManager options. **partial_controller (dict): Partially evaluated controller arguments in the form `{name:partial}` Raises: TranspilerError: When partial_controller is not well-formed. Returns: FlowController: A FlowController instance. """ if None in partial_controller.values(): raise TranspilerError('The controller needs a condition.') if partial_controller: for registered_controller in cls.registered_controllers.keys(): if registered_controller in partial_controller: return cls.registered_controllers[registered_controller](passes, options, **partial_controller) raise TranspilerError("The controllers for %s are not registered" % partial_controller) else: return FlowControllerLinear(passes, options)
[ "Constructs", "a", "flow", "controller", "based", "on", "the", "partially", "evaluated", "controller", "arguments", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passmanager.py#L250-L276
[ "def", "controller_factory", "(", "cls", ",", "passes", ",", "options", ",", "*", "*", "partial_controller", ")", ":", "if", "None", "in", "partial_controller", ".", "values", "(", ")", ":", "raise", "TranspilerError", "(", "'The controller needs a condition.'", ")", "if", "partial_controller", ":", "for", "registered_controller", "in", "cls", ".", "registered_controllers", ".", "keys", "(", ")", ":", "if", "registered_controller", "in", "partial_controller", ":", "return", "cls", ".", "registered_controllers", "[", "registered_controller", "]", "(", "passes", ",", "options", ",", "*", "*", "partial_controller", ")", "raise", "TranspilerError", "(", "\"The controllers for %s are not registered\"", "%", "partial_controller", ")", "else", ":", "return", "FlowControllerLinear", "(", "passes", ",", "options", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
u_base
Apply U to q.
qiskit/extensions/standard/ubase.py
def u_base(self, theta, phi, lam, q): """Apply U to q.""" return self.append(UBase(theta, phi, lam), [q], [])
def u_base(self, theta, phi, lam, q): """Apply U to q.""" return self.append(UBase(theta, phi, lam), [q], [])
[ "Apply", "U", "to", "q", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/ubase.py#L50-L52
[ "def", "u_base", "(", "self", ",", "theta", ",", "phi", ",", "lam", ",", "q", ")", ":", "return", "self", ".", "append", "(", "UBase", "(", "theta", ",", "phi", ",", "lam", ")", ",", "[", "q", "]", ",", "[", "]", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
UBase.to_matrix
Return a Numpy.array for the U3 gate.
qiskit/extensions/standard/ubase.py
def to_matrix(self): """Return a Numpy.array for the U3 gate.""" theta, phi, lam = self.params return numpy.array( [[ numpy.cos(theta / 2), -numpy.exp(1j * lam) * numpy.sin(theta / 2) ], [ numpy.exp(1j * phi) * numpy.sin(theta / 2), numpy.exp(1j * (phi + lam)) * numpy.cos(theta / 2) ]], dtype=complex)
def to_matrix(self): """Return a Numpy.array for the U3 gate.""" theta, phi, lam = self.params return numpy.array( [[ numpy.cos(theta / 2), -numpy.exp(1j * lam) * numpy.sin(theta / 2) ], [ numpy.exp(1j * phi) * numpy.sin(theta / 2), numpy.exp(1j * (phi + lam)) * numpy.cos(theta / 2) ]], dtype=complex)
[ "Return", "a", "Numpy", ".", "array", "for", "the", "U3", "gate", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/ubase.py#L33-L45
[ "def", "to_matrix", "(", "self", ")", ":", "theta", ",", "phi", ",", "lam", "=", "self", ".", "params", "return", "numpy", ".", "array", "(", "[", "[", "numpy", ".", "cos", "(", "theta", "/", "2", ")", ",", "-", "numpy", ".", "exp", "(", "1j", "*", "lam", ")", "*", "numpy", ".", "sin", "(", "theta", "/", "2", ")", "]", ",", "[", "numpy", ".", "exp", "(", "1j", "*", "phi", ")", "*", "numpy", ".", "sin", "(", "theta", "/", "2", ")", ",", "numpy", ".", "exp", "(", "1j", "*", "(", "phi", "+", "lam", ")", ")", "*", "numpy", ".", "cos", "(", "theta", "/", "2", ")", "]", "]", ",", "dtype", "=", "complex", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1
test
single_gate_params
Apply a single qubit gate to the qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: tuple: a tuple of U gate parameters (theta, phi, lam) Raises: QiskitError: if the gate name is not valid
qiskit/providers/basicaer/basicaertools.py
def single_gate_params(gate, params=None): """Apply a single qubit gate to the qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: tuple: a tuple of U gate parameters (theta, phi, lam) Raises: QiskitError: if the gate name is not valid """ if gate in ('U', 'u3'): return params[0], params[1], params[2] elif gate == 'u2': return np.pi / 2, params[0], params[1] elif gate == 'u1': return 0, 0, params[0] elif gate == 'id': return 0, 0, 0 raise QiskitError('Gate is not among the valid types: %s' % gate)
def single_gate_params(gate, params=None): """Apply a single qubit gate to the qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: tuple: a tuple of U gate parameters (theta, phi, lam) Raises: QiskitError: if the gate name is not valid """ if gate in ('U', 'u3'): return params[0], params[1], params[2] elif gate == 'u2': return np.pi / 2, params[0], params[1] elif gate == 'u1': return 0, 0, params[0] elif gate == 'id': return 0, 0, 0 raise QiskitError('Gate is not among the valid types: %s' % gate)
[ "Apply", "a", "single", "qubit", "gate", "to", "the", "qubit", "." ]
Qiskit/qiskit-terra
python
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L19-L38
[ "def", "single_gate_params", "(", "gate", ",", "params", "=", "None", ")", ":", "if", "gate", "in", "(", "'U'", ",", "'u3'", ")", ":", "return", "params", "[", "0", "]", ",", "params", "[", "1", "]", ",", "params", "[", "2", "]", "elif", "gate", "==", "'u2'", ":", "return", "np", ".", "pi", "/", "2", ",", "params", "[", "0", "]", ",", "params", "[", "1", "]", "elif", "gate", "==", "'u1'", ":", "return", "0", ",", "0", ",", "params", "[", "0", "]", "elif", "gate", "==", "'id'", ":", "return", "0", ",", "0", ",", "0", "raise", "QiskitError", "(", "'Gate is not among the valid types: %s'", "%", "gate", ")" ]
d4f58d903bc96341b816f7c35df936d6421267d1