INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Add additional requirements from setup. cfg to file metadata_path | 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' i... |
Convert an. egg - info directory into a. dist - info directory | 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... |
GetConversations. | 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 ... |
CreateConversation. | 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 me... |
GetConversationPagedMembers. | 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. ... |
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 th... | 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... |
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 cli... | 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: th... |
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 m... | 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 poi... |
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.: ... | 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 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... | 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... |
Returns a simple text 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 ... |
Returns a message that includes a set of suggested actions and optional text. | 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:
messa... |
Returns a single message activity containing an attachment. | 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='... |
Returns a message that will display a set of attachments in list form. | 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(Her... |
Returns a message that will display a single image or video to a user. | 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('... |
Validate the incoming Auth Header | 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 Fra... |
Validate the incoming Auth Header | 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... |
Creates a trace activity based on this activity. | 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
:para... |
Adds a new dialog to the set and returns the added dialog.: param dialog: The dialog to add. | 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 ... |
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. | 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 TypeErro... |
Returns the storage key for the current user state.: param context:: return: | 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_prop... |
Return the top scoring intent and its score.: return: Intent and score.: rtype: TopIntent | 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=""... |
Sets the telemetry client for logging events. | 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 |
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... | 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 au... |
Initializes a new instance of the <see cref = LuisApplication/ > class.: param application_endpoint: LUIS application endpoint.: type application_endpoint: str: return:: rtype: LuisApplication | 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
"""
... |
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 i... | 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 defau... |
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 N... | 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: Conte... |
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... | 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 recognize... |
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 ... | 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 t... |
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 formda... | 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.
... |
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 | 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 ... |
Async Generator for streaming request body data.: param response: The initial response: param user_callback: Custom callback for monitoring progress. | 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 Str... |
Read storeitems from storage. | 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_contain... |
Save storeitems to storage. | 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_cont... |
Remove storeitems from storage. | 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()
... |
Create a StoreItem from a result out of CosmosDB. | 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
... |
Return the dict of a StoreItem. | 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 at... |
Return the sanitized 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 wit... |
Call the get or create methods. | 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, con... |
Return the database link. | 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.... |
Return the container link. | 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 th... |
Fills the event properties and metrics for the QnaMessage event for telemetry. | 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 tel... |
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 ] | 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.
:retu... |
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 () | 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 opti... |
Called when this TurnContext instance is passed into the constructor of a new TurnContext instance. Can be overridden in derived classes.: param context:: return: | 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', '... |
Used to set TurnContext. _activity when a context object is created. Only takes instances of Activities.: param value:: return: | 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 ... |
Returns True is set () has been called for a key. The cached value may be of type None.: param key:: return: | 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 |
Caches a value for the lifetime of the current turn.: param key:: param value:: return: | 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._servi... |
Sends a single activity or message to the user.: param activity_or_text:: return: | 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 = [TurnC... |
Replaces an existing activity.: param activity:: return: | 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)) |
Deletes an existing activity.: param id_or_reference:: return: | 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)
... |
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. | 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_conve... |
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: | 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... |
Adds a new step to the waterfall.: param step: Step to add: return: Waterfall dialog for fluent calls to add_step (). | 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.... |
Give the waterfall step a unique 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 |
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 w... | 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.
:... |
Utility function to calculate a change hash for a StoreItem.: param item:: return: | 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) |
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. | 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)... |
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: | 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: Co... |
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: | 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... |
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 paren... | 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 ... |
Deletes any existing dialog stack thus cancelling all dialogs on the stack.: param result: ( Optional ) result to pass to the parent dialogs.: return: | 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):
... |
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: | 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... |
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: | 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.
... |
Calls reprompt on the currently active dialog if there is one. Used with Prompts that have a reprompt behavior.: return: | 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
dia... |
Determine if a number of Suggested Actions are supported by a Channel. | 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 ... |
Determine if a number of Card Actions are supported by a Channel. | 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 num... |
Get the Channel Id from the current Activity on the Turn Context. | 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... |
Begins listening to console input.: param logic:: return: | 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
... |
Logs a series of activities to the console.: param context:: param activities:: return: | 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(): `c... |
Determines if a given Auth header is from the Bot Framework Emulator | 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. Otherwis... |
Validate the incoming Auth Header | 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 ... |
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: | 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 ... |
Returns an attachment for an animation card. Will raise a TypeError if the card argument is not an AnimationCard.: param card:: return: | 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 TypeE... |
Returns an attachment for an audio card. Will raise a TypeError if card argument is not an AudioCard.: param card:: return: | 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(): ... |
Returns an attachment for a hero card. Will raise a TypeError if card argument is not a HeroCard. | 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:
... |
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: | 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, OAut... |
Returns an attachment for a receipt card. Will raise a TypeError if card argument is not a ReceiptCard.: param card:: return: | 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.receip... |
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: | 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:
... |
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 ... | 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 i... |
Returns an attachment for a video card. Will raise a TypeError if card argument is not a VideoCard.: param card:: return: | 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(): `c... |
return instruction 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.param... |
Assemble a QasmQobjInstruction | 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 = [
... |
For a composite instruction reverse the order of sub - gates. | 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:... |
Invert this instruction. | 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.)
Re... |
Add classical control on register classical and value val. | 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-ne... |
shallow copy of the instruction. | 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
upda... |
Print an if statement if needed. | 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 |
Return a default OpenQASM string for the instruction. | 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, ",".jo... |
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.. | 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_... |
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_c... | 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. D... |
Run all the passes on a QuantumCircuit | 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(circui... |
Do a pass and its requires. | 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... |
Returns a list structure of the appended passes and its options. | 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 |
Fetches the passes added to this flow controller. | 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 ... |
Removes a flow controller. Args: name ( string ): Name of the controller to remove. Raises: KeyError: If the controller to remove was not registered. | 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:
... |
Constructs a flow controller based on the partially evaluated controller arguments. | 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.
... |
Apply U to q. | def u_base(self, theta, phi, lam, q):
"""Apply U to q."""
return self.append(UBase(theta, phi, lam), [q], []) |
Return a Numpy. array for the U3 gate. | 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) *... |
Apply a single qubit gate to the qubit. | 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 th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.