text
stringlengths 5
22M
| id
stringlengths 12
177
| metadata
dict | __index_level_0__
int64 0
1.37k
|
---|---|---|---|
#!/bin/env python
# -*- coding: utf-8 -*-
##
# resource_estimator.py: Qiskit result for microsoft.estimator target.
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
from azure.quantum.target.microsoft import MicrosoftEstimatorResult
def make_estimator_result(data):
if not data["success"]:
error_data = data["error_data"]
message = "Cannot retrieve results as job execution failed " \
f"({error_data['code']}: {error_data['message']})"
raise RuntimeError(message)
results = data["results"]
if len(results) == 1:
data = results[0]['data']
return MicrosoftEstimatorResult(data)
else:
raise ValueError("Expected Qiskit results for RE be of length 1")
|
azure-quantum-python/azure-quantum/azure/quantum/qiskit/results/resource_estimator.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/qiskit/results/resource_estimator.py",
"repo_id": "azure-quantum-python",
"token_count": 294
}
| 407 |
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from typing import Any, Dict
from warnings import warn
from azure.quantum.target.target import (
Target,
_determine_shots_or_deprecated_num_shots,
)
from azure.quantum.job.job import Job
from azure.quantum.workspace import Workspace
from azure.quantum._client.models import CostEstimate, UsageEvent
class Quantinuum(Target):
"""Quantinuum target."""
target_names = (
# Note: Target names on the same line are equivalent.
"quantinuum.qpu.h1-1",
"quantinuum.sim.h1-1sc",
"quantinuum.sim.h1-1e",
"quantinuum.qpu.h2-1",
"quantinuum.sim.h2-1sc",
"quantinuum.sim.h2-1e",
)
_SHOTS_PARAM_NAME = "count"
def __init__(
self,
workspace: Workspace,
name: str = "quantinuum.sim.h1-1sc",
input_data_format: str = "honeywell.openqasm.v1",
output_data_format: str = "honeywell.quantum-results.v1",
capability: str = "AdaptiveExecution",
provider_id: str = "quantinuum",
content_type: str = "application/qasm",
encoding: str = "",
**kwargs
):
super().__init__(
workspace=workspace,
name=name,
input_data_format=input_data_format,
output_data_format=output_data_format,
capability=capability,
provider_id=provider_id,
content_type=content_type,
encoding=encoding,
**kwargs
)
def submit(
self,
circuit: str = None,
name: str = "quantinuum-job",
shots: int = None,
input_params: Dict[str, Any] = None,
**kwargs
) -> Job:
"""Submit a Quantinuum program (OpenQASM 2.0 format)
:param circuit: Quantum circuit in Quantinuum OpenQASM 2.0 format
:type circuit: str
:param name: Job name
:type name: str
:param shots: Number of shots, defaults to None
:type shots: int
:param input_params: Optional input params dict
:type input_params: Dict[str, Any]
:return: Azure Quantum job
:rtype: Job
"""
input_data = kwargs.pop("input_data", circuit)
if input_data is None:
raise ValueError(
"Either the `circuit` parameter or the `input_data` parameter must have a value."
)
if input_params is None:
input_params = {}
num_shots = kwargs.pop("num_shots", None)
shots = _determine_shots_or_deprecated_num_shots(
shots=shots,
num_shots=num_shots,
)
return super().submit(
input_data=input_data,
name=name,
shots=shots,
input_params=input_params,
**kwargs
)
def estimate_cost(
self,
circuit: str = None,
num_shots: int = None,
N_1q: int = None,
N_2q: int = None,
N_m: int = None,
shots: int = None,
) -> CostEstimate:
"""Estimate the cost in HQC for a given circuit.
Optionally, you can provide the number of gate and measurement operations
manually.
The actual price charged by the provider may differ from this estimation.
For the most current pricing details, see
https://aka.ms/AQ/Quantinuum/Documentation
Or find your workspace and view pricing options in the "Provider" tab
of your workspace: https://aka.ms/aq/myworkspaces
:param circuit: Quantum circuit in OpenQASM 2.0 format
:type circuit: str
:param num_shots: Number of shots for which to estimate costs
:type num_shots: int
:param N_1q: Number of one-qubit gates, if not specified,
this is estimated from the circuit
:type N_1q: int
:param N_2q: Number of two-qubit gates, if not specified,
this is estimated from the circuit
:type N_2q: int
:param N_m: Number of measurement operations, if not specified,
this is estimated from the circuit
:type N_m: int
:param shots: Number of shots for which to estimate costs
:type shots: int
:raises ImportError: If N_1q, N_2q and N_m are not specified,
this will require a qiskit installation.
"""
if num_shots is None and shots is None:
raise ValueError("The 'shots' parameter has to be specified")
if num_shots is not None:
warn(
"The 'num_shots' parameter will be deprecated. Please, use 'shots' parameter instead.",
category=DeprecationWarning,
)
shots = num_shots
if circuit is not None and (N_1q is None or N_2q is None or N_m is None):
try:
from qiskit.qasm2 import loads
from qiskit.converters.circuit_to_dag import circuit_to_dag
except ImportError:
raise ImportError(
"Missing dependency qiskit. Please run `pip install azure-quantum[qiskit]` " \
"to estimate the circuit cost. Alternatively, specify the number of one-qubit and two-qubit " \
"gates in the method input arguments.")
else:
from qiskit.dagcircuit.dagnode import DAGOpNode
circuit_obj = loads(string=circuit)
dag = circuit_to_dag(circuit=circuit_obj)
N_1q, N_2q, N_m = 0, 0, 0
for node in dag._multi_graph.nodes():
if isinstance(node, DAGOpNode):
if node.op.name in ["measure", "reset"]:
N_m += 1
elif node.op.num_qubits == 1:
N_1q += 1
else:
N_2q += 1
import re
is_emulator_regex = re.compile("^.*(-sim|-[0-9]*e)$")
is_syntax_checker_regex = re.compile("^.*(-apival|-[0-9]*sc)$")
if is_emulator_regex.match(self.name):
currency_code = "EHQC"
else:
currency_code = "HQC"
if is_syntax_checker_regex.match(self.name):
HQC = 0.0
else:
HQC = 5 + shots * (N_1q + 10 * N_2q + 5 * N_m) / 5000
return CostEstimate(
events=[
UsageEvent(
dimension_id="gates1q",
dimension_name="1Q Gates",
measure_unit="1q gates",
amount_billed=0.0,
amount_consumed=N_1q,
unit_price=0.0
),
UsageEvent(
dimension_id="gates2q",
dimension_name="2Q Gates",
measure_unit="2q gates",
amount_billed=0.0,
amount_consumed=N_2q,
unit_price=0.0
),
UsageEvent(
dimension_id="measops",
dimension_name="Measurement operations",
measure_unit="measurement operations",
amount_billed=0.0,
amount_consumed=N_m,
unit_price=0.0
)
],
currency_code=currency_code,
estimated_total=HQC
)
|
azure-quantum-python/azure-quantum/azure/quantum/target/quantinuum.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/target/quantinuum.py",
"repo_id": "azure-quantum-python",
"token_count": 3744
}
| 408 |
open Microsoft.Quantum.Arithmetic;
@EntryPoint()
operation EstimateMultiplier(bitwidth : Int) : Unit {
use xs = Qubit[bitwidth];
use ys = Qubit[bitwidth];
use zs = Qubit[2 * bitwidth];
MultiplyI(LittleEndian(xs), LittleEndian(ys), LittleEndian(zs));
}
|
azure-quantum-python/azure-quantum/examples/resource_estimation/cli_test_files/multiplier.qs/0
|
{
"file_path": "azure-quantum-python/azure-quantum/examples/resource_estimation/cli_test_files/multiplier.qs",
"repo_id": "azure-quantum-python",
"token_count": 109
}
| 409 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
import re
import os
import json
import time
from unittest.mock import patch
from vcr.request import Request as VcrRequest
from azure_devtools.scenario_tests.base import ReplayableTest
from azure_devtools.scenario_tests.recording_processors import (
RecordingProcessor,
is_text_payload,
)
from azure.quantum import Workspace
from azure.quantum._workspace_connection_params import (
WorkspaceConnectionParams,
)
from azure.quantum._constants import (
EnvironmentVariables,
ConnectionConstants,
GUID_REGEX_PATTERN,
)
from azure.quantum import Job
from azure.quantum.target import Target
from azure.identity import ClientSecretCredential
ZERO_UID = "00000000-0000-0000-0000-000000000000"
ONE_UID = "00000000-0000-0000-0000-000000000001"
TENANT_ID = "72f988bf-86f1-41af-91ab-2d7cd011db47"
PLACEHOLDER = "PLACEHOLDER"
SUBSCRIPTION_ID = "11111111-2222-3333-4444-555555555555"
RESOURCE_GROUP = "myresourcegroup"
WORKSPACE = "myworkspace"
LOCATION = "eastus"
STORAGE = "mystorage"
API_KEY = "myapikey"
APP_ID = "testapp"
DEFAULT_TIMEOUT_SECS = 300
AUTH_URL = "https://login.microsoftonline.com/"
GUID_REGEX_CAPTURE = f"(?P<guid>{GUID_REGEX_PATTERN})"
class RegexScrubbingPatterns:
URL_PATH_SUBSCRIPTION_ID = f"/subscriptions/{GUID_REGEX_CAPTURE}"
DATE_TIME = r"\d{8}-\d{6}"
URL_PATH_BLOB_GUID = f'blob.core.windows.net/{GUID_REGEX_CAPTURE}'
URL_PATH_RESOURCE_GROUP = r"/resourceGroups/[a-z0-9-]+/"
URL_PATH_WORKSPACE_NAME = r"/workspaces/[a-z0-9-]+/"
URL_STORAGE_ACCOUNT = r"https://[^\.]+.blob.core.windows.net"
URL_QUANTUM_ENDPOINT = r"https://[^\.]+.quantum(-test)?.azure.com/"
URL_OAUTH_ENDPOINT = \
f"https://login.(microsoftonline.com|windows-ppe.net)/{GUID_REGEX_CAPTURE}/oauth2/.*"
URL_QUERY_SAS_KEY_SIGNATURE = r"sig=[^&]+\&"
URL_QUERY_SAS_KEY_VALUE = r"sv=[^&]+\&"
URL_QUERY_SAS_KEY_EXPIRATION = r"se=[^&]+\&"
URL_QUERY_AUTH_CLIENT_ID = r"client_id=[^&]+\&"
URL_QUERY_AUTH_CLIENT_SECRET = r"client_secret=[^&]+\&"
URL_QUERY_AUTH_CLIENT_ASSERTION = r"client_assertion=[^&]+\&"
URL_QUERY_AUTH_CLIENT_ASSERTION_TYPE = r"client_assertion_type=[^&]+\&"
URL_QUERY_AUTH_CLAIMS = r"claims=[^&]+\&"
URL_QUERY_AUTH_CODE_VERIFIER = r"code_verifier=[^&]+\&"
URL_QUERY_AUTH_CODE = r"code=[^&]+\&"
URL_HTTP = r"http://" # Devskim: ignore DS137138
class QuantumTestBase(ReplayableTest):
"""QuantumTestBase
During init, gets Azure Credentials and
Azure Quantum Workspace parameters from OS environment variables.
"""
def __init__(self, method_name):
connection_params = WorkspaceConnectionParams.from_env_vars()
connection_params.apply_defaults(
client_id=ZERO_UID,
tenant_id=TENANT_ID,
resource_group=RESOURCE_GROUP,
subscription_id=SUBSCRIPTION_ID,
workspace_name=WORKSPACE,
location=LOCATION,
user_agent_app_id=APP_ID,
)
self.connection_params = connection_params
self._client_secret = os.environ.get(EnvironmentVariables.AZURE_CLIENT_SECRET, PLACEHOLDER)
self._regex_replacer = CustomRecordingProcessor(self)
recording_processors = [
AuthenticationMetadataFilter(),
self._regex_replacer,
CustomAccessTokenReplacer(),
]
replay_processors = [
AuthenticationMetadataFilter(),
self._regex_replacer,
]
super(QuantumTestBase, self).__init__(
method_name,
recording_processors=recording_processors,
replay_processors=replay_processors,
)
# as we append a sequence id to every request,
# we ensure that that a request can only be recorded once
self.vcr.record_mode = 'once'
self.vcr.register_matcher('query', self._custom_request_query_matcher)
self._regex_replacer.register_guid_regex(
f"(?:job-|jobs/|session-|sessions/){GUID_REGEX_CAPTURE}")
self._regex_replacer.register_scrubbing(connection_params.client_id, ZERO_UID)
self._regex_replacer.register_scrubbing(
self._client_secret, PLACEHOLDER
)
self._regex_replacer.register_scrubbing(connection_params.tenant_id, ZERO_UID)
self._regex_replacer.register_scrubbing(connection_params.subscription_id, ZERO_UID)
self._regex_replacer.register_scrubbing(connection_params.workspace_name, WORKSPACE)
self._regex_replacer.register_scrubbing(connection_params.location, LOCATION)
self._regex_replacer.register_scrubbing(connection_params.resource_group, RESOURCE_GROUP)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_PATH_SUBSCRIPTION_ID,
f"/subscriptions/{ZERO_UID}",
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.DATE_TIME,
"20210101-000000"
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_PATH_BLOB_GUID,
f'blob.core.windows.net/{ZERO_UID}',
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_PATH_RESOURCE_GROUP,
f'/resourceGroups/{RESOURCE_GROUP}/'
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_PATH_WORKSPACE_NAME,
f'/workspaces/{WORKSPACE}/'
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_STORAGE_ACCOUNT,
f'https://{STORAGE}.blob.core.windows.net'
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_QUANTUM_ENDPOINT,
ConnectionConstants.GET_QUANTUM_PRODUCTION_ENDPOINT(LOCATION)
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_OAUTH_ENDPOINT,
f'https://login.microsoftonline.com/{ZERO_UID}/oauth2/v2.0/token'
)
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_SAS_KEY_SIGNATURE,
"sig=PLACEHOLDER&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_SAS_KEY_VALUE,
"sv=PLACEHOLDER&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_SAS_KEY_EXPIRATION,
"se=2050-01-01T00%3A00%3A00Z&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_AUTH_CLIENT_ID,
"client_id=PLACEHOLDER&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_AUTH_CLIENT_SECRET,
"client_secret=PLACEHOLDER&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_AUTH_CLAIMS,
"claims=PLACEHOLDER&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_AUTH_CODE_VERIFIER,
"code_verifier=PLACEHOLDER&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_QUERY_AUTH_CODE,
"code=PLACEHOLDER&")
self._regex_replacer.register_scrubbing(RegexScrubbingPatterns.URL_HTTP, "https://")
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_QUERY_AUTH_CLIENT_ASSERTION,
"client_assertion=PLACEHOLDER&"
)
self._regex_replacer.register_scrubbing(
RegexScrubbingPatterns.URL_QUERY_AUTH_CLIENT_ASSERTION_TYPE,
"client_assertion_type=PLACEHOLDER&"
)
def disable_scrubbing(self, pattern: str) -> None:
"""
Disable scrubbing of a pattern.
This is useful when you need to have a value in the recording
that would otherwise be scrubbed by default.
Use it carefully not to leak any secrets in the recording.
To be used in conjunction with `enable_scrubbing()` method.
:param pattern:
Pattern to disable scrubbing.
"""
self._regex_replacer.disable_scrubbing(pattern)
def enable_scrubbing(self, pattern: str) -> None:
"""
Enable scrubbing of a pattern.
This is useful when you need to have a value in the recording
that would otherwise be scrubbed by default.
You disable the scrubbing with `disable_scrubbing()` method
and then re-enable the scrubbing with this method.
:param pattern:
Pattern to enable scrubbing.
"""
self._regex_replacer.enable_scrubbing(pattern)
@classmethod
def _custom_request_query_matcher(cls, r1: VcrRequest, r2: VcrRequest):
""" Ensure method, path, and query parameters match. """
from six.moves.urllib_parse import urlparse, parse_qs # pylint: disable=import-error, relative-import
assert r1.method == r2.method, f"method: {r1.method} != {r2.method}"
url1 = urlparse(r1.uri)
url2 = urlparse(r2.uri)
assert url1.hostname == url2.hostname, f"hostname: {url1.hostname} != {url2.hostname}"
assert url1.path == url2.path, f"path: {url1.path} != {url2.path}"
q1 = parse_qs(url1.query)
q2 = parse_qs(url2.query)
for key in q1.keys():
assert key in q2, f"&{key} not found in {url2.query}"
assert q1[key][0].lower() == q2[key][0].lower(), f"&{key}: {q1[key][0].lower()} != {q2[key][0].lower()}"
for key in q2.keys():
assert key in q1, f"&{key} not found in {url1.query}"
assert q1[key][0].lower() == q2[key][0].lower(), f"&{key}: {q1[key][0].lower()} != {q2[key][0].lower()}"
return True
def setUp(self):
self.in_test_setUp = True
super(QuantumTestBase, self).setUp()
# Since we are appending a sequence id to the requests
# we don't allow playback repeats
self.cassette.allow_playback_repeats = False
# modify the _default_poll_wait time to zero
# so that we don't artificially wait or delay
# the tests when in playback mode
self.patch_default_poll_wait = patch.object(
Job,
"_default_poll_wait",
0.0
)
if self.is_playback:
self.patch_default_poll_wait.start()
self.in_test_setUp = False
def tearDown(self):
self.patch_default_poll_wait.stop()
super().tearDown()
def pause_recording(self):
self.disable_recording = True
def resume_recording(self):
self.disable_recording = False
@property
def is_playback(self):
return (self.connection_params.subscription_id == SUBSCRIPTION_ID
and not self.in_recording
and not self.is_live)
def clear_env_vars(self, os_environ):
for env_var in EnvironmentVariables.ALL:
if env_var in os_environ:
del os_environ[env_var]
def create_workspace(
self,
credential = None,
**kwargs) -> Workspace:
"""
Create workspace using credentials passed via OS Environment Variables
described in the README.md documentation, or when in playback mode use
a placeholder credential.
"""
connection_params = self.connection_params
if not credential and self.is_playback:
credential = ClientSecretCredential(
tenant_id=TENANT_ID,
client_id=ZERO_UID,
client_secret=PLACEHOLDER)
workspace = Workspace(
credential=credential,
subscription_id=connection_params.subscription_id,
resource_group=connection_params.resource_group,
name=connection_params.workspace_name,
location=connection_params.location,
user_agent=connection_params.user_agent_app_id,
**kwargs
)
return workspace
def create_echo_target(
self,
credential = None,
**kwargs
) -> Target:
"""
Create a `Microsoft.Test.echo-target` Target for simple job submission tests.
Uses the Workspace returned from `create_workspace()` method.
"""
workspace = self.create_workspace(credential=credential, **kwargs)
target = Target(
workspace=workspace,
name="echo-output",
provider_id="Microsoft.Test",
input_data_format = "microsoft.quantum-log.v1",
output_data_format = "microsoft.quantum-log.v1"
)
return target
class RegexScrubbingRule:
""" A Regex Scrubbing Rule to be applied during test recordings and playbacks."""
def __init__(
self,
pattern: str,
replacement_text: str,
) -> None:
self.pattern = pattern
self.replacement_text = replacement_text
self._regex = re.compile(pattern=pattern,
flags=re.IGNORECASE | re.MULTILINE)
self.enabled = True
def replace(self, original_text) -> str:
"""
If enabled, returns the `original_text` with the regex replacement applied to it.
Otherwise, returns the unmodified `original_text`.
"""
if self.enabled:
return self._regex.sub(self.replacement_text, original_text)
return original_text
class CustomRecordingProcessor(RecordingProcessor):
ALLOW_HEADERS = [
"connection",
"content-length",
"content-range",
"content-type",
"accept",
"accept-encoding",
"accept-charset",
"accept-ranges",
"transfer-encoding",
"x-ms-blob-content-md5",
"x-ms-blob-type",
"x-ms-creation-time",
"x-ms-date",
"x-ms-encryption-algorithm",
"x-ms-lease-state",
"x-ms-lease-status",
"x-ms-meta-avg_coupling",
"x-ms-meta-max_coupling",
"x-ms-meta-min_coupling",
"x-ms-meta-num_terms",
"x-ms-meta-type",
"x-ms-range",
"x-ms-server-encrypted",
"x-ms-version",
"x-client-cpu",
"x-client-current-telemetry",
"x-client-os",
"x-client-sku",
"x-client-ver",
"user-agent",
"www-authenticate",
]
ALLOW_SANITIZED_HEADERS = [
ConnectionConstants.QUANTUM_API_KEY_HEADER,
]
def __init__(self, quantumTest: QuantumTestBase):
self._scrubbingRules = dict[str, RegexScrubbingRule]()
self._auto_guid_regexes = []
self._guids = dict[str, int]()
self._sequence_ids = dict[str, float]()
self._quantumTest = quantumTest
def disable_scrubbing(self, pattern: str) -> None:
"""
Disable scrubbing of a pattern.
This is useful when you need to have a value in the recording
that would otherwise be scrubbed by default.
Use it carefully not to leak any secrets in the recording.
To be used in conjunction with `enable_scrubbing()` method.
:param pattern:
Pattern to disable scrubbing.
"""
if pattern in self._scrubbingRules:
self._scrubbingRules[pattern].enabled = False
def enable_scrubbing(self, pattern: str) -> None:
"""
Enable scrubbing of a pattern.
This is useful when you need to have a value in the recording
that would otherwise be scrubbed by default.
You disable the scrubbing with `disable_scrubbing()` method
and then re-enable the scrubbing with this method.
Example:
```python
self.disable_scrubbing(RegexScrubbingPatterns.URL_QUERY_SAS_KEY_EXPIRATION)
try:
# your testing logic here that relies on the un-scrubbed value
finally:
self.enable_scrubbing(RegexScrubbingPatterns.URL_QUERY_SAS_KEY_EXPIRATION)
```
:param pattern:
Pattern to enable scrubbing.
"""
if pattern in self._scrubbingRules:
self._scrubbingRules[pattern].enabled = True
def register_scrubbing(self, regex_pattern, replacement_text):
"""
Registers a regular expression that should be used to replace the
HTTP requests' uri, headers and body with a `replacement_text`.
"""
self._scrubbingRules[regex_pattern] = RegexScrubbingRule(
pattern=regex_pattern,
replacement_text=replacement_text
)
def register_guid_regex(self, guid_regex):
"""
Registers a regular expression that should detect guids from
HTTP requests' uri, headers and body and automatically
register replacements with an auto-incremented deterministic guid
to be included in the recordings
"""
self._auto_guid_regexes.append(
re.compile(pattern=guid_regex,
flags=re.IGNORECASE | re.MULTILINE))
def _search_for_guids(self, value: str):
"""
Looks for a registered guid pattern and, if found,
automatically adds it to be replaced in future
requests/responses.
"""
if value:
for regex in self._auto_guid_regexes:
match = regex.search(value)
if match:
guid = match.groups("guid")[0]
if (
guid not in self._guids
and not guid.startswith("00000000-")
):
i = len(self._guids) + 1
new_guid = "00000000-0000-0000-0000-%0.12X" % i
self._guids[guid] = new_guid
self.register_scrubbing(guid, new_guid)
def _append_sequence_id(self, request: VcrRequest):
"""
Appends a sequential `&test-sequence-id=` in the querystring
of the recordings, such that multiple calls to the same
URL will be recorded multiple times with potentially different
responses.
For example, when a job is submitted and we want to fetch
the job status, the HTTP request to get the job status is the same,
but the response can be different, initially returning
Status="In-Progress" and later returning Status="Completed".
The sequence is only for `quantum.azure.com` API requests
and is on a per Method+Uri basis.
"""
if "quantum.azure.com" not in request.uri:
return request
import math
SEQUENCE_ID_KEY = "&test-sequence-id="
if SEQUENCE_ID_KEY not in request.uri:
key = f"{request.method}:{request.uri}"
sequence_id = self._sequence_ids.pop(key, 0.0)
# if we are in playback
# or we are recording and the recording is not suspended
# we increment the sequence id
if (
self._quantumTest.is_playback or
not self._quantumTest.disable_recording
):
# VCR calls this method twice per request
# so we need to increment the sequence by 0.5
# and use the ceiling
sequence_id += 0.5
self._sequence_ids[key] = sequence_id
if "?" not in request.uri:
request.uri += "?"
request.uri += SEQUENCE_ID_KEY + "%0.f" % math.ceil(sequence_id)
return request
def _apply_scrubbings(self, value: str):
for scrubbing_rule in self._scrubbingRules.values():
value = scrubbing_rule.replace(value)
return value
def process_request(self, request):
# when loading the VCR cassete during
# the test playback, just return the request
# that is recorded in the cassete
if self._quantumTest.in_test_setUp:
return request
content_type = self._get_content_type(request)
body = request.body
encode_body = False
if body:
if (
(content_type == "application/x-www-form-urlencoded") and
(isinstance(body, bytes) or isinstance(body, bytearray))
):
body = body.decode("utf-8")
encode_body = True
else:
body = str(body)
for key in request.headers:
self._search_for_guids(request.headers[key])
self._search_for_guids(request.uri)
self._search_for_guids(body)
headers = {}
for key in request.headers:
if key.lower() in self.ALLOW_HEADERS:
headers[key] = self._apply_scrubbings(request.headers[key])
if key.lower() in self.ALLOW_SANITIZED_HEADERS:
headers[key] = PLACEHOLDER
request.headers = headers
request.uri = self._apply_scrubbings(request.uri)
self._append_sequence_id(request)
if body is not None:
body = self._apply_scrubbings(body)
if encode_body:
body = body.encode("utf-8")
request.body = body
request.headers["content-length"] = ["%s" % len(body)]
return request
def _get_content_type(self, entity):
# 'headers' is a field of 'request',
# but it is a dict-key in 'response'
if hasattr(entity, "headers"):
headers = getattr(entity, "headers")
else:
headers = entity.get('headers')
content_type = None
if headers is not None:
content_type = headers.get('content-type')
if content_type is not None:
# content-type could be an array from response
# so we extract it out if needed
if isinstance(content_type, list):
content_type = content_type[0]
content_type = content_type.split(";")[0].lower()
return content_type
def process_response(self, response):
# when loading the VCR cassete during
# the test playback, just return the response
# that is recorded in the cassete
if self._quantumTest.in_test_setUp:
return response
headers = {}
for key in response["headers"]:
if key.lower() in self.ALLOW_HEADERS:
new_header_values = []
for old_header_value in response["headers"][key]:
new_header_value = (
self._apply_scrubbings(old_header_value))
new_header_values.append(new_header_value)
headers[key] = new_header_values
response["headers"] = headers
if "url" in response:
response["url"] = self._apply_scrubbings(response["url"])
content_type = self._get_content_type(response)
if (
is_text_payload(response)
or "application/octet-stream" == content_type
):
body = response["body"]["string"]
if body is not None:
encode_body = False
if not isinstance(body, str):
body = body.decode("utf-8")
encode_body = True
if body:
body = self._apply_scrubbings(body)
if encode_body:
body = body.encode("utf-8")
response["body"]["string"] = body
response["headers"]["content-length"] = ["%s" % len(body)]
return response
class AuthenticationMetadataFilter(RecordingProcessor):
"""
Remove authority and tenant discovery requests
and responses from recordings.
MSAL sends these requests to obtain non-secret
metadata about the token authority.
Recording them is unnecessary because tests use
fake credentials during playback that don't invoke MSAL.
"""
def process_request(self, request):
if (
"/.well-known/openid-configuration" in request.uri
or "/common/discovery/instance" in request.uri
or "&discover-tenant-id-and-authority" in request.uri
):
return None
return request
class CustomAccessTokenReplacer(RecordingProcessor):
"""
Sanitize the access token in the response body.
"""
def process_response(self, response):
try:
body = json.loads(response['body']['string'])
if not isinstance(body, list) and 'access_token' in body:
refresh_in = 365*24*60*60
expires_in = int(time.time()) + refresh_in
body['access_token'] = PLACEHOLDER
body['expires_in'] = expires_in
body['ext_expires_in'] = expires_in
body['refresh_in'] = refresh_in
for prop in (
'scope', 'refresh_token',
'foci', 'client_info',
'id_token'
):
if prop in body:
del body[prop]
body_bytes = json.dumps(body).encode()
response['body']['string'] = body_bytes
response['headers']['content-length'] = [str(len(body_bytes))]
except (KeyError, ValueError):
return response
return response
class InteractiveAccessTokenReplacer(RecordingProcessor):
"""Replace the access token for interactive authentication in a response body."""
def __init__(self, replacement='fake_token'):
self._replacement = replacement
def process_response(self, response):
import json
try:
body = json.loads(response['body']['string'])
if 'access_token' in body:
body['access_token'] = self._replacement
for property in ('scope', 'refresh_token',
'foci', 'client_info',
'id_token'):
if property in body:
del body[property]
except (KeyError, ValueError):
return response
body_bytes = json.dumps(body).encode()
response['body']['string'] = body_bytes
response['headers']['content-length'] = [str(len(body_bytes))]
return response
|
azure-quantum-python/azure-quantum/tests/unit/common.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/common.py",
"repo_id": "azure-quantum-python",
"token_count": 12406
}
| 410 |
interactions:
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_info=1&client_secret=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '144'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1745070444, "ext_expires_in":
1745070444, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000001"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '64'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl"}'
headers:
connection:
- keep-alive
content-length:
- '174'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 13:47:25 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: "\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ContainerNotFound</Code><Message>The
specified container does not exist.\nRequestId:b32efb9d-501e-0073-1260-927453000000\nTime:2024-04-19T13:47:26.3160848Z</Message></Error>"
headers:
content-length:
- '223'
content-type:
- application/xml
x-ms-version:
- '2023-11-03'
status:
code: 404
message: The specified container does not exist.
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 13:47:26 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 13:47:26 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-version:
- '2023-11-03'
status:
code: 200
message: OK
- request:
body: 'b"{ input: ''data'' }"'
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '20'
Content-Type:
- application/octet-stream
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-blob-type:
- BlockBlob
x-ms-date:
- Fri, 19 Apr 2024 13:47:27 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000001", "name": "azure-quantum-job",
"providerId": "Microsoft.Test", "target": "echo-output", "itemType": "Job",
"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "outputDataFormat":
"microsoft.quantum-log.v1"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '558'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Waiting", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "azure-quantum-job",
"id": "00000000-0000-0000-0000-000000000001", "providerId": "microsoft.test",
"target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1079'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Waiting", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1330'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Waiting", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1330'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Waiting", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1330'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=4
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=5
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=6
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=7
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=8
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=9
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=10
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=11
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Executing", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1354'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=12
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "microsoft.quantum-log.v1", "inputParams": {}, "metadata":
null, "sessionId": null, "status": "Succeeded", "jobType": "QuantumComputing",
"outputDataFormat": "microsoft.quantum-log.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dazure-quantum-job-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-04-19T13:47:28.334Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "azure-quantum-job", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-output", "creationTime": "2024-04-19T13:47:27.8496769+00:00",
"endExecutionTime": "2024-04-19T13:47:57.181Z", "costEstimate": null, "itemType":
"Job"}'
headers:
connection:
- keep-alive
content-length:
- '1379'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000001", "blobName":
"rawOutputData"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '93'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw"}'
headers:
connection:
- keep-alive
content-length:
- '179'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 13:48:05 GMT
x-ms-range:
- bytes=0-33554431
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw
response:
body:
string: '{ input: ''data'' }'
headers:
accept-ranges:
- bytes
content-length:
- '17'
content-range:
- bytes 0-16/17
content-type:
- application/json
x-ms-blob-content-md5:
- 2hWorJzTZ+T0wH2NOkMqhA==
x-ms-blob-type:
- BlockBlob
x-ms-creation-time:
- Fri, 19 Apr 2024 13:47:28 GMT
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-server-encrypted:
- 'true'
x-ms-version:
- '2023-11-03'
status:
code: 206
message: Partial Content
version: 1
|
azure-quantum-python/azure-quantum/tests/unit/recordings/test_job_get_results_with_expired_sas_token.yaml/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/recordings/test_job_get_results_with_expired_sas_token.yaml",
"repo_id": "azure-quantum-python",
"token_count": 16901
}
| 411 |
interactions:
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_assertion=PLACEHOLDER&client_info=1&client_assertion_type=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '181'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1746122628, "ext_expires_in":
1746122628, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000001"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '64'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl"}'
headers:
connection:
- keep-alive
content-length:
- '174'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Wed, 01 May 2024 18:03:49 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: "\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ContainerNotFound</Code><Message>The
specified container does not exist.\nRequestId:bc5c907f-d01e-0052-79f1-9b5028000000\nTime:2024-05-01T18:03:51.9467500Z</Message></Error>"
headers:
content-length:
- '223'
content-type:
- application/xml
x-ms-version:
- '2023-11-03'
status:
code: 404
message: The specified container does not exist.
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Wed, 01 May 2024 18:03:51 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Wed, 01 May 2024 18:03:51 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-version:
- '2023-11-03'
status:
code: 200
message: OK
- request:
body: b'a\n\nDECLARE ro BIT[2]\n\nH 0\nCNOT 0 1\n\nMEASURE 0 ro[0]\nMEASURE 1
ro[1]\n'
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '80'
Content-Type:
- application/octet-stream
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-blob-type:
- BlockBlob
x-ms-date:
- Wed, 01 May 2024 18:03:52 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000001", "name": "qdk-python-test",
"providerId": "rigetti", "target": "rigetti.sim.qvm", "itemType": "Job", "containerUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "outputDataFormat":
"rigetti.quil-results.v1"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '543'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Waiting", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "qdk-python-test",
"id": "00000000-0000-0000-0000-000000000001", "providerId": "rigetti", "target":
"rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00", "endExecutionTime":
null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1135'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Waiting", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"qdk-python-test", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1311'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Waiting", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"qdk-python-test", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1311'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Waiting", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"qdk-python-test", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1311'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=4
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Waiting", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"qdk-python-test", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1311'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=5
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Waiting", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"qdk-python-test", "id": "00000000-0000-0000-0000-000000000001", "providerId":
"rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1311'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=6
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Failed", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-05-01T18:03:57.1586489Z", "cancellationTime":
null, "quantumComputingData": {"count": 1}, "errorData": {"code": "InvalidInputData",
"message": "QVM reported a problem running your program: error when calling
QVM: failed to perform multishot: Encountered the invalid instruction\n\n a\n\nwhich
could not be executed because the operator a is not known"}, "isCancelling":
false, "tags": [], "name": "qdk-python-test", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": "2024-05-01T18:03:57.7311069Z", "costEstimate": null,
"itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1613'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=7
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Failed", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-05-01T18:03:57.1586489Z", "cancellationTime":
null, "quantumComputingData": {"count": 1}, "errorData": {"code": "InvalidInputData",
"message": "QVM reported a problem running your program: error when calling
QVM: failed to perform multishot: Encountered the invalid instruction\n\n a\n\nwhich
could not be executed because the operator a is not known"}, "isCancelling":
false, "tags": [], "name": "qdk-python-test", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": "2024-05-01T18:03:57.7311069Z", "costEstimate": null,
"itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1613'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=8
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.input.json",
"inputDataFormat": "rigetti.quil.v1", "inputParams": {}, "metadata": null,
"sessionId": null, "status": "Failed", "jobType": "QuantumComputing", "outputDataFormat":
"rigetti.quil-results.v1", "outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000001/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3Dqdk-python-test-00000000-0000-0000-0000-000000000001.output.json",
"beginExecutionTime": "2024-05-01T18:03:57.1586489Z", "cancellationTime":
null, "quantumComputingData": {"count": 1}, "errorData": {"code": "InvalidInputData",
"message": "QVM reported a problem running your program: error when calling
QVM: failed to perform multishot: Encountered the invalid instruction\n\n a\n\nwhich
could not be executed because the operator a is not known"}, "isCancelling":
false, "tags": [], "name": "qdk-python-test", "id": "00000000-0000-0000-0000-000000000001",
"providerId": "rigetti", "target": "rigetti.sim.qvm", "creationTime": "2024-05-01T18:03:54.3887091+00:00",
"endExecutionTime": "2024-05-01T18:03:57.7311069Z", "costEstimate": null,
"itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1613'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
version: 1
|
azure-quantum-python/azure-quantum/tests/unit/recordings/test_quil_syntax_error.yaml/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/recordings/test_quil_syntax_error.yaml",
"repo_id": "azure-quantum-python",
"token_count": 12213
}
| 412 |
interactions:
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.18 (Windows-10-10.0.22631-SP0)
x-ms-quantum-api-key:
- PLACEHOLDER
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"value": [], "nextLink": null}'
headers:
connection:
- keep-alive
content-length:
- '2'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.18 (Windows-10-10.0.22631-SP0)
x-ms-quantum-api-key:
- PLACEHOLDER
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: ''
headers:
connection:
- keep-alive
content-length:
- '0'
www-authenticate:
- Bearer error="invalid_token"
status:
code: 401
message: Unauthorized
version: 1
|
azure-quantum-python/azure-quantum/tests/unit/recordings/test_workspace_auth_connection_string_api_key.yaml/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/recordings/test_workspace_auth_connection_string_api_key.yaml",
"repo_id": "azure-quantum-python",
"token_count": 764
}
| 413 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
import pytest
from pytest import raises
from os import path
import re
from azure.quantum.target.microsoft.target import DistillationUnitSpecification, MicrosoftEstimatorConstraints, ProtocolSpecificDistillationUnitSpecification, MeasurementErrorRate
from common import QuantumTestBase, DEFAULT_TIMEOUT_SECS
from azure.quantum import JobStatus
from azure.quantum.target.microsoft import MicrosoftEstimator, \
MicrosoftEstimatorJob, MicrosoftEstimatorResult, \
MicrosoftEstimatorParams, QubitParams, ErrorBudgetPartition
class TestMicrosoftQC(QuantumTestBase):
"""TestMicrosoftQC
Tests the azure.quantum.target.microsoft module.
"""
def _ccnot_bitcode(self) -> bytes:
"""
QIR sample file for CCNOT gate applied to 3 qubits.
"""
bitcode_filename = path.join(path.dirname(__file__), "qir", "ccnot.bc")
with open(bitcode_filename, "rb") as f:
return f.read()
def _mock_result_data(self) -> dict:
"""
A small result data for tests.
"""
return {
"physicalCounts": {
"physicalQubits": 655321,
"runtime": 1729,
"rqops": 314
},
"reportData": {"groups": [], "assumptions": []}
}
def _mock_result_data_full(self, status) -> dict:
formatted = {
"algorithmicLogicalQubits": 10,
"logicalDepth": 100,
"numTstates": 15,
"numTfactories": 1000,
"physicalQubitsForTfactoriesPercentage": 10,
"physicalQubits": 30000,
"rqops": 45678,
"runtime": 23456789
}
result = {
"physicalCounts": {
"physicalQubits": 655321,
"runtime": 1729,
"rqops": 314
},
"logicalQubit": {
"codeDistance": 11
},
"reportData": {"groups": [], "assumptions": []}
}
result["physicalCountsFormatted"] = formatted
result["status"] = status
return result
@pytest.mark.microsoft_qc
@pytest.mark.live_test
def test_estimator_non_batching_job(self):
"""
Submits a job with default job parameters.
Checks whether job and results have expected type.
"""
ws = self.create_workspace()
estimator = MicrosoftEstimator(ws)
ccnot = self._ccnot_bitcode()
job = estimator.submit(ccnot)
self.assertIsInstance(job, MicrosoftEstimatorJob)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
result = job.get_results(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertIsInstance(result, MicrosoftEstimatorResult)
# Retrieve job by ID
job2 = ws.get_job(job.id)
self.assertEqual(type(job2), type(job))
result2 = job2.get_results(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertEqual(type(result2), type(result))
@pytest.mark.microsoft_qc
@pytest.mark.live_test
def test_estimator_batching_job(self):
"""
Submits a job with default job parameters.
Checks whether job and results have expected type.
"""
ws = self.create_workspace()
estimator = MicrosoftEstimator(ws)
ccnot = self._ccnot_bitcode()
params = estimator.make_params(num_items=3)
params.items[0].error_budget = 0.001
params.items[0].qubit_params.name = QubitParams.MAJ_NS_E4
params.items[0].qubit_params.instruction_set = "majorana"
params.items[0].qubit_params.t_gate_error_rate = 0.03
params.items[0].qubit_params.t_gate_time = "10 ns"
params.items[0].qubit_params.idle_error_rate = 0.00002
params.items[0].qubit_params.two_qubit_joint_measurement_error_rate = \
MeasurementErrorRate(process=0.00005, readout=0.00007)
specification1 = DistillationUnitSpecification()
specification1.display_name = "S"
specification1.num_input_ts = 1
specification1.num_output_ts = 15
specification1.output_error_rate_formula = "35.0 * inputErrorRate ^ 3 + 7.1 * cliffordErrorRate"
specification1.failure_probability_formula = "15.0 * inputErrorRate + 356.0 * cliffordErrorRate"
physical_qubit_specification = ProtocolSpecificDistillationUnitSpecification()
physical_qubit_specification.num_unit_qubits = 12
physical_qubit_specification.duration_in_qubit_cycle_time = 45
specification1.physical_qubit_specification = physical_qubit_specification
logical_qubit_specification = ProtocolSpecificDistillationUnitSpecification()
logical_qubit_specification.num_unit_qubits = 20
logical_qubit_specification.duration_in_qubit_cycle_time = 13
specification1.logical_qubit_specification = physical_qubit_specification
specification2 = DistillationUnitSpecification()
specification2.name = "15-1 RM"
specification3 = DistillationUnitSpecification()
specification3.name = "15-1 space-efficient"
params.items[0].distillation_unit_specifications = [
specification1, specification2, specification3]
params.items[1].error_budget = 0.002
params.items[1].constraints.max_duration = "20s"
params.items[2].error_budget = 0.003
params.items[2].constraints.max_physical_qubits = 10000
job = estimator.submit(ccnot, input_params=params)
self.assertIsInstance(job, MicrosoftEstimatorJob)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
if job.details.status != "Succeeded":
raise Exception(f"Job {job.id} not succeeded in "
"test_estimator_batching_job")
result = job.get_results(timeout_secs=DEFAULT_TIMEOUT_SECS)
errors = []
if type(result) != MicrosoftEstimatorResult:
errors.append("Unexpected type for result")
if 'summary_data_frame' not in dir(result):
errors.append("summary_data_frame not method of result")
from pandas import DataFrame
df = result.summary_data_frame()
if type(df) != DataFrame:
errors.append("Unexpected type for summary data frame")
self.assertEqual(errors, [])
@pytest.mark.microsoft_qc
@pytest.mark.live_test
def test_estimator_failing_job(self):
"""
Submits a job with wrong parameters.
Checks whether error handling is correct.
"""
ws = self.create_workspace()
estimator = MicrosoftEstimator(ws)
ccnot = self._ccnot_bitcode()
job = estimator.submit(ccnot, input_params={"errorBudget": 2})
self.assertIsInstance(job, MicrosoftEstimatorJob)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertEqual(job.details.status, "Failed")
expected = "Cannot retrieve results as job execution failed " \
"(InvalidInputError: The error budget must be " \
"between 0.0 and 1.0, provided input was `2`)"
with raises(RuntimeError, match=re.escape(expected)):
_ = job.get_results(timeout_secs=DEFAULT_TIMEOUT_SECS)
@pytest.mark.microsoft_qc
def test_estimator_failing_job_client_validation(self):
"""
Submits a job with wrong parameters.
Checks whether error handling is correct.
"""
# This test will not send any request (not even authentication),
# because the error is caught before submit can send a request.
ws = self.create_workspace()
estimator = MicrosoftEstimator(ws)
ccnot = self._ccnot_bitcode()
params = estimator.make_params()
params.error_budget = 2
expected = "error_budget must be value between 0 and 1"
with raises(ValueError, match=expected):
estimator.submit(ccnot, input_params=params)
@pytest.mark.microsoft_qc
@pytest.mark.live_test
def test_estimator_qiskit_job(self):
"""
Submits a job from a Qiskit QuantumCircuit.
Checks whether error handling is correct.
"""
ws = self.create_workspace()
estimator = MicrosoftEstimator(ws)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.crx(0.2, 0, 1)
circ.ccx(0, 1, 2)
job = estimator.submit(circ)
self.assertIsInstance(job, MicrosoftEstimatorJob)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertEqual(job.details.status, JobStatus.SUCCEEDED)
result = job.get_results(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertIsInstance(result, MicrosoftEstimatorResult)
@pytest.mark.microsoft_qc
@pytest.mark.live_test
def test_estimator_profiling_job(self):
"""
Submits a job with profiling information.
"""
from graphviz import Digraph
ws = self.create_workspace()
estimator = MicrosoftEstimator(ws)
ccnot = self._ccnot_bitcode()
params = estimator.make_params()
params.profiling.call_stack_depth = 0
job = estimator.submit(ccnot, input_params=params)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertEqual(job.details.status, JobStatus.SUCCEEDED)
result = job.get_results(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertIsInstance(result.call_graph, Digraph)
@pytest.mark.microsoft_qc
@pytest.mark.live_test
def test_estimator_warn_on_passed_shots(self):
ws = self.create_workspace()
estimator = MicrosoftEstimator(ws)
ccnot = self._ccnot_bitcode()
with pytest.warns(match="The 'shots' parameter is ignored in resource estimation."):
job = estimator.submit(ccnot, shots=10)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
def test_estimator_params_validation_valid_cases(self):
"""
Checks validation cases for resource estimation parameters for valid
cases.
"""
params = MicrosoftEstimatorParams()
params.error_budget = 0.1
params.qubit_params.name = QubitParams.GATE_NS_E3
params.qubit_params.instruction_set = "gate_based"
params.qubit_params.t_gate_error_rate = 0.03
params.qubit_params.t_gate_time = "10 ns"
params.qubit_params.idle_error_rate = 0.02
# If validation would be wrong, the call to as_dict will raise an
# exception.
params.as_dict()
def test_estimator_params_validation_large_error_budget(self):
params = MicrosoftEstimatorParams()
params.error_budget = 2
expected = "error_budget must be value between 0 and 1"
with raises(ValueError, match=expected):
params.as_dict()
def test_estimator_params_validation_small_error_budget(self):
params = MicrosoftEstimatorParams()
params.error_budget = 0
expected = "error_budget must be value between 0 and 1"
with raises(ValueError, match=expected):
params.as_dict()
def test_estimator_params_validation_invalid_instruction_set(self):
params = MicrosoftEstimatorParams()
params.qubit_params.instruction_set = "invalid"
with raises(ValueError, match="instruction_set must be GateBased or "
"Majorana"):
params.as_dict()
def test_estimator_params_validation_invalid_error_rate(self):
params = MicrosoftEstimatorParams()
params.qubit_params.t_gate_error_rate = 0
with raises(ValueError, match="t_gate_error_rate must be between 0 "
"and 1"):
params.as_dict()
def test_estimator_params_validation_invalid_gate_time_type(self):
params = MicrosoftEstimatorParams()
params.qubit_params.t_gate_time = 20
with raises(TypeError, match="expected string or bytes-like object"):
params.as_dict()
def test_estimator_params_validation_invalid_gate_time_value(self):
params = MicrosoftEstimatorParams()
params.qubit_params.t_gate_time = "20"
with raises(ValueError, match="t_gate_time is not a valid time "
"string; use a suffix s, ms, us, or ns"):
params.as_dict()
def test_estimator_params_validation_missing_instruction_set(self):
params = MicrosoftEstimatorParams()
params.qubit_params.t_gate_time = "1 ns"
with raises(LookupError, match="instruction_set must be set for "
"custom qubit parameters"):
params.as_dict()
def test_estimator_params_validation_missing_fields(self):
params = MicrosoftEstimatorParams()
params.qubit_params.instruction_set = "gateBased"
params.qubit_params.t_gate_time = "1 ns"
with raises(LookupError, match="one_qubit_measurement_time must be "
"set"):
params.as_dict()
def test_estimator_params_validation_measurement_error_rates_valid(self):
params = MicrosoftEstimatorParams()
params.error_budget = 0.1
params.qubit_params.name = QubitParams.GATE_NS_E3
params.qubit_params.instruction_set = "gate_based"
params.qubit_params.t_gate_error_rate = 0.03
params.qubit_params.t_gate_time = "10 ns"
params.qubit_params.idle_error_rate = 0.02
params.qubit_params.one_qubit_measurement_error_rate = 0.01
params.qubit_params.two_qubit_joint_measurement_error_rate = \
MeasurementErrorRate(process=0.02, readout=0.03)
assert params.as_dict() == {
"errorBudget": 0.1,
"qubitParams": {"name": "qubit_gate_ns_e3",
"instructionSet": "gate_based",
"tGateErrorRate": 0.03,
"tGateTime": "10 ns",
"idleErrorRate": 0.02,
"oneQubitMeasurementErrorRate": 0.01,
"twoQubitJointMeasurementErrorRate":
{"process": 0.02, "readout": 0.03}}
}
def test_estimator_error_budget_float(self):
params = MicrosoftEstimatorParams()
params.error_budget = 0.001
assert params.as_dict() == {"errorBudget": 0.001}
def test_estimator_error_budget_partition(self):
params = MicrosoftEstimatorParams()
params.error_budget = ErrorBudgetPartition(0.01, 0.02, 0.03)
assert params.as_dict() == {
"errorBudget": {
"logical": 0.01,
"rotations": 0.03,
"tStates": 0.02
}
}
def test_estimator_profiling_valid_fields(self):
params = MicrosoftEstimatorParams()
params.profiling.call_stack_depth = 10
params.profiling.inline_functions = True
assert params.as_dict() == {
"profiling": {
"callStackDepth": 10,
"inlineFunctions": True
}
}
def test_estimator_profiling_invalid_fields(self):
params = MicrosoftEstimatorParams()
params.profiling.call_stack_depth = 50
params.profiling.inline_functions = True
with raises(ValueError, match="call_stack_depth must be nonnegative "
"and at most 30"):
params.as_dict()
def test_estimator_custom_distillation_units_by_name(self):
params = MicrosoftEstimatorParams()
unit1 = DistillationUnitSpecification()
unit1.name = "S"
params.distillation_unit_specifications.append(unit1)
unit2 = DistillationUnitSpecification()
unit2.name = "T"
params.distillation_unit_specifications.append(unit2)
assert params.as_dict() == {
"distillationUnitSpecifications": [{"name": "S"}, {"name": "T"}]
}
def test_estimator_custom_distillation_units_empty_not_allowed(self):
params = MicrosoftEstimatorParams()
unit = DistillationUnitSpecification()
params.distillation_unit_specifications.append(unit)
with raises(LookupError, match="name must be set or custom specification must be provided"):
params.as_dict()
def test_estimator_custom_distillation_units_name_and_custom_not_allowed_together(self):
params = MicrosoftEstimatorParams()
unit = DistillationUnitSpecification()
unit.name = "T"
unit.num_output_ts = 1
params.distillation_unit_specifications.append(unit)
with raises(LookupError, match="If predefined name is provided, "
"custom specification is not allowed. "
"Either remove name or remove all other "
"specification of the distillation unit"):
params.as_dict()
def test_estimator_custom_distillation_units_by_specification_short(self):
params = MicrosoftEstimatorParams()
unit = DistillationUnitSpecification()
unit.display_name = "T"
unit.failure_probability_formula = "c"
unit.output_error_rate_formula = "r"
unit.num_input_ts = 1
unit.num_output_ts = 2
params.distillation_unit_specifications.append(unit)
assert params.as_dict() == {
"distillationUnitSpecifications":
[{"displayName": "T", "failureProbabilityFormula": "c",
"outputErrorRateFormula": "r", "numInputTs": 1, "numOutputTs": 2}]
}
def test_estimator_custom_distillation_units_by_specification_full(self):
params = MicrosoftEstimatorParams()
unit = DistillationUnitSpecification()
unit.display_name = "T"
unit.failure_probability_formula = "c"
unit.output_error_rate_formula = "r"
unit.num_input_ts = 1
unit.num_output_ts = 2
physical_qubit_specification = ProtocolSpecificDistillationUnitSpecification()
physical_qubit_specification.num_unit_qubits = 1
physical_qubit_specification.duration_in_qubit_cycle_time = 2
unit.physical_qubit_specification = physical_qubit_specification
logical_qubit_specification = ProtocolSpecificDistillationUnitSpecification()
logical_qubit_specification.num_unit_qubits = 3
logical_qubit_specification.duration_in_qubit_cycle_time = 4
unit.logical_qubit_specification = logical_qubit_specification
logical_qubit_specification_first_round_override = \
ProtocolSpecificDistillationUnitSpecification()
logical_qubit_specification_first_round_override.num_unit_qubits = 5
logical_qubit_specification_first_round_override.duration_in_qubit_cycle_time = 6
unit.logical_qubit_specification_first_round_override = \
logical_qubit_specification_first_round_override
params.distillation_unit_specifications.append(unit)
print(params.as_dict())
assert params.as_dict() == {
"distillationUnitSpecifications":
[{"displayName": "T", "numInputTs": 1, "numOutputTs": 2,
"failureProbabilityFormula": "c", "outputErrorRateFormula": "r",
"physicalQubitSpecification": {"numUnitQubits": 1, "durationInQubitCycleTime": 2},
"logicalQubitSpecification": {"numUnitQubits": 3, "durationInQubitCycleTime": 4},
"logicalQubitSpecificationFirstRoundOverride":
{"numUnitQubits": 5, "durationInQubitCycleTime": 6}}]
}
def test_estimator_protocol_specific_distillation_unit_specification_empty_not_allowed(self):
specification = ProtocolSpecificDistillationUnitSpecification()
with raises(LookupError, match="num_unit_qubits must be set"):
specification.as_dict()
def test_estimator_protocol_specific_distillation_unit_specification_missing_num_unit_qubits(self):
specification = ProtocolSpecificDistillationUnitSpecification()
specification.duration_in_qubit_cycle_time = 1
with raises(LookupError, match="num_unit_qubits must be set"):
specification.as_dict()
def test_estimator_protocol_specific_distillation_unit_specification_missing_duration_in_qubit_cycle_time(self):
specification = ProtocolSpecificDistillationUnitSpecification()
specification.num_unit_qubits = 1
with raises(LookupError, match="duration_in_qubit_cycle_time must be set"):
specification.as_dict()
def test_estimator_protocol_specific_distillation_unit_specification_valid(self):
specification = ProtocolSpecificDistillationUnitSpecification()
specification.num_unit_qubits = 1
specification.duration_in_qubit_cycle_time = 2
assert specification.as_dict() == {
"numUnitQubits": 1, "durationInQubitCycleTime": 2
}
def test_simple_result_as_json(self):
data = self._mock_result_data()
result = MicrosoftEstimatorResult(data)
import json
assert json.loads(result.json) == data
def test_batch_result_as_json(self):
data = [self._mock_result_data(), self._mock_result_data()]
result = MicrosoftEstimatorResult(data)
import json
assert json.loads(result.json) == data
def test_list_status_all_failed(self):
data = [self._mock_result_data_full(
"error"), self._mock_result_data_full("failure")]
result = MicrosoftEstimatorResult(data)
import json
assert json.loads(result.json) == data
data_frame = result.summary_data_frame()
assert data_frame.values.real[0][0] == "No solution found"
assert data_frame.values.real[1][5] == "No solution found"
assert not hasattr(result[0], "summary")
assert not hasattr(result[1], "summary")
assert not hasattr(result[0], "diagram")
assert not hasattr(result[1], "diagram")
def test_list_status_partial_success(self):
data = [self._mock_result_data_full(
"success"), self._mock_result_data_full("error")]
result = MicrosoftEstimatorResult(data)
import json
assert json.loads(result.json) == data
data_frame = result.summary_data_frame()
assert data_frame.values.real[0][0] == 10
assert data_frame.values.real[1][5] == "No solution found"
assert hasattr(result[0], "summary")
assert not hasattr(result[1], "summary")
assert hasattr(result[0], "diagram")
assert not hasattr(result[1], "diagram")
def test_dict_status_failed(self):
data = self._mock_result_data_full("error")
result = MicrosoftEstimatorResult(data)
import json
assert json.loads(result.json) == data
assert not hasattr(result, "summary_data_frame")
assert not hasattr(result, "summary")
assert not hasattr(result, "diagram")
def test_dict_status_success(self):
data = self._mock_result_data_full("success")
result = MicrosoftEstimatorResult(data)
import json
assert json.loads(result.json) == data
assert not hasattr(result, "summary_data_frame")
assert hasattr(result, "summary")
assert hasattr(result, "diagram")
def test_duration_and_physical_qubits_constraints_not_allowed_together(self):
constraints = MicrosoftEstimatorConstraints()
constraints.max_physical_qubits = 100
constraints.max_duration = "5s"
with raises(LookupError, match="Both duration and number of physical qubits constraints are provided, but only one is allowe at a time."):
constraints.as_dict()
|
azure-quantum-python/azure-quantum/tests/unit/test_microsoft_qc.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/test_microsoft_qc.py",
"repo_id": "azure-quantum-python",
"token_count": 10337
}
| 414 |
<jupyter_start><jupyter_text>👋🌍 Hello, world: Submit a Q job to QuantinuumIn this notebook, we'll review the basics of Azure Quantum by submitting a simple *job*, or quantum program, to [Quantinuum](https://www.quantinuum.com/). We will use [Q](https://learn.microsoft.com/azure/quantum/user-guide/) to express the quantum job. Submit a simple job Quantinuum using Azure QuantumAzure Quantum provides several ways to express quantum programs. In this example we are using Q, but note that Qiskit and Cirq are also supported. All code in this example will be written in Python and Q.Let's begin. When you see a code block, hover over it and click the triangle play-button to execute it. To avoid any compilation issues, this should be done in order from top to bottom. 1. Connect to the Azure Quantum workspaceTo connect to the Azure Quantum service, initialize the `Workspace` as seen below.<jupyter_code>from azure.quantum import Workspace
workspace = Workspace (
resource_id = "",
location = ""
)<jupyter_output><empty_output><jupyter_text>We can use the resulting object to see which _targets_ are available for submission.<jupyter_code>print("This workspace's targets:")
for target in workspace.get_targets():
print("-", target.name)<jupyter_output><empty_output><jupyter_text>❕ Do you see `quantinuum.sim.h1-1sc` in your list of targets? If so, you're ready to keep going.Don't see it? You may need to add Quantinuum to your workspace to run this sample. Navigate to the **Providers** page in the portal and click **+Add** to add the Quantinuum provider. Don't worry, there's a free credits plan available. Quantinuum: The quantum providerAzure Quantum partners with third-party companies to deliver solutions to quantum jobs. These company offerings are called *providers*. Each provider can offer multiple *targets* with different capabilities. See the table below for Quantinuum's H1-1 device targets.| Target name | Target ID | Number of qubits | Description|| --- | ---| ---|---|H1-1 Syntax Checker | `quantinuum.sim.h1-1sc` | 20 | Quantinuum's H1-1 Syntax Checker. This will return all zeros in place of actual or simulated results. Use this to validate quantum programs against the H1-1 compiler before submitting to hardware or emulators on Quantinuum's platform. Free of cost. |H2-1 Syntax Checker | `quantinuum.sim.h2-1sc` | 32 | Quantinuum's H2-1 Syntax Checker. This will return all zeros in place of actual or simulated results. Use this to validate quantum programs against the H2-1 compiler before submitting to hardware or emulators on Quantinuum's platform. Free of cost. |H1-1 Emulator | `quantinuum.sim.h1-1e` | 20 | Quantinuum's H1-1 Emulator. Uses a realistic physical model and noise model of H1-1. |H2-1 Emulator | `quantinuum.sim.h2-1e` | 32 | Quantinuum's H2-1 Emulator. Uses a realistic physical model and noise model of H2-1. |H1-1 | `quantinuum.qpu.h1-1` | 20 | Quantinuum's H1-1 trapped ion device. |H2-1 | `quantinuum.qpu.h2-1` | 32 | Quantinuum's H2-1 trapped ion device. |For this example, we will use `quantinuum.sim.h1-1sc` to avoid any costs or credit usage. If you wish to emulate or run the actual circuit, you may replace all instances of `quantinuum.sim.h1-1sc` in subsequent code cells with one of the other values in the table above, but please note any costs incurred. To learn more about Quantinuum's targets, check out our [documentation](https://aka.ms/AQ/Quantinuum/Documentation). 2. Build the quantum programLet's create a simple Q program to run.First, let's initialize the Q environment and set the target profile to Base Profile. Today, Azure Quantum targets only support the Base Profile, a subset of all Q commands.<jupyter_code>import qsharp
qsharp.init(target_profile=qsharp.TargetProfile.Base)
%%qsharp
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Convert;
operation GenerateRandomBit() : Result {
use target = Qubit();
// Apply an H-gate and measure.
H(target);
return M(target);
}
# Compile the qsharp operation
operation = qsharp.compile("GenerateRandomBit()")<jupyter_output><empty_output><jupyter_text>The program you built is a simple quantum random bit generator. With Quantinuum's Syntax Checker, we will be able to confirm that the circuit is able to be run on their H1 emulator and hardware. 3. Submit the quantum program to QuantinuumWe will use the `target.submit` function to run the quantum program above on Quantinuum's `quantinuum.sim.h1-1sc` target. This may take a minute or so ⏳. Your job will be packaged and sent to Quantinuum, where it will wait its turn to be run.<jupyter_code># Set the target to quantinuum.sim.h1-1sc
target = workspace.get_targets("quantinuum.sim.h1-1sc")
# Execute the job. We'll use 100 shots (simulated runs).
job = target.submit(operation, "Generate one random bit", shots=100)
print("Job Id:" + job.id)
result = job.get_results()<jupyter_output><empty_output><jupyter_text>The job ID can be used to retrieve the results later using the [get_job method](https://learn.microsoft.com/python/azure-quantum/azure.quantum.workspace?azure-quantum-workspace-get-job) or by viewing it under the **Job management** section of the portal. 4. Visualize the job resultsYou can view a histogram of the results using [`pyplot`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html):<jupyter_code>from matplotlib import pyplot
pyplot.bar(result.keys(), result.values())
pyplot.title("Result")
pyplot.ylabel("Probability")
pyplot.xlabel("Measurement")
pyplot.show()<jupyter_output><empty_output>
|
azure-quantum-python/samples/hello-world/HW-quantinuum-qsharp.ipynb/0
|
{
"file_path": "azure-quantum-python/samples/hello-world/HW-quantinuum-qsharp.ipynb",
"repo_id": "azure-quantum-python",
"token_count": 1646
}
| 415 |
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
from typing import List
from urllib.request import urlopen
import json
ALLOWED_RELEASE_TYPES = ["major", "minor", "patch"]
ALLOWED_BUILD_TYPES = ["stable", "rc", "dev"]
PACKAGE_NAME = "azure-quantum"
PYPI_URL = f"https://pypi.python.org/pypi/{PACKAGE_NAME}/json"
RELEASE_TYPE = os.environ.get("RELEASE_TYPE") or "patch"
BUILD_TYPE = os.environ.get("BUILD_TYPE") or "dev"
if RELEASE_TYPE not in ALLOWED_RELEASE_TYPES:
print(f"RELEASE_TYPE environment variable must be {', '.join(ALLOWED_RELEASE_TYPES)}. Current value: {RELEASE_TYPE}")
exit(1)
if BUILD_TYPE not in ALLOWED_BUILD_TYPES:
print(f"BUILD_TYPE environment variable must be {', '.join(ALLOWED_BUILD_TYPES)}. Current value: {BUILD_TYPE}")
exit(1)
def _get_build_version(version_type: str, build_type: str, package_versions: List[str]) -> str:
stable_version_parts = None
# find last stable version
for version in package_versions:
version_parts = str(version).split(".")
if len(version_parts) == 3:
stable_version_parts = version_parts
break
if stable_version_parts is None:
stable_version_parts = ["0", "0", "0"]
if version_type == "major":
next_stable_version = f"{int(stable_version_parts[0]) + 1}.0.0"
elif version_type == "minor":
next_stable_version = f"{stable_version_parts[0]}.{int(stable_version_parts[1]) + 1}.0"
elif version_type == "patch":
next_stable_version = f"{stable_version_parts[0]}.{stable_version_parts[1]}.{int(stable_version_parts[2]) + 1}"
else:
raise ValueError(f"Version type \"{version_type}\" is not supported.")
if build_type == "stable":
return next_stable_version
# in case the build type is not "stable" find last "rc"/"dev" release and bump up it's suffix-number
for i in range(0, 100):
next_version = f"{next_stable_version}.{build_type}{i}"
if next_version not in package_versions:
return next_version
raise RuntimeError(f"Build version could not be determined for version type \"{version_type}\" and build type \"{build_type}\"")
def get_build_version(version_type: str, build_type: str) -> str:
"""Get build version by analysing released versions in PyPi and figuring out the next version.
Example:
- If the last stable version in PyPi was "1.1.0" and version_type = "major" and build_type = "stable", then returned version will be "2.0.0".
- If the last stable version in PyPi was "1.1.0" and the last dev version was "1.2.0.dev0" and version_type = "patch" and build_type = "dev",
then returned version will be "1.1.1.dev0".
- If the last stable version in PyPi was "1.1.0" and the last dev version was "1.2.0.dev0" and version_type = "minor" and build_type = "dev",
then returned version will be "1.2.0.dev1".
:param version_type: SYMVER type ("major"/"minor"/"patch")
:type version_type: str
:param build_type: Build type ("stable", "dev", "rc")
:type build_type: str
:return: build version
:rtype: str
"""
# get all releases from PyPi
with urlopen(PYPI_URL) as response:
if response.status == 200:
response_content = response.read()
response = json.loads(response_content.decode("utf-8"))
else:
raise RuntimeError(f"Request \"GET:{PYPI_URL}\" failed. Status code: \"{response.status}\"")
# Note: assuming versions are SYMVER (major.minor.patch[.dev0|.rc0]) and in chronological order:
# "1.0.0", "1.0.1", "1.1.0", "1.1.0.dev0", "1.1.0.dev1", "1.1.0.rc0"
# The next "rc" and "dev" version must follow the last "stable" version.
# sorting by time in reverse order to find the last releases, so we could assume the next version of certain "build_type"
package_versions_sorted = sorted(response["releases"].items(), key=lambda k: k[1][0]["upload_time_iso_8601"], reverse=True)
package_versions = [version[0] for version in package_versions_sorted]
return _get_build_version(version_type, build_type, package_versions)
if __name__ == "__main__":
build_version = get_build_version(RELEASE_TYPE, BUILD_TYPE)
print(f"Package version: {build_version}")
# Set PYTHON_VERSION variable for steps in same job to reference as $(PYTHON_VERSION)
print(f"##vso[task.setvariable variable=PYTHON_VERSION;]{build_version}")
# Set build tags
print(f"##vso[build.addbuildtag]v{build_version}")
print(f"##vso[build.addbuildtag]{BUILD_TYPE}")
|
azure-quantum-python/set_version.py/0
|
{
"file_path": "azure-quantum-python/set_version.py",
"repo_id": "azure-quantum-python",
"token_count": 1769
}
| 416 |
/*------------------------------------
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
All rights reserved.
------------------------------------ */
import React from "react";
import { create } from "react-test-renderer";
import { IColumn, IGroup, ThemeProvider } from "@fluentui/react";
import { Icon } from "@fluentui/react/lib/Icon";
import {
getTheme,
mergeStyleSets,
setIconOptions,
} from "@fluentui/react/lib/Styling";
import { TooltipHost } from "@fluentui/react/lib/Tooltip";
import { IItem, IState, TableComponent } from "../Table";
// Suppress icon warnings.
setIconOptions({
disableWarnings: true,
});
const classNames = mergeStyleSets({
cellText: {
overflow: "hidden",
textOverflow: "ellipsis",
},
tooltipHost: {
marginLeft: "8px",
cursor: "default",
},
infoIcon: {
width: "12px",
height: "12px",
display: "inline-block",
verticalAlign: "-0.1rem",
fill: getTheme().semanticColors.infoIcon,
},
});
describe("Table tests", () => {
it("Verify Table", () => {
const tableItems: IItem[] = [
{
name: "Total physical qubits",
value: "12",
description:
"Total physical qubits required for algorithm and T factories.",
},
{
name: "Physical T factory qubits",
value: "20",
description: "Number of physical qubits for the T factories.",
},
{
name: "Number of T factory copies",
value: "100",
description:
"Number of T factories capable of producing the demanded T states during the algorithm's runtime.",
},
{
name: "Physical qubits for single T factory",
value: "2",
description: "",
},
];
const tableGroups: IGroup[] = [
{
key: "1",
name: "Group 1",
startIndex: 0,
count: 1,
},
{
key: "2",
name: "Group 2",
startIndex: 1,
count: 2,
},
{
key: "3",
name: "Group 3",
startIndex: 3,
count: 1,
},
];
const tableProps: IState = {
items: tableItems,
groups: tableGroups,
showItemIndexInView: false,
isCompactMode: false,
};
const columns: IColumn[] = [
{
key: "name",
name: "Name",
onRender: (item: IItem) => {
return (
<div className={classNames.cellText} data-is-focusable={true}>
{item.name}
{item.description ? (
<TooltipHost
hostClassName={classNames.tooltipHost}
content={item.description}
>
<Icon iconName="Info" className={classNames.infoIcon} />
</TooltipHost>
) : (
<></>
)}
</div>
);
},
minWidth: 220,
flexGrow: 3,
},
{
key: "value",
name: "Value",
onRender: (item: IItem) => {
return (
<div className={classNames.cellText} data-is-focusable={true}>
{item.value}
</div>
);
},
minWidth: 50,
flexGrow: 1,
},
];
const component = create(
<ThemeProvider>
<TableComponent state={tableProps} columns={columns} />
</ThemeProvider>,
);
expect(component.toJSON()).toMatchSnapshot("Table");
});
});
|
azure-quantum-python/visualization/react-lib/src/components/table/__tests__/Table.test.tsx/0
|
{
"file_path": "azure-quantum-python/visualization/react-lib/src/components/table/__tests__/Table.test.tsx",
"repo_id": "azure-quantum-python",
"token_count": 1621
}
| 417 |
BiStringBuilder
===============
.. js:autoclass:: BiStringBuilder
:members:
|
bistring/docs/JavaScript/BiStringBuilder.rst/0
|
{
"file_path": "bistring/docs/JavaScript/BiStringBuilder.rst",
"repo_id": "bistring",
"token_count": 26
}
| 418 |
/*!
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
import Alignment, { BiIndex, Bounds } from "./alignment";
import BiString, { AnyString } from "./bistring";
import { cloneRegExp } from "./regex";
/**
* A token extracted from a string.
*/
export class Token {
/** The actual text of the token. */
readonly text: BiString;
/** The start position of the token. */
readonly start: number;
/** The end position of the token. */
readonly end: number;
/**
* Create a token.
*
* @param text
* The text of this token.
* @param start
* The start position of the token.
* @param end
* The end position of the token.
*/
constructor(text: AnyString, start: number, end: number) {
this.text = BiString.from(text);
this.start = start;
this.end = end;
Object.freeze(this);
}
/**
* Create a token from a slice of a string.
*
* @param text
* The text to slice.
* @param start
* The start index of the token.
* @param end
* The end index of the token.
*/
static slice(text: AnyString, start: number, end: number): Token {
return new Token(BiString.from(text).slice(start, end), start, end);
}
/**
* The original value of the token.
*/
get original(): string {
return this.text.original;
}
/**
* The modified value of the token.
*/
get modified(): string {
return this.text.modified;
}
}
/**
* A string and its tokenization.
*/
export class Tokenization {
/** The text that was tokenized. */
readonly text: BiString;
/** The tokens extracted from the text. */
readonly tokens: readonly Token[];
/** The alignment between the text and the tokens. */
readonly alignment: Alignment;
/** The number of tokens. */
readonly length: number;
/**
* Create a `Tokenization`.
*
* @param text
* The text from which the tokens have been extracted.
* @param tokens
* The tokens extracted from the text.
*/
constructor(text: AnyString, tokens: Iterable<Token>) {
this.text = BiString.from(text);
this.tokens = Object.freeze(Array.from(tokens));
const alignment: BiIndex[] = [[0, 0]];
this.tokens.forEach((token, i) => {
alignment.push([token.start, i]);
alignment.push([token.end, i + 1]);
});
alignment.push([this.text.length, this.tokens.length]);
this.alignment = new Alignment(alignment);
this.length = this.tokens.length;
Object.freeze(this);
}
/**
* Infer a `Tokenization` from a sequence of tokens.
*
* Due to the possibility of ambiguity, it is much better to use a :js:class:`Tokenizer` or some other method of
* producing :js:class:`Token`\ s with their positions explicitly set.
*
* @param text
* The text that was tokenized.
* @param tokens
* The extracted tokens.
* @returns
* The inferred tokenization, with token positions found by simple forward search.
*/
static infer(text: AnyString, tokens: Iterable<string>) {
text = BiString.from(text);
const result = [];
let start = 0, end;
for (const token of tokens) {
[start, end] = text.boundsOf(token, start);
if (start < 0) {
throw new Error(`Couldn't find the token "${token}" in the text`);
}
result.push(Token.slice(text, start, end));
start = end;
}
return new Tokenization(text, result);
}
/**
* Compute a slice of this tokenization.
*
* @param start
* The position to start from.
* @param end
* The position to end at.
* @returns
* The requested slice as a new `Tokenization`.
*/
slice(start?: number, end?: number): Tokenization {
return new Tokenization(this.text, this.tokens.slice(start, end));
}
/**
* Map a span of tokens to the corresponding substring.
*/
substring(start?: number, end?: number): BiString {
const [first, last] = this.textBounds(start, end);
return this.text.substring(first, last);
}
/**
* Map a span of tokens to the bounds of the corresponding text.
*/
textBounds(start?: number, end?: number): Bounds {
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = this.length;
}
return this.alignment.originalBounds(start, end);
}
/**
* Map a span of tokens to the bounds of the corresponding original text.
*/
originalBounds(start?: number, end?: number): Bounds {
return this.text.alignment.originalBounds(this.textBounds(start, end));
}
/**
* Map a span of text to the bounds of the corresponding span of tokens.
*/
boundsForText(start: number, end: number): Bounds {
return this.alignment.modifiedBounds(start, end);
}
/**
* Map a span of original text to the bounds of the corresponding span of tokens.
*/
boundsForOriginal(start: number, end: number): Bounds {
const textBounds = this.text.alignment.modifiedBounds(start, end);
return this.boundsForText(...textBounds);
}
/**
* Map a span of text to the corresponding span of tokens.
*/
sliceByText(start: number, end: number): Tokenization {
return this.slice(...this.boundsForText(start, end));
}
/**
* Map a span of original text to the corresponding span of tokens.
*/
sliceByOriginal(start: number, end: number): Tokenization {
return this.slice(...this.boundsForOriginal(start, end));
}
/**
* Expand a span of text to align it with token boundaries.
*/
snapTextBounds(start: number, end: number): Bounds {
return this.textBounds(...this.boundsForText(start, end));
}
/**
* Expand a span of original text to align it with token boundaries.
*/
snapOriginalBounds(start: number, end: number): Bounds {
return this.originalBounds(...this.boundsForOriginal(start, end));
}
}
/**
* A tokenizer that produces :js:class:`Tokenization`\ s.
*/
export interface Tokenizer {
/**
* Tokenize a string.
*
* @param text
* The text to tokenize, either a string or a :js:class:`BiString`.
* @returns
* A :js:class:`Tokenization` holding the text and its tokens.
*/
tokenize(text: AnyString): Tokenization;
}
/**
* Breaks text into tokens based on a :js:class:`RegExp`.
*/
export class RegExpTokenizer implements Tokenizer {
private readonly _pattern: RegExp;
/**
* Create a `RegExpTokenizer`.
*
* @param pattern
* The regex that will match tokens.
*/
constructor(pattern: RegExp) {
this._pattern = cloneRegExp(pattern, "g");
}
tokenize(text: AnyString): Tokenization {
text = BiString.from(text);
const tokens = [];
for (const match of text.matchAll(this._pattern)) {
const start = match.index!;
const end = start + match[0].length;
tokens.push(Token.slice(text, start, end));
}
return new Tokenization(text, tokens);
}
}
/**
* Splits text into tokens based on a :js:class:`RegExp`.
*/
export class SplittingTokenizer implements Tokenizer {
private readonly _pattern: RegExp;
/**
* Create a `SplittingTokenizer`.
*
* @param pattern
* A regex that matches the regions between tokens.
*/
constructor(pattern: RegExp) {
this._pattern = cloneRegExp(pattern, "g");
}
tokenize(text: AnyString): Tokenization {
text = BiString.from(text);
const tokens = [];
let last = 0;
for (const match of text.matchAll(this._pattern)) {
const start = match.index!;
if (start > last) {
tokens.push(Token.slice(text, last, start));
}
last = start + match[0].length;
}
if (text.length > last) {
tokens.push(Token.slice(text, last, text.length));
}
return new Tokenization(text, tokens);
}
}
|
bistring/js/src/token.ts/0
|
{
"file_path": "bistring/js/src/token.ts",
"repo_id": "bistring",
"token_count": 3465
}
| 419 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import icu
from typing import Callable, Optional
from ._bistr import bistr
from ._builder import BistrBuilder
def _edit(bs: bistr, op: Callable, locale: Optional[str] = None) -> bistr:
builder = BistrBuilder(bs)
edits = icu.Edits()
ucur = icu.UnicodeString(builder.current)
if locale is None:
umod = icu.UnicodeString(op(ucur, edits))
else:
umod = icu.UnicodeString(op(icu.Locale(locale), ucur, edits))
for is_change, old_len, new_len, old_i, new_i, _ in edits.getFineIterator():
old_len = ucur.countChar32(old_i, old_len)
if is_change:
repl = str(umod[new_i:new_i+new_len])
builder.replace(old_len, repl)
else:
builder.skip(old_len)
return builder.build()
def casefold(bs: bistr) -> bistr:
return _edit(bs, icu.CaseMap.fold)
def lower(bs: bistr, locale: Optional[str]) -> bistr:
return _edit(bs, icu.CaseMap.toLower, locale)
def upper(bs: bistr, locale: Optional[str]) -> bistr:
return _edit(bs, icu.CaseMap.toUpper, locale)
def title(bs: bistr, locale: Optional[str]) -> bistr:
return _edit(bs, icu.CaseMap.toTitle, locale)
def _normalize(normalizer: icu.Normalizer2, bs: bistr) -> bistr:
builder = BistrBuilder(bs)
current = builder.current
while not builder.is_complete:
i = builder.position
j = i + 1
while j < len(current) and not normalizer.hasBoundaryBefore(current[j]):
j += 1
chunk = current[i:j]
repl = normalizer.normalize(chunk)
if repl == chunk:
builder.skip(len(chunk))
else:
builder.replace(len(chunk), repl)
return builder.build()
_NORMALIZERS = {
'NFC': icu.Normalizer2.getNFCInstance,
'NFKC': icu.Normalizer2.getNFKCInstance,
'NFD': icu.Normalizer2.getNFDInstance,
'NFKD': icu.Normalizer2.getNFKDInstance,
}
def normalize(bs: bistr, form: str) -> bistr:
factory = _NORMALIZERS.get(form)
if factory:
return _normalize(factory(), bs)
else:
raise ValueError('invalid normalization form')
|
bistring/python/bistring/_icu.py/0
|
{
"file_path": "bistring/python/bistring/_icu.py",
"repo_id": "bistring",
"token_count": 960
}
| 420 |
[run]
source = ./libraries/
omit =
*/tests/*
setup.py
*/botbuilder-schema/*
|
botbuilder-python/.coveragerc/0
|
{
"file_path": "botbuilder-python/.coveragerc",
"repo_id": "botbuilder-python",
"token_count": 39
}
| 421 |
{
"bot_name": "my_chat_bot",
"bot_description": "Demonstrate the core capabilities of the Microsoft Bot Framework"
}
|
botbuilder-python/generators/app/templates/core/cookiecutter.json/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/cookiecutter.json",
"repo_id": "botbuilder-python",
"token_count": 40
}
| 422 |
Need deploy BotAppService before AzureBot
---
az login
az deployment group create --resource-group <group-name> --template-file <template-file> --parameters @<parameters-file>
---
# parameters-for-template-BotApp-with-rg:
**appServiceName**:(required) The Name of the Bot App Service.
(choose an existingAppServicePlan or create a new AppServicePlan)
**existingAppServicePlanName**: The name of the App Service Plan.
**existingAppServicePlanLocation**: The location of the App Service Plan.
**newAppServicePlanName**: The name of the App Service Plan.
**newAppServicePlanLocation**: The location of the App Service Plan.
**newAppServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
**appSecret**:(required) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
# parameters-for-template-AzureBot-with-rg:
**azureBotId**:(required) The globally unique and immutable bot ID.
**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
**botEndpoint**: Use to handle client messages, Such as https://<botappServiceName>.azurewebsites.net/api/messages.
**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
|
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/readme.md",
"repo_id": "botbuilder-python",
"token_count": 606
}
| 423 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from enum import Enum
from typing import Dict
from botbuilder.ai.luis import LuisRecognizer
from botbuilder.core import IntentScore, TopIntent, TurnContext
from booking_details import BookingDetails
class Intent(Enum):
BOOK_FLIGHT = "BookFlight"
CANCEL = "Cancel"
GET_WEATHER = "GetWeather"
NONE_INTENT = "NoneIntent"
def top_intent(intents: Dict[Intent, dict]) -> TopIntent:
max_intent = Intent.NONE_INTENT
max_value = 0.0
for intent, value in intents:
intent_score = IntentScore(value)
if intent_score.score > max_value:
max_intent, max_value = intent, intent_score.score
return TopIntent(max_intent, max_value)
class LuisHelper:
@staticmethod
async def execute_luis_query(
luis_recognizer: LuisRecognizer, turn_context: TurnContext
) -> (Intent, object):
"""
Returns an object with pre-formatted LUIS results for the bot's dialogs to consume.
"""
result = None
intent = None
try:
recognizer_result = await luis_recognizer.recognize(turn_context)
intent = (
sorted(
recognizer_result.intents,
key=recognizer_result.intents.get,
reverse=True,
)[:1][0]
if recognizer_result.intents
else None
)
if intent == Intent.BOOK_FLIGHT.value:
result = BookingDetails()
# We need to get the result from the LUIS JSON which at every level
# returns an array.
to_entities = recognizer_result.entities.get("$instance", {}).get(
"To", []
)
if len(to_entities) > 0:
if recognizer_result.entities.get("To", [{"$instance": {}}])[0][
"$instance"
]:
result.destination = to_entities[0]["text"].capitalize()
else:
result.unsupported_airports.append(
to_entities[0]["text"].capitalize()
)
from_entities = recognizer_result.entities.get("$instance", {}).get(
"From", []
)
if len(from_entities) > 0:
if recognizer_result.entities.get("From", [{"$instance": {}}])[0][
"$instance"
]:
result.origin = from_entities[0]["text"].capitalize()
else:
result.unsupported_airports.append(
from_entities[0]["text"].capitalize()
)
# This value will be a TIMEX. And we are only interested in a Date so
# grab the first result and drop the Time part.
# TIMEX is a format that represents DateTime expressions that include
# some ambiguity. e.g. missing a Year.
date_entities = recognizer_result.entities.get("datetime", [])
if date_entities:
timex = date_entities[0]["timex"]
if timex:
datetime = timex[0].split("T")[0]
result.travel_date = datetime
else:
result.travel_date = None
except Exception as err:
print(err)
return intent, result
|
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/luis_helper.py/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/luis_helper.py",
"repo_id": "botbuilder-python",
"token_count": 1863
}
| 424 |
Need deploy BotAppService before AzureBot
---
az login
az deployment sub create --template-file <template-file> --location <bot-region> --parameters @<parameters-file>
---
# parameters-for-template-BotApp-new-rg:
**groupName**:(required) Specifies the name of the new Resource Group.
**groupLocation**:(required) Specifies the location of the new Resource Group.
**appServiceName**:(required) The location of the App Service Plan.
**appServicePlanName**:(required) The name of the App Service Plan.
**appServicePlanLocation**: The location of the App Service Plan. Defaults to use groupLocation.
**appServicePlanSku**: The SKU of the App Service Plan. Defaults to Standard values.
**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
**appSecret**:(required for MultiTenant and SingleTenant) Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings.
# parameters-for-template-AzureBot-new-rg:
**groupName**:(required) Specifies the name of the new Resource Group.
**groupLocation**:(required) Specifies the location of the new Resource Group.
**azureBotId**:(required) The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable.
**azureBotSku**: The pricing tier of the Bot Service Registration. **Allowed values are: F0, S1(default)**.
**azureBotRegion**: Specifies the location of the new AzureBot. **Allowed values are: global(default), westeurope**.
**botEndpoint**: Use to handle client messages, Such as https://<botappServiceName>.azurewebsites.net/api/messages.
**appId**:(required) Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings.
|
botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md/0
|
{
"file_path": "botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/readme.md",
"repo_id": "botbuilder-python",
"token_count": 715
}
| 425 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from slack.web.classes.attachments import Attachment
from slack.web.classes.blocks import Block
class SlackMessage:
def __init__(self, **kwargs):
self.ephemeral = kwargs.get("ephemeral")
self.as_user = kwargs.get("as_user")
self.icon_url = kwargs.get("icon_url")
self.icon_emoji = kwargs.get("icon_emoji")
self.thread_ts = kwargs.get("thread_ts")
self.user = kwargs.get("user")
self.channel = kwargs.get("channel")
self.text = kwargs.get("text")
self.team = kwargs.get("team")
self.ts = kwargs.get("ts") # pylint: disable=invalid-name
self.username = kwargs.get("username")
self.bot_id = kwargs.get("bot_id")
self.icons = kwargs.get("icons")
self.blocks: [Block] = kwargs.get("blocks")
# Create proper Attachment objects
# It would appear that we can get dict fields from the wire that aren't defined
# in the Attachment class. So only pass in known fields.
attachments = kwargs.get("attachments")
if attachments is not None:
self.attachments = [
Attachment(**{x: att[x] for x in att if x in Attachment.attributes})
for att in kwargs.get("attachments")
]
|
botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_message.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_message.py",
"repo_id": "botbuilder-python",
"token_count": 583
}
| 426 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import BotTelemetryClient, NullTelemetryClient
class LuisRecognizerOptions:
def __init__(
self,
include_api_results: bool = None,
telemetry_client: BotTelemetryClient = NullTelemetryClient(),
log_personal_information: bool = False,
):
self.include_api_results = include_api_results
self.telemetry_client = telemetry_client
self.log_personal_information = log_personal_information
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_options.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_options.py",
"repo_id": "botbuilder-python",
"token_count": 191
}
| 427 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from msrest.serialization import Model
class Metadata(Model):
"""Metadata associated with the answer."""
_attribute_map = {
"name": {"key": "name", "type": "str"},
"value": {"key": "value", "type": "str"},
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.name = kwargs.get("name", None)
self.value = kwargs.get("value", None)
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/metadata.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/metadata.py",
"repo_id": "botbuilder-python",
"token_count": 190
}
| 428 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from copy import copy
from typing import Any, List, Union
import json
import requests
from aiohttp import ClientResponse, ClientSession
from botbuilder.core import BotTelemetryClient, NullTelemetryClient, TurnContext
from botbuilder.schema import Activity
from .http_request_utils import HttpRequestUtils
from ..qnamaker_endpoint import QnAMakerEndpoint
from ..qnamaker_options import QnAMakerOptions
from ..models import (
GenerateAnswerRequestBody,
QnAMakerTraceInfo,
QueryResult,
QueryResults,
)
QNAMAKER_TRACE_NAME = "QnAMaker"
QNAMAKER_TRACE_LABEL = "QnAMaker Trace"
QNAMAKER_TRACE_TYPE = "https://www.qnamaker.ai/schemas/trace"
class GenerateAnswerUtils:
"""
Helper class for Generate Answer API, which is used to make queries to
a single QnA Maker knowledge base and return the result.
"""
def __init__(
self,
telemetry_client: Union[BotTelemetryClient, NullTelemetryClient],
endpoint: QnAMakerEndpoint,
options: QnAMakerOptions,
http_client: ClientSession,
):
"""
Parameters:
-----------
telemetry_client: Telemetry client.
endpoint: QnA Maker endpoint details.
options: QnA Maker options to configure the instance.
http_client: HTTP client.
"""
self._telemetry_client = telemetry_client
self._endpoint = endpoint
self.options = (
options if isinstance(options, QnAMakerOptions) else QnAMakerOptions()
)
self._validate_options(self.options)
self._http_client = http_client
async def get_answers(
self, context: TurnContext, options: QnAMakerOptions = None
) -> List[QueryResult]:
result: QueryResults = await self.get_answers_raw(context, options)
return result
async def get_answers_raw(
self, context: TurnContext, options: QnAMakerOptions = None
) -> QueryResults:
if not isinstance(context, TurnContext):
raise TypeError(
"GenerateAnswerUtils.get_answers(): context must be an instance of TurnContext"
)
hydrated_options = self._hydrate_options(options)
self._validate_options(hydrated_options)
result: QueryResults = await self._query_qna_service(context, hydrated_options)
await self._emit_trace_info(context, result.answers, hydrated_options)
return result
def _validate_options(self, options: QnAMakerOptions):
if not options.score_threshold:
options.score_threshold = 0.3
if not options.top:
options.top = 1
if options.score_threshold < 0 or options.score_threshold > 1:
raise ValueError("Score threshold should be a value between 0 and 1")
if options.top < 1:
raise ValueError("QnAMakerOptions.top should be an integer greater than 0")
if not options.strict_filters:
options.strict_filters = []
if not options.timeout:
options.timeout = 100000
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 query_options.strict_filters:
hydrated_options.strict_filters = query_options.strict_filters
if (
query_options.timeout != hydrated_options.timeout
and query_options.timeout
):
hydrated_options.timeout = query_options.timeout
hydrated_options.context = query_options.context
hydrated_options.qna_id = query_options.qna_id
hydrated_options.is_test = query_options.is_test
hydrated_options.ranker_type = query_options.ranker_type
hydrated_options.strict_filters_join_operator = (
query_options.strict_filters_join_operator
)
return hydrated_options
async def _query_qna_service(
self, turn_context: TurnContext, options: QnAMakerOptions
) -> QueryResults:
url = f"{ self._endpoint.host }/knowledgebases/{ self._endpoint.knowledge_base_id }/generateAnswer"
question = GenerateAnswerRequestBody(
question=turn_context.activity.text,
top=options.top,
score_threshold=options.score_threshold,
strict_filters=options.strict_filters,
context=options.context,
qna_id=options.qna_id,
is_test=options.is_test,
ranker_type=options.ranker_type,
strict_filters_join_operator=options.strict_filters_join_operator,
)
http_request_helper = HttpRequestUtils(self._http_client)
response: Any = await http_request_helper.execute_http_request(
url, question, self._endpoint, options.timeout
)
result: QueryResults = await self._format_qna_result(response, options)
return result
async def _emit_trace_info(
self, context: TurnContext, result: List[QueryResult], options: QnAMakerOptions
):
trace_info = QnAMakerTraceInfo(
message=context.activity,
query_results=result,
knowledge_base_id=self._endpoint.knowledge_base_id,
score_threshold=options.score_threshold,
top=options.top,
strict_filters=options.strict_filters,
context=options.context,
qna_id=options.qna_id,
is_test=options.is_test,
ranker_type=options.ranker_type,
)
trace_activity = Activity(
label=QNAMAKER_TRACE_LABEL,
name=QNAMAKER_TRACE_NAME,
type="trace",
value=trace_info,
value_type=QNAMAKER_TRACE_TYPE,
)
await context.send_activity(trace_activity)
async def _format_qna_result(
self, result, options: QnAMakerOptions
) -> QueryResults:
json_res = result
if isinstance(result, ClientResponse):
json_res = await result.json()
if isinstance(result, requests.Response):
json_res = json.loads(result.text)
answers_within_threshold = [
{**answer, "score": answer["score"] / 100}
for answer in json_res["answers"]
if answer["score"] / 100 > options.score_threshold
]
sorted_answers = sorted(
answers_within_threshold, key=lambda ans: ans["score"], reverse=True
)
answers_as_query_results = [
QueryResult().deserialize(answer) for answer in sorted_answers
]
active_learning_enabled = (
json_res["activeLearningEnabled"]
if "activeLearningEnabled" in json_res
else True
)
query_answer_response = QueryResults(
answers_as_query_results, active_learning_enabled
)
return query_answer_response
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/utils/generate_answer_utils.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/utils/generate_answer_utils.py",
"repo_id": "botbuilder-python",
"token_count": 3361
}
| 429 |
{
"text": "12 years old and 3 days old and monday july 3rd, 2019 and every monday and between 3am and 5:30am and 4 acres and 4 pico meters and [email protected] and $4 and $4.25 and also 32 and 210.4 and first and 10% and 10.5% and 425-555-1234 and 3 degrees and -27.5 degrees c and the next one and the previous one",
"intents": {
"Cancel": {
"score": 0.00000156337478
},
"Delivery": {
"score": 0.0002846266
},
"EntityTests": {
"score": 0.953405857
},
"Greeting": {
"score": 8.20979437e-7
},
"Help": {
"score": 0.00000481870757
},
"None": {
"score": 0.01040122
},
"Roles": {
"score": 0.197366714
},
"search": {
"score": 0.14049834
},
"SpecifyName": {
"score": 0.000137732946
},
"Travel": {
"score": 0.0100996653
},
"Weather_GetForecast": {
"score": 0.0143940123
}
},
"entities": {
"$instance": {
"Composite1": [
{
"endIndex": 306,
"modelType": "Composite Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.880988955,
"startIndex": 0,
"text": "12 years old and 3 days old and monday july 3rd, 2019 and every monday and between 3am and 5:30am and 4 acres and 4 pico meters and [email protected] and $4 and $4.25 and also 32 and 210.4 and first and 10% and 10.5% and 425-555-1234 and 3 degrees and -27.5 degrees c and the next one and the previous one",
"type": "Composite1"
}
],
"ordinalV2": [
{
"endIndex": 47,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 44,
"text": "3rd",
"type": "builtin.ordinalV2"
},
{
"endIndex": 199,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 194,
"text": "first",
"type": "builtin.ordinalV2"
},
{
"endIndex": 285,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 277,
"text": "next one",
"type": "builtin.ordinalV2.relative"
},
{
"endIndex": 306,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 294,
"text": "previous one",
"type": "builtin.ordinalV2.relative"
}
]
},
"Composite1": [
{
"$instance": {
"age": [
{
"endIndex": 12,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 0,
"text": "12 years old",
"type": "builtin.age"
},
{
"endIndex": 27,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 17,
"text": "3 days old",
"type": "builtin.age"
}
],
"datetime": [
{
"endIndex": 8,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 0,
"text": "12 years",
"type": "builtin.datetimeV2.duration"
},
{
"endIndex": 23,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 17,
"text": "3 days",
"type": "builtin.datetimeV2.duration"
},
{
"endIndex": 53,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 32,
"text": "monday july 3rd, 2019",
"type": "builtin.datetimeV2.date"
},
{
"endIndex": 70,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 58,
"text": "every monday",
"type": "builtin.datetimeV2.set"
},
{
"endIndex": 97,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 75,
"text": "between 3am and 5:30am",
"type": "builtin.datetimeV2.timerange"
}
],
"dimension": [
{
"endIndex": 109,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 102,
"text": "4 acres",
"type": "builtin.dimension"
},
{
"endIndex": 127,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 114,
"text": "4 pico meters",
"type": "builtin.dimension"
}
],
"email": [
{
"endIndex": 150,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 132,
"text": "[email protected]",
"type": "builtin.email"
}
],
"money": [
{
"endIndex": 157,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 155,
"text": "$4",
"type": "builtin.currency"
},
{
"endIndex": 167,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 162,
"text": "$4.25",
"type": "builtin.currency"
}
],
"number": [
{
"endIndex": 2,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 0,
"text": "12",
"type": "builtin.number"
},
{
"endIndex": 18,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 17,
"text": "3",
"type": "builtin.number"
},
{
"endIndex": 53,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 49,
"text": "2019",
"type": "builtin.number"
},
{
"endIndex": 92,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 91,
"text": "5",
"type": "builtin.number"
},
{
"endIndex": 103,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 102,
"text": "4",
"type": "builtin.number"
},
{
"endIndex": 115,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 114,
"text": "4",
"type": "builtin.number"
},
{
"endIndex": 157,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 156,
"text": "4",
"type": "builtin.number"
},
{
"endIndex": 167,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 163,
"text": "4.25",
"type": "builtin.number"
},
{
"endIndex": 179,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 177,
"text": "32",
"type": "builtin.number"
},
{
"endIndex": 189,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 184,
"text": "210.4",
"type": "builtin.number"
},
{
"endIndex": 206,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 204,
"text": "10",
"type": "builtin.number"
},
{
"endIndex": 216,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 212,
"text": "10.5",
"type": "builtin.number"
},
{
"endIndex": 225,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 222,
"text": "425",
"type": "builtin.number"
},
{
"endIndex": 229,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 226,
"text": "555",
"type": "builtin.number"
},
{
"endIndex": 234,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 230,
"text": "1234",
"type": "builtin.number"
},
{
"endIndex": 240,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 239,
"text": "3",
"type": "builtin.number"
},
{
"endIndex": 258,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 253,
"text": "-27.5",
"type": "builtin.number"
},
{
"endIndex": 285,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 282,
"text": "one",
"type": "builtin.number"
},
{
"endIndex": 306,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 303,
"text": "one",
"type": "builtin.number"
}
],
"percentage": [
{
"endIndex": 207,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 204,
"text": "10%",
"type": "builtin.percentage"
},
{
"endIndex": 217,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 212,
"text": "10.5%",
"type": "builtin.percentage"
}
],
"phonenumber": [
{
"endIndex": 234,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.9,
"startIndex": 222,
"text": "425-555-1234",
"type": "builtin.phonenumber"
}
],
"temperature": [
{
"endIndex": 248,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 239,
"text": "3 degrees",
"type": "builtin.temperature"
},
{
"endIndex": 268,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 253,
"text": "-27.5 degrees c",
"type": "builtin.temperature"
}
]
},
"age": [
{
"number": 12,
"units": "Year"
},
{
"number": 3,
"units": "Day"
}
],
"datetime": [
{
"timex": [
"P12Y"
],
"type": "duration"
},
{
"timex": [
"P3D"
],
"type": "duration"
},
{
"timex": [
"2019-07-03"
],
"type": "date"
},
{
"timex": [
"XXXX-WXX-1"
],
"type": "set"
},
{
"timex": [
"(T03,T05:30,PT2H30M)"
],
"type": "timerange"
}
],
"dimension": [
{
"number": 4,
"units": "Acre"
},
{
"number": 4,
"units": "Picometer"
}
],
"email": [
"[email protected]"
],
"money": [
{
"number": 4,
"units": "Dollar"
},
{
"number": 4.25,
"units": "Dollar"
}
],
"number": [
12,
3,
2019,
5,
4,
4,
4,
4.25,
32,
210.4,
10,
10.5,
425,
555,
1234,
3,
-27.5,
1,
1
],
"percentage": [
10,
10.5
],
"phonenumber": [
"425-555-1234"
],
"temperature": [
{
"number": 3,
"units": "Degree"
},
{
"number": -27.5,
"units": "C"
}
]
}
],
"ordinalV2": [
{
"offset": 3,
"relativeTo": "start"
},
{
"offset": 1,
"relativeTo": "start"
},
{
"offset": 1,
"relativeTo": "current"
},
{
"offset": -1,
"relativeTo": "current"
}
]
},
"sentiment": {
"label": "neutral",
"score": 0.5
},
"v3": {
"response": {
"prediction": {
"entities": {
"$instance": {
"Composite1": [
{
"length": 306,
"modelType": "Composite Entity Extractor",
"modelTypeId": 4,
"recognitionSources": [
"model"
],
"score": 0.880988955,
"startIndex": 0,
"text": "12 years old and 3 days old and monday july 3rd, 2019 and every monday and between 3am and 5:30am and 4 acres and 4 pico meters and [email protected] and $4 and $4.25 and also 32 and 210.4 and first and 10% and 10.5% and 425-555-1234 and 3 degrees and -27.5 degrees c and the next one and the previous one",
"type": "Composite1"
}
],
"ordinalV2": [
{
"length": 3,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 44,
"text": "3rd",
"type": "builtin.ordinalV2"
},
{
"length": 5,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 194,
"text": "first",
"type": "builtin.ordinalV2"
},
{
"length": 8,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 277,
"text": "next one",
"type": "builtin.ordinalV2.relative"
},
{
"length": 12,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 294,
"text": "previous one",
"type": "builtin.ordinalV2.relative"
}
]
},
"Composite1": [
{
"$instance": {
"age": [
{
"length": 12,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 0,
"text": "12 years old",
"type": "builtin.age"
},
{
"length": 10,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 17,
"text": "3 days old",
"type": "builtin.age"
}
],
"datetimeV2": [
{
"length": 8,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 0,
"text": "12 years",
"type": "builtin.datetimeV2.duration"
},
{
"length": 6,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 17,
"text": "3 days",
"type": "builtin.datetimeV2.duration"
},
{
"length": 21,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 32,
"text": "monday july 3rd, 2019",
"type": "builtin.datetimeV2.date"
},
{
"length": 12,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 58,
"text": "every monday",
"type": "builtin.datetimeV2.set"
},
{
"length": 22,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 75,
"text": "between 3am and 5:30am",
"type": "builtin.datetimeV2.timerange"
}
],
"dimension": [
{
"length": 7,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 102,
"text": "4 acres",
"type": "builtin.dimension"
},
{
"length": 13,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 114,
"text": "4 pico meters",
"type": "builtin.dimension"
}
],
"email": [
{
"length": 18,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 132,
"text": "[email protected]",
"type": "builtin.email"
}
],
"money": [
{
"length": 2,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 155,
"text": "$4",
"type": "builtin.currency"
},
{
"length": 5,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 162,
"text": "$4.25",
"type": "builtin.currency"
}
],
"number": [
{
"length": 2,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 0,
"text": "12",
"type": "builtin.number"
},
{
"length": 1,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 17,
"text": "3",
"type": "builtin.number"
},
{
"length": 4,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 49,
"text": "2019",
"type": "builtin.number"
},
{
"length": 1,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 91,
"text": "5",
"type": "builtin.number"
},
{
"length": 1,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 102,
"text": "4",
"type": "builtin.number"
},
{
"length": 1,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 114,
"text": "4",
"type": "builtin.number"
},
{
"length": 1,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 156,
"text": "4",
"type": "builtin.number"
},
{
"length": 4,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 163,
"text": "4.25",
"type": "builtin.number"
},
{
"length": 2,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 177,
"text": "32",
"type": "builtin.number"
},
{
"length": 5,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 184,
"text": "210.4",
"type": "builtin.number"
},
{
"length": 2,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 204,
"text": "10",
"type": "builtin.number"
},
{
"length": 4,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 212,
"text": "10.5",
"type": "builtin.number"
},
{
"length": 3,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 222,
"text": "425",
"type": "builtin.number"
},
{
"length": 3,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 226,
"text": "555",
"type": "builtin.number"
},
{
"length": 4,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 230,
"text": "1234",
"type": "builtin.number"
},
{
"length": 1,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 239,
"text": "3",
"type": "builtin.number"
},
{
"length": 5,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 253,
"text": "-27.5",
"type": "builtin.number"
},
{
"length": 3,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 282,
"text": "one",
"type": "builtin.number"
},
{
"length": 3,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 303,
"text": "one",
"type": "builtin.number"
}
],
"percentage": [
{
"length": 3,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 204,
"text": "10%",
"type": "builtin.percentage"
},
{
"length": 5,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 212,
"text": "10.5%",
"type": "builtin.percentage"
}
],
"phonenumber": [
{
"length": 12,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"score": 0.9,
"startIndex": 222,
"text": "425-555-1234",
"type": "builtin.phonenumber"
}
],
"temperature": [
{
"length": 9,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 239,
"text": "3 degrees",
"type": "builtin.temperature"
},
{
"length": 15,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 253,
"text": "-27.5 degrees c",
"type": "builtin.temperature"
}
]
},
"age": [
{
"number": 12,
"unit": "Year"
},
{
"number": 3,
"unit": "Day"
}
],
"datetimeV2": [
{
"type": "duration",
"values": [
{
"timex": "P12Y",
"value": "378432000"
}
]
},
{
"type": "duration",
"values": [
{
"timex": "P3D",
"value": "259200"
}
]
},
{
"type": "date",
"values": [
{
"timex": "2019-07-03",
"value": "2019-07-03"
}
]
},
{
"type": "set",
"values": [
{
"timex": "XXXX-WXX-1",
"value": "not resolved"
}
]
},
{
"type": "timerange",
"values": [
{
"end": "05:30:00",
"start": "03:00:00",
"timex": "(T03,T05:30,PT2H30M)"
}
]
}
],
"dimension": [
{
"number": 4,
"unit": "Acre"
},
{
"number": 4,
"unit": "Picometer"
}
],
"email": [
"[email protected]"
],
"money": [
{
"number": 4,
"unit": "Dollar"
},
{
"number": 4.25,
"unit": "Dollar"
}
],
"number": [
12,
3,
2019,
5,
4,
4,
4,
4.25,
32,
210.4,
10,
10.5,
425,
555,
1234,
3,
-27.5,
1,
1
],
"percentage": [
10,
10.5
],
"phonenumber": [
"425-555-1234"
],
"temperature": [
{
"number": 3,
"unit": "Degree"
},
{
"number": -27.5,
"unit": "C"
}
]
}
],
"ordinalV2": [
{
"offset": 3,
"relativeTo": "start"
},
{
"offset": 1,
"relativeTo": "start"
},
{
"offset": 1,
"relativeTo": "current"
},
{
"offset": -1,
"relativeTo": "current"
}
]
},
"intents": {
"Cancel": {
"score": 0.00000156337478
},
"Delivery": {
"score": 0.0002846266
},
"EntityTests": {
"score": 0.953405857
},
"Greeting": {
"score": 8.20979437e-7
},
"Help": {
"score": 0.00000481870757
},
"None": {
"score": 0.01040122
},
"Roles": {
"score": 0.197366714
},
"search": {
"score": 0.14049834
},
"SpecifyName": {
"score": 0.000137732946
},
"Travel": {
"score": 0.0100996653
},
"Weather_GetForecast": {
"score": 0.0143940123
}
},
"normalizedQuery": "12 years old and 3 days old and monday july 3rd, 2019 and every monday and between 3am and 5:30am and 4 acres and 4 pico meters and [email protected] and $4 and $4.25 and also 32 and 210.4 and first and 10% and 10.5% and 425-555-1234 and 3 degrees and -27.5 degrees c and the next one and the previous one",
"sentiment": {
"label": "neutral",
"score": 0.5
},
"topIntent": "EntityTests"
},
"query": "12 years old and 3 days old and monday july 3rd, 2019 and every monday and between 3am and 5:30am and 4 acres and 4 pico meters and [email protected] and $4 and $4.25 and also 32 and 210.4 and first and 10% and 10.5% and 425-555-1234 and 3 degrees and -27.5 degrees c and the next one and the previous one"
},
"options": {
"includeAllIntents": true,
"includeAPIResults": true,
"includeInstanceData": true,
"log": true,
"preferExternalEntities": true,
"slot": "production"
}
}
}
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Composite1_v3.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Composite1_v3.json",
"repo_id": "botbuilder-python",
"token_count": 25710
}
| 430 |
{
"query": "I want to travel on united",
"topScoringIntent": {
"intent": "Travel",
"score": 0.8785189
},
"intents": [
{
"intent": "Travel",
"score": 0.8785189
}
],
"entities": [
{
"entity": "united",
"type": "Airline",
"startIndex": 20,
"endIndex": 25,
"resolution": {
"values": [
"United"
]
}
}
]
}
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/MultipleIntents_ListEntityWithSingleValue.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/MultipleIntents_ListEntityWithSingleValue.json",
"repo_id": "botbuilder-python",
"token_count": 329
}
| 431 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import base64
import json
from abc import ABC, abstractmethod
from _sha256 import sha256
class TelemetryProcessor(ABC):
"""Application Insights Telemetry Processor base class for Bot"""
@property
def activity_json(self) -> json:
"""Retrieve the request body as json (Activity)."""
body_text = self.get_request_body()
if body_text:
return body_text if isinstance(body_text, dict) else json.loads(body_text)
return None
@abstractmethod
def can_process(self) -> bool:
"""Whether the processor can process the request body.
:return: True if the request body can be processed, False otherwise.
:rtype: bool
"""
return False
@abstractmethod
def get_request_body(self) -> str: # pylint: disable=inconsistent-return-statements
"""Retrieve the request body from flask/django middleware component."""
raise NotImplementedError()
def __call__(self, data, context) -> bool:
"""Traditional Web user and session ID's don't apply for Bots. This processor
replaces the identifiers to be consistent with Bot Framework's notion of
user and session id's.
Each event that gets logged (with this processor added) will contain additional
properties.
The following properties are replaced:
- context.user.id - The user ID that Application Insights uses to identify
a unique user.
- context.session.id - The session ID that APplication Insights uses to
identify a unique session.
In addition, the additional data properties are added:
- activityId - The Bot Framework's Activity ID which represents a unique
message identifier.
- channelId - The Bot Framework "Channel" (ie, slack/facebook/directline/etc)
- activityType - The Bot Framework message classification (ie, message)
:param data: Data from Application Insights
:type data: telemetry item
:param context: Context from Application Insights
:type context: context object
:returns: bool -- determines if the event is passed to the server (False = Filtered).
"""
post_data = self.activity_json
if post_data is None:
# If there is no body (not a BOT request or not configured correctly).
# We *could* filter here, but we're allowing event to go through.
return True
# Override session and user id
from_prop = post_data["from"] if "from" in post_data else None
user_id = from_prop["id"] if from_prop is not None else None
channel_id = post_data["channelId"] if "channelId" in post_data else None
conversation = (
post_data["conversation"] if "conversation" in post_data else None
)
session_id = ""
if "id" in conversation:
conversation_id = conversation["id"]
session_id = base64.b64encode(
sha256(conversation_id.encode("utf-8")).digest()
).decode()
# Set the user id on the Application Insights telemetry item.
context.user.id = channel_id + user_id
# Set the session id on the Application Insights telemetry item.
# Hashed ID is used due to max session ID length for App Insights session Id
context.session.id = session_id
# Set the activity id:
# https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#id
if "id" in post_data:
data.properties["activityId"] = post_data["id"]
# Set the channel id:
# https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#channel-id
if "channelId" in post_data:
data.properties["channelId"] = post_data["channelId"]
# Set the activity type:
# https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#type
if "type" in post_data:
data.properties["activityType"] = post_data["type"]
return True
|
botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py",
"repo_id": "botbuilder-python",
"token_count": 1565
}
| 432 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import pytest
from azure.core.exceptions import ResourceNotFoundError
from azure.storage.blob.aio import BlobServiceClient
from botbuilder.core import StoreItem
from botbuilder.azure import BlobStorage, BlobStorageSettings
from botbuilder.testing import StorageBaseTests
# local blob emulator instance blob
BLOB_STORAGE_SETTINGS = BlobStorageSettings(
account_name="",
account_key="",
container_name="test",
# Default Azure Storage Emulator Connection String
connection_string="AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq"
+ "2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;DefaultEndpointsProtocol=http;BlobEndpoint="
+ "http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;"
+ "TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;",
)
EMULATOR_RUNNING = False
def get_storage():
return BlobStorage(BLOB_STORAGE_SETTINGS)
async def reset():
storage = BlobServiceClient.from_connection_string(
BLOB_STORAGE_SETTINGS.connection_string
)
try:
await storage.delete_container(BLOB_STORAGE_SETTINGS.container_name)
except ResourceNotFoundError:
pass
class SimpleStoreItem(StoreItem):
def __init__(self, counter=1, e_tag="*"):
super(SimpleStoreItem, self).__init__()
self.counter = counter
self.e_tag = e_tag
class TestBlobStorageConstructor:
@pytest.mark.asyncio
async def test_blob_storage_init_should_error_without_blob_config(self):
try:
BlobStorage(BlobStorageSettings()) # pylint: disable=no-value-for-parameter
except Exception as error:
assert error
class TestBlobStorageBaseTests:
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_return_empty_object_when_reading_unknown_key(self):
await reset()
test_ran = await StorageBaseTests.return_empty_object_when_reading_unknown_key(
get_storage()
)
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_handle_null_keys_when_reading(self):
await reset()
test_ran = await StorageBaseTests.handle_null_keys_when_reading(get_storage())
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_handle_null_keys_when_writing(self):
await reset()
test_ran = await StorageBaseTests.handle_null_keys_when_writing(get_storage())
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_does_not_raise_when_writing_no_items(self):
await reset()
test_ran = await StorageBaseTests.does_not_raise_when_writing_no_items(
get_storage()
)
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_create_object(self):
await reset()
test_ran = await StorageBaseTests.create_object(get_storage())
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_handle_crazy_keys(self):
await reset()
test_ran = await StorageBaseTests.handle_crazy_keys(get_storage())
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_update_object(self):
await reset()
test_ran = await StorageBaseTests.update_object(get_storage())
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_delete_object(self):
await reset()
test_ran = await StorageBaseTests.delete_object(get_storage())
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_perform_batch_operations(self):
await reset()
test_ran = await StorageBaseTests.perform_batch_operations(get_storage())
assert test_ran
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_proceeds_through_waterfall(self):
await reset()
test_ran = await StorageBaseTests.proceeds_through_waterfall(get_storage())
assert test_ran
class TestBlobStorage:
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_blob_storage_read_update_should_return_new_etag(self):
storage = BlobStorage(BLOB_STORAGE_SETTINGS)
await storage.write({"test": SimpleStoreItem(counter=1)})
data_result = await storage.read(["test"])
data_result["test"].counter = 2
await storage.write(data_result)
data_updated = await storage.read(["test"])
assert data_updated["test"].counter == 2
assert data_updated["test"].e_tag != data_result["test"].e_tag
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_blob_storage_write_should_overwrite_when_new_e_tag_is_an_asterisk(
self,
):
storage = BlobStorage(BLOB_STORAGE_SETTINGS)
await storage.write({"user": SimpleStoreItem()})
await storage.write({"user": SimpleStoreItem(counter=10, e_tag="*")})
data = await storage.read(["user"])
assert data["user"].counter == 10
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_blob_storage_delete_should_delete_according_cached_data(self):
storage = BlobStorage(BLOB_STORAGE_SETTINGS)
await storage.write({"test": SimpleStoreItem()})
try:
await storage.delete(["test"])
except Exception as error:
raise error
else:
data = await storage.read(["test"])
assert isinstance(data, dict)
assert not data.keys()
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_blob_storage_delete_should_delete_multiple_values_when_given_multiple_valid_keys(
self,
):
storage = BlobStorage(BLOB_STORAGE_SETTINGS)
await storage.write({"test": SimpleStoreItem(), "test2": SimpleStoreItem(2)})
await storage.delete(["test", "test2"])
data = await storage.read(["test", "test2"])
assert not data.keys()
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_blob_storage_delete_should_delete_values_when_given_multiple_valid_keys_and_ignore_other_data(
self,
):
storage = BlobStorage(BLOB_STORAGE_SETTINGS)
await storage.write(
{
"test": SimpleStoreItem(),
"test2": SimpleStoreItem(counter=2),
"test3": SimpleStoreItem(counter=3),
}
)
await storage.delete(["test", "test2"])
data = await storage.read(["test", "test2", "test3"])
assert len(data.keys()) == 1
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_blob_storage_delete_invalid_key_should_do_nothing_and_not_affect_cached_data(
self,
):
storage = BlobStorage(BLOB_STORAGE_SETTINGS)
await storage.write({"test": SimpleStoreItem()})
await storage.delete(["foo"])
data = await storage.read(["test"])
assert len(data.keys()) == 1
data = await storage.read(["foo"])
assert not data.keys()
@pytest.mark.skipif(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
@pytest.mark.asyncio
async def test_blob_storage_delete_invalid_keys_should_do_nothing_and_not_affect_cached_data(
self,
):
storage = BlobStorage(BLOB_STORAGE_SETTINGS)
await storage.write({"test": SimpleStoreItem()})
await storage.delete(["foo", "bar"])
data = await storage.read(["test"])
assert len(data.keys()) == 1
|
botbuilder-python/libraries/botbuilder-azure/tests/test_blob_storage.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-azure/tests/test_blob_storage.py",
"repo_id": "botbuilder-python",
"token_count": 3557
}
| 433 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=too-many-lines
import asyncio
import base64
import json
import os
import uuid
from http import HTTPStatus
from typing import List, Callable, Awaitable, Union, Dict
from msrest.serialization import Model
from botframework.connector import Channels, EmulatorApiClient
from botframework.connector.aio import ConnectorClient
from botframework.connector.auth import (
AuthenticationConfiguration,
AuthenticationConstants,
ChannelValidation,
ChannelProvider,
ClaimsIdentity,
GovernmentChannelValidation,
GovernmentConstants,
MicrosoftAppCredentials,
JwtTokenValidation,
CredentialProvider,
SimpleCredentialProvider,
SkillValidation,
AppCredentials,
SimpleChannelProvider,
MicrosoftGovernmentAppCredentials,
)
from botframework.connector.token_api import TokenApiClient
from botframework.connector.token_api.models import (
TokenStatus,
TokenExchangeRequest,
SignInUrlResponse,
TokenResponse as ConnectorTokenResponse,
)
from botbuilder.schema import (
Activity,
ActivityEventNames,
ActivityTypes,
ChannelAccount,
ConversationAccount,
ConversationParameters,
ConversationReference,
ExpectedReplies,
InvokeResponse,
TokenResponse,
ResourceResponse,
DeliveryModes,
CallerIdConstants,
)
from . import __version__
from .bot_adapter import BotAdapter
from .oauth import (
ConnectorClientBuilder,
ExtendedUserTokenProvider,
)
from .turn_context import TurnContext
from .conversation_reference_extension import get_continuation_activity
USER_AGENT = f"Microsoft-BotFramework/3.1 (BotBuilder Python/{__version__})"
OAUTH_ENDPOINT = "https://api.botframework.com"
US_GOV_OAUTH_ENDPOINT = "https://api.botframework.azure.us"
class TokenExchangeState(Model):
"""TokenExchangeState
:param connection_name: The connection name that was used.
:type connection_name: str
:param conversation: Gets or sets a reference to the conversation.
:type conversation: ~botframework.connector.models.ConversationReference
:param relates_to: Gets or sets a reference to a related parent conversation for this token exchange.
:type relates_to: ~botframework.connector.models.ConversationReference
:param bot_ur: The URL of the bot messaging endpoint.
:type bot_ur: str
:param ms_app_id: The bot's registered application ID.
:type ms_app_id: str
"""
_attribute_map = {
"connection_name": {"key": "connectionName", "type": "str"},
"conversation": {"key": "conversation", "type": "ConversationReference"},
"relates_to": {"key": "relatesTo", "type": "ConversationReference"},
"bot_url": {"key": "connectionName", "type": "str"},
"ms_app_id": {"key": "msAppId", "type": "str"},
}
def __init__(
self,
*,
connection_name: str = None,
conversation=None,
relates_to=None,
bot_url: str = None,
ms_app_id: str = None,
**kwargs,
) -> None:
super(TokenExchangeState, self).__init__(**kwargs)
self.connection_name = connection_name
self.conversation = conversation
self.relates_to = relates_to
self.bot_url = bot_url
self.ms_app_id = ms_app_id
class BotFrameworkAdapterSettings:
def __init__(
self,
app_id: str,
app_password: str = None,
channel_auth_tenant: str = None,
oauth_endpoint: str = None,
open_id_metadata: str = None,
channel_provider: ChannelProvider = None,
auth_configuration: AuthenticationConfiguration = None,
app_credentials: AppCredentials = None,
credential_provider: CredentialProvider = None,
):
"""
Contains the settings used to initialize a :class:`BotFrameworkAdapter` instance.
:param app_id: The bot application ID.
:type app_id: str
:param app_password: The bot application password.
the value os the `MicrosoftAppPassword` parameter in the `config.py` file.
:type app_password: str
:param channel_auth_tenant: The channel tenant to use in conversation
:type channel_auth_tenant: str
:param oauth_endpoint:
:type oauth_endpoint: str
:param open_id_metadata:
:type open_id_metadata: str
:param channel_provider: The channel provider
:type channel_provider: :class:`botframework.connector.auth.ChannelProvider`. Defaults to SimpleChannelProvider
if one isn't specified.
:param auth_configuration:
:type auth_configuration: :class:`botframework.connector.auth.AuthenticationConfiguration`
:param credential_provider: Defaults to SimpleCredentialProvider if one isn't specified.
:param app_credentials: Allows for a custom AppCredentials. Used, for example, for CertificateAppCredentials.
"""
self.app_id = app_id
self.app_password = app_password
self.app_credentials = app_credentials
self.channel_auth_tenant = channel_auth_tenant
self.oauth_endpoint = oauth_endpoint
self.channel_provider = (
channel_provider if channel_provider else SimpleChannelProvider()
)
self.credential_provider = (
credential_provider
if credential_provider
else SimpleCredentialProvider(self.app_id, self.app_password)
)
self.auth_configuration = auth_configuration or AuthenticationConfiguration()
# If no open_id_metadata values were passed in the settings, check the
# process' Environment Variable.
self.open_id_metadata = (
open_id_metadata
if open_id_metadata
else os.environ.get(AuthenticationConstants.BOT_OPEN_ID_METADATA_KEY)
)
class BotFrameworkAdapter(
BotAdapter, ExtendedUserTokenProvider, ConnectorClientBuilder
):
"""
Defines an adapter to connect a bot to a service endpoint.
.. remarks::
The bot adapter encapsulates authentication processes and sends activities to and
receives activities from the Bot Connector Service. When your bot receives an activity,
the adapter creates a context object, passes it to your bot's application logic, and
sends responses back to the user's channel.
The adapter processes and directs incoming activities in through the bot middleware
pipeline to your bot’s logic and then back out again.
As each activity flows in and out of the bot, each piece of middleware can inspect or act
upon the activity, both before and after the bot logic runs.
"""
def __init__(self, settings: BotFrameworkAdapterSettings):
"""
Initializes a new instance of the :class:`BotFrameworkAdapter` class.
:param settings: The settings to initialize the adapter
:type settings: :class:`BotFrameworkAdapterSettings`
"""
super(BotFrameworkAdapter, self).__init__()
self.settings = settings or BotFrameworkAdapterSettings("", "")
self._credentials = self.settings.app_credentials
self._credential_provider = SimpleCredentialProvider(
self.settings.app_id, self.settings.app_password
)
self._channel_provider = self.settings.channel_provider
self._is_emulating_oauth_cards = False
if self.settings.open_id_metadata:
ChannelValidation.open_id_metadata_endpoint = self.settings.open_id_metadata
GovernmentChannelValidation.OPEN_ID_METADATA_ENDPOINT = (
self.settings.open_id_metadata
)
# There is a significant boost in throughput if we reuse a ConnectorClient
self._connector_client_cache: Dict[str, ConnectorClient] = {}
# Cache for appCredentials to speed up token acquisition (a token is not requested unless is expired)
self._app_credential_map: Dict[str, AppCredentials] = {}
async def continue_conversation(
self,
reference: ConversationReference,
callback: Callable,
bot_id: str = None,
claims_identity: ClaimsIdentity = None,
audience: str = None,
):
"""
Continues a conversation with a user.
:param reference: A reference to the conversation to continue
:type reference: :class:`botbuilder.schema.ConversationReference
:param callback: The method to call for the resulting bot turn
:type callback: :class:`typing.Callable`
:param bot_id: The application Id of the bot. This is the appId returned by the Azure portal registration,
and is generally found in the `MicrosoftAppId` parameter in `config.py`.
:type bot_id: :class:`typing.str`
:param claims_identity: The bot claims identity
:type claims_identity: :class:`botframework.connector.auth.ClaimsIdentity`
:param audience:
:type audience: :class:`typing.str`
:raises: It raises an argument null exception.
:return: A task that represents the work queued to execute.
.. remarks::
This is often referred to as the bots *proactive messaging* flow as it lets the bot proactively
send messages to a conversation or user that are already in a communication.
Scenarios such as sending notifications or coupons to a user are enabled by this function.
"""
if not reference:
raise TypeError(
"Expected reference: ConversationReference but got None instead"
)
if not callback:
raise TypeError("Expected callback: Callable but got None instead")
# This has to have either a bot_id, in which case a ClaimsIdentity will be created, or
# a ClaimsIdentity. In either case, if an audience isn't supplied one will be created.
if not (bot_id or claims_identity):
raise TypeError("Expected bot_id or claims_identity")
if bot_id and not claims_identity:
claims_identity = ClaimsIdentity(
claims={
AuthenticationConstants.AUDIENCE_CLAIM: bot_id,
AuthenticationConstants.APP_ID_CLAIM: bot_id,
},
is_authenticated=True,
)
if not audience:
audience = self.__get_botframework_oauth_scope()
context = TurnContext(self, get_continuation_activity(reference))
context.turn_state[BotAdapter.BOT_IDENTITY_KEY] = claims_identity
context.turn_state[BotAdapter.BOT_CALLBACK_HANDLER_KEY] = callback
context.turn_state[BotAdapter.BOT_OAUTH_SCOPE_KEY] = audience
client = await self.create_connector_client(
reference.service_url, claims_identity, audience
)
context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY] = client
return await self.run_pipeline(context, callback)
async def create_conversation(
self,
reference: ConversationReference,
logic: Callable[[TurnContext], Awaitable] = None,
conversation_parameters: ConversationParameters = None,
channel_id: str = None,
service_url: str = None,
credentials: AppCredentials = None,
):
"""
Starts a new conversation with a user. Used to direct message to a member of a group.
:param reference: The conversation reference that contains the tenant
:type reference: :class:`botbuilder.schema.ConversationReference`
:param logic: The logic to use for the creation of the conversation
:type logic: :class:`typing.Callable`
:param conversation_parameters: The information to use to create the conversation
:type conversation_parameters:
:param channel_id: The ID for the channel.
:type channel_id: :class:`typing.str`
:param service_url: The channel's service URL endpoint.
:type service_url: :class:`typing.str`
:param credentials: The application credentials for the bot.
:type credentials: :class:`botframework.connector.auth.AppCredentials`
:raises: It raises a generic exception error.
:return: A task representing the work queued to execute.
.. remarks::
To start a conversation, your bot must know its account information and the user's
account information on that channel.
Most channels only support initiating a direct message (non-group) conversation.
The adapter attempts to create a new conversation on the channel, and
then sends a conversation update activity through its middleware pipeline
to the the callback method.
If the conversation is established with the specified users, the ID of the activity
will contain the ID of the new conversation.
"""
try:
if not service_url:
service_url = reference.service_url
if not service_url:
raise TypeError(
"BotFrameworkAdapter.create_conversation(): service_url or reference.service_url is required."
)
if not channel_id:
channel_id = reference.channel_id
if not channel_id:
raise TypeError(
"BotFrameworkAdapter.create_conversation(): channel_id or reference.channel_id is required."
)
parameters = (
conversation_parameters
if conversation_parameters
else ConversationParameters(
bot=reference.bot, members=[reference.user], is_group=False
)
)
# Mix in the tenant ID if specified. This is required for MS Teams.
if (
reference
and reference.conversation
and reference.conversation.tenant_id
):
# Putting tenant_id in channel_data is a temporary while we wait for the Teams API to be updated
if parameters.channel_data is None:
parameters.channel_data = {}
parameters.channel_data["tenant"] = {
"tenantId": reference.conversation.tenant_id
}
# Permanent solution is to put tenant_id in parameters.tenant_id
parameters.tenant_id = reference.conversation.tenant_id
# This is different from C# where credentials are required in the method call.
# Doing this for compatibility.
app_credentials = (
credentials
if credentials
else await self.__get_app_credentials(
self.settings.app_id, self.__get_botframework_oauth_scope()
)
)
# Create conversation
client = self._get_or_create_connector_client(service_url, app_credentials)
resource_response = await client.conversations.create_conversation(
parameters
)
event_activity = Activity(
type=ActivityTypes.event,
name=ActivityEventNames.create_conversation,
channel_id=channel_id,
service_url=service_url,
id=resource_response.activity_id
if resource_response.activity_id
else str(uuid.uuid4()),
conversation=ConversationAccount(
id=resource_response.id,
tenant_id=parameters.tenant_id,
),
channel_data=parameters.channel_data,
recipient=parameters.bot,
)
context = self._create_context(event_activity)
context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY] = client
claims_identity = ClaimsIdentity(
claims={
AuthenticationConstants.AUDIENCE_CLAIM: app_credentials.microsoft_app_id,
AuthenticationConstants.APP_ID_CLAIM: app_credentials.microsoft_app_id,
AuthenticationConstants.SERVICE_URL_CLAIM: service_url,
},
is_authenticated=True,
)
context.turn_state[BotAdapter.BOT_IDENTITY_KEY] = claims_identity
return await self.run_pipeline(context, logic)
except Exception as error:
raise error
async def process_activity(self, req, auth_header: str, logic: Callable):
"""
Creates a turn context and runs the middleware pipeline for an incoming activity.
:param req: The incoming activity
:type req: :class:`typing.str`
:param auth_header: The HTTP authentication header of the request
:type auth_header: :class:`typing.str`
:param logic: The logic to execute at the end of the adapter's middleware pipeline.
:type logic: :class:`typing.Callable`
:return: A task that represents the work queued to execute.
.. remarks::
This class processes an activity received by the bots web server. This includes any messages
sent from a user and is the method that drives what's often referred to as the
bots *reactive messaging* flow.
Call this method to reactively send a message to a conversation.
If the task completes successfully, then an :class:`InvokeResponse` is returned;
otherwise. `null` is returned.
"""
activity = await self.parse_request(req)
auth_header = auth_header or ""
identity = await self._authenticate_request(activity, auth_header)
return await self.process_activity_with_identity(activity, identity, logic)
async def process_activity_with_identity(
self, activity: Activity, identity: ClaimsIdentity, logic: Callable
):
context = self._create_context(activity)
activity.caller_id = await self.__generate_callerid(identity)
context.turn_state[BotAdapter.BOT_IDENTITY_KEY] = identity
context.turn_state[BotAdapter.BOT_CALLBACK_HANDLER_KEY] = logic
# The OAuthScope is also stored on the TurnState to get the correct AppCredentials if fetching
# a token is required.
scope = (
JwtTokenValidation.get_app_id_from_claims(identity.claims)
if SkillValidation.is_skill_claim(identity.claims)
else self.__get_botframework_oauth_scope()
)
context.turn_state[BotAdapter.BOT_OAUTH_SCOPE_KEY] = scope
client = await self.create_connector_client(
activity.service_url, identity, scope
)
context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY] = client
# Fix to assign tenant_id from channelData to Conversation.tenant_id.
# MS Teams currently sends the tenant ID in channelData and the correct behavior is to expose
# this value in Activity.Conversation.tenant_id.
# This code copies the tenant ID from channelData to Activity.Conversation.tenant_id.
# Once MS Teams sends the tenant_id in the Conversation property, this code can be removed.
if (
Channels.ms_teams == context.activity.channel_id
and context.activity.conversation is not None
and not context.activity.conversation.tenant_id
and context.activity.channel_data
):
teams_channel_data = context.activity.channel_data
if teams_channel_data.get("tenant", {}).get("id", None):
context.activity.conversation.tenant_id = str(
teams_channel_data["tenant"]["id"]
)
await self.run_pipeline(context, logic)
# Handle ExpectedReplies scenarios where the all the activities have been buffered and sent back at once
# in an invoke response.
# Return the buffered activities in the response. In this case, the invoker
# should deserialize accordingly:
# activities = ExpectedReplies().deserialize(response.body).activities
if context.activity.delivery_mode == DeliveryModes.expect_replies:
expected_replies = ExpectedReplies(
activities=context.buffered_reply_activities
).serialize()
return InvokeResponse(status=int(HTTPStatus.OK), body=expected_replies)
# Handle Invoke scenarios, which deviate from the request/request model in that
# the Bot will return a specific body and return code.
if activity.type == ActivityTypes.invoke:
invoke_response = context.turn_state.get(
BotFrameworkAdapter._INVOKE_RESPONSE_KEY # pylint: disable=protected-access
)
if invoke_response is None:
return InvokeResponse(status=int(HTTPStatus.NOT_IMPLEMENTED))
return InvokeResponse(
status=invoke_response.value.status,
body=invoke_response.value.body,
)
return None
async def __generate_callerid(self, claims_identity: ClaimsIdentity) -> str:
# Is the bot accepting all incoming messages?
is_auth_disabled = await self._credential_provider.is_authentication_disabled()
if is_auth_disabled:
# Return None so that the callerId is cleared.
return None
# Is the activity from another bot?
if SkillValidation.is_skill_claim(claims_identity.claims):
app_id = JwtTokenValidation.get_app_id_from_claims(claims_identity.claims)
return f"{CallerIdConstants.bot_to_bot_prefix}{app_id}"
# Is the activity from Public Azure?
if not self._channel_provider or self._channel_provider.is_public_azure():
return CallerIdConstants.public_azure_channel
# Is the activity from Azure Gov?
if self._channel_provider and self._channel_provider.is_government():
return CallerIdConstants.us_gov_channel
# Return None so that the callerId is cleared.
return None
async def _authenticate_request(
self, request: Activity, auth_header: str
) -> ClaimsIdentity:
"""
Allows for the overriding of authentication in unit tests.
:param request: The request to authenticate
:type request: :class:`botbuilder.schema.Activity`
:param auth_header: The authentication header
:raises: A permission exception error.
:return: The request claims identity
:rtype: :class:`botframework.connector.auth.ClaimsIdentity`
"""
claims = await JwtTokenValidation.authenticate_request(
request,
auth_header,
self._credential_provider,
await self.settings.channel_provider.get_channel_service(),
self.settings.auth_configuration,
)
if not claims.is_authenticated:
raise PermissionError("Unauthorized Access. Request is not authorized")
return claims
def _create_context(self, activity):
"""
Allows for the overriding of the context object in unit tests and derived adapters.
:param activity:
:return:
"""
return TurnContext(self, activity)
@staticmethod
async def parse_request(req):
"""
Parses and validates request
:param req:
:return:
"""
async def validate_activity(activity: Activity):
if not isinstance(activity.type, str):
raise TypeError(
"BotFrameworkAdapter.parse_request(): invalid or missing activity type."
)
return True
if not isinstance(req, Activity):
# If the req is a raw HTTP Request, try to deserialize it into an Activity and return the Activity.
if getattr(req, "body_exists", False):
try:
body = await req.json()
activity = Activity().deserialize(body)
is_valid_activity = await validate_activity(activity)
if is_valid_activity:
return activity
except Exception as error:
raise error
elif "body" in req:
try:
activity = Activity().deserialize(req["body"])
is_valid_activity = await validate_activity(activity)
if is_valid_activity:
return activity
except Exception as error:
raise error
else:
raise TypeError(
"BotFrameworkAdapter.parse_request(): received invalid request"
)
else:
# The `req` has already been deserialized to an Activity, so verify the Activity.type and return it.
is_valid_activity = await validate_activity(req)
if is_valid_activity:
return req
async def update_activity(self, context: TurnContext, activity: Activity):
"""
Replaces an activity that was previously sent to a channel. It should be noted that not all
channels support this feature.
:param context: The context object for the turn
:type context: :class:`TurnContext'
:param activity: New replacement activity
:type activity: :class:`botbuilder.schema.Activity`
:raises: A generic exception error
:return: A task that represents the work queued to execute
.. remarks::
If the activity is successfully sent, the task result contains
a :class:`botbuilder.schema.ResourceResponse` object containing the ID that
the receiving channel assigned to the activity.
Before calling this function, set the ID of the replacement activity to the ID
of the activity to replace.
"""
try:
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
return await client.conversations.update_activity(
activity.conversation.id, activity.id, activity
)
except Exception as error:
raise error
async def delete_activity(
self, context: TurnContext, reference: ConversationReference
):
"""
Deletes an activity that was previously sent to a channel. It should be noted that not all
channels support this feature.
:param context: The context object for the turn
:type context: :class:`TurnContext'
:param reference: Conversation reference for the activity to delete
:type reference: :class:`botbuilder.schema.ConversationReference`
:raises: A exception error
:return: A task that represents the work queued to execute
.. note::
The activity_id of the :class:`botbuilder.schema.ConversationReference` identifies the activity to delete.
"""
try:
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
await client.conversations.delete_activity(
reference.conversation.id, reference.activity_id
)
except Exception as error:
raise error
async def send_activities(
self, context: TurnContext, activities: List[Activity]
) -> List[ResourceResponse]:
try:
responses: List[ResourceResponse] = []
for activity in activities:
response: ResourceResponse = None
if activity.type == "delay":
try:
delay_in_ms = float(activity.value) / 1000
except TypeError:
raise TypeError(
"Unexpected delay value passed. Expected number or str type."
)
except AttributeError:
raise Exception("activity.value was not found.")
else:
await asyncio.sleep(delay_in_ms)
elif activity.type == "invokeResponse":
context.turn_state[self._INVOKE_RESPONSE_KEY] = activity
else:
if not getattr(activity, "service_url", None):
raise TypeError(
"BotFrameworkAdapter.send_activity(): service_url can not be None."
)
if (
not hasattr(activity, "conversation")
or not activity.conversation
or not getattr(activity.conversation, "id", None)
):
raise TypeError(
"BotFrameworkAdapter.send_activity(): conversation.id can not be None."
)
if activity.type == "trace" and activity.channel_id != "emulator":
pass
elif activity.reply_to_id:
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
response = await client.conversations.reply_to_activity(
activity.conversation.id, activity.reply_to_id, activity
)
else:
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
response = await client.conversations.send_to_conversation(
activity.conversation.id, activity
)
if not response:
response = ResourceResponse(id=activity.id or "")
responses.append(response)
return responses
except Exception as error:
raise error
async def delete_conversation_member(
self, context: TurnContext, member_id: str
) -> None:
"""
Deletes a member from the current conversation.
:param context: The context object for the turn
:type context: :class:`botbuilder.core.TurnContext`
:param member_id: The ID of the member to remove from the conversation
:type member_id: str
:raises: A exception error
:return: A task that represents the work queued to execute.</returns
"""
try:
if not context.activity.service_url:
raise TypeError(
"BotFrameworkAdapter.delete_conversation_member(): missing service_url"
)
if (
not context.activity.conversation
or not context.activity.conversation.id
):
raise TypeError(
"BotFrameworkAdapter.delete_conversation_member(): missing conversation or "
"conversation.id"
)
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
return await client.conversations.delete_conversation_member(
context.activity.conversation.id, member_id
)
except AttributeError as attr_e:
raise attr_e
except Exception as error:
raise error
async def get_activity_members(self, context: TurnContext, activity_id: str):
"""
Lists the members of a given activity.
:param context: The context object for the turn
:type context: :class:`botbuilder.core.TurnContext`
:param activity_id: (Optional) Activity ID to enumerate.
If not specified the current activities ID will be used.
:raises: An exception error
:return: List of Members of the activity
"""
try:
if not activity_id:
activity_id = context.activity.id
if not context.activity.service_url:
raise TypeError(
"BotFrameworkAdapter.get_activity_member(): missing service_url"
)
if (
not context.activity.conversation
or not context.activity.conversation.id
):
raise TypeError(
"BotFrameworkAdapter.get_activity_member(): missing conversation or conversation.id"
)
if not activity_id:
raise TypeError(
"BotFrameworkAdapter.get_activity_member(): missing both activity_id and "
"context.activity.id"
)
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
return await client.conversations.get_activity_members(
context.activity.conversation.id, activity_id
)
except Exception as error:
raise error
async def get_conversation_members(self, context: TurnContext):
"""
Lists the members of a current conversation.
:param context: The context object for the turn
:type context: :class:`botbuilder.core.TurnContext`
:raises: TypeError if missing service_url or conversation.id
:return: List of members of the current conversation
"""
if not context.activity.service_url:
raise TypeError(
"BotFrameworkAdapter.get_conversation_members(): missing service_url"
)
if not context.activity.conversation or not context.activity.conversation.id:
raise TypeError(
"BotFrameworkAdapter.get_conversation_members(): missing conversation or "
"conversation.id"
)
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
return await client.conversations.get_conversation_members(
context.activity.conversation.id
)
async def get_conversation_member(
self, context: TurnContext, member_id: str
) -> ChannelAccount:
"""
Retrieve a member of a current conversation.
:param context: The context object for the turn
:type context: :class:`botbuilder.core.TurnContext`
:param member_id: The member Id
:type member_id: str
:raises: A TypeError if missing member_id, service_url, or conversation.id
:return: A member of the current conversation
"""
if not context.activity.service_url:
raise TypeError(
"BotFrameworkAdapter.get_conversation_member(): missing service_url"
)
if not context.activity.conversation or not context.activity.conversation.id:
raise TypeError(
"BotFrameworkAdapter.get_conversation_member(): missing conversation or "
"conversation.id"
)
if not member_id:
raise TypeError(
"BotFrameworkAdapter.get_conversation_member(): missing memberId"
)
client = context.turn_state[BotAdapter.BOT_CONNECTOR_CLIENT_KEY]
return await client.conversations.get_conversation_member(
context.activity.conversation.id, member_id
)
async def get_conversations(
self,
service_url: str,
credentials: AppCredentials,
continuation_token: str = None,
):
"""
Lists the Conversations in which this bot has participated for a given channel server.
:param service_url: The URL of the channel server to query. This can be retrieved from
`context.activity.serviceUrl`
:type service_url: str
:param continuation_token: The continuation token from the previous page of results
:type continuation_token: str
:raises: A generic exception error
:return: A task that represents the work queued to execute
.. remarks::
The channel server returns results in pages and each page will include a `continuationToken` that
can be used to fetch the next page of results from the server.
If the task completes successfully, the result contains a page of the members of the current conversation.
This overload may be called from outside the context of a conversation, as only the bot's service URL and
credentials are required.
"""
client = self._get_or_create_connector_client(service_url, credentials)
return await client.conversations.get_conversations(continuation_token)
async def get_user_token(
self,
context: TurnContext,
connection_name: str,
magic_code: str = None,
oauth_app_credentials: AppCredentials = None, # pylint: disable=unused-argument
) -> TokenResponse:
"""
Attempts to retrieve the token for a user that's in a login flow.
:param context: Context for the current turn of conversation with the user
:type context: :class:`botbuilder.core.TurnContext`
:param connection_name: Name of the auth connection to use
:type connection_name: str
:param magic_code" (Optional) user entered code to validate
:str magic_code" str
:param oauth_app_credentials: (Optional) AppCredentials for OAuth.
:type oauth_app_credentials: :class:`botframework.connector.auth.AppCredential`
:raises: An exception error
:returns: Token Response
:rtype: :class:'botbuilder.schema.TokenResponse`
"""
if (
context.activity.from_property is None
or not context.activity.from_property.id
):
raise Exception(
"BotFrameworkAdapter.get_user_token(): missing from or from.id"
)
if not connection_name:
raise Exception(
"get_user_token() requires a connection_name but none was provided."
)
client = await self._create_token_api_client(context, oauth_app_credentials)
result = client.user_token.get_token(
context.activity.from_property.id,
connection_name,
context.activity.channel_id,
magic_code,
)
if result is None or result.token is None:
return None
return result
async def sign_out_user(
self,
context: TurnContext,
connection_name: str = None, # pylint: disable=unused-argument
user_id: str = None,
oauth_app_credentials: AppCredentials = None,
):
"""
Signs the user out with the token server.
:param context: Context for the current turn of conversation with the user
:type context: :class:`botbuilder.core.TurnContext`
:param connection_name: Name of the auth connection to use
:type connection_name: str
:param user_id: User id of user to sign out
:type user_id: str
:param oauth_app_credentials: (Optional) AppCredentials for OAuth.
:type oauth_app_credentials: :class:`botframework.connector.auth.AppCredential`
"""
if not context.activity.from_property or not context.activity.from_property.id:
raise Exception(
"BotFrameworkAdapter.sign_out_user(): missing from_property or from_property.id"
)
if not user_id:
user_id = context.activity.from_property.id
client = await self._create_token_api_client(context, oauth_app_credentials)
client.user_token.sign_out(
user_id, connection_name, context.activity.channel_id
)
async def get_oauth_sign_in_link(
self,
context: TurnContext,
connection_name: str,
final_redirect: str = None, # pylint: disable=unused-argument
oauth_app_credentials: AppCredentials = None,
) -> str:
"""
Gets the raw sign-in link to be sent to the user for sign-in for a connection name.
:param context: Context for the current turn of conversation with the user
:type context: :class:`botbuilder.core.TurnContext`
:param connection_name: Name of the auth connection to use
:type connection_name: str
:param final_redirect: The final URL that the OAuth flow will redirect to.
:param oauth_app_credentials: (Optional) AppCredentials for OAuth.
:type oauth_app_credentials: :class:`botframework.connector.auth.AppCredential`
:return: If the task completes successfully, the result contains the raw sign-in link
"""
client = await self._create_token_api_client(context, oauth_app_credentials)
conversation = TurnContext.get_conversation_reference(context.activity)
state = TokenExchangeState(
connection_name=connection_name,
conversation=conversation,
ms_app_id=client.config.credentials.microsoft_app_id,
relates_to=context.activity.relates_to,
)
final_state = base64.b64encode(
json.dumps(state.serialize()).encode(encoding="UTF-8", errors="strict")
).decode()
return client.bot_sign_in.get_sign_in_url(final_state)
async def get_token_status(
self,
context: TurnContext,
connection_name: str = None,
user_id: str = None,
include_filter: str = None,
oauth_app_credentials: AppCredentials = None,
) -> List[TokenStatus]:
"""
Retrieves the token status for each configured connection for the given user.
:param context: Context for the current turn of conversation with the user
:type context: :class:`botbuilder.core.TurnContext`
:param connection_name: Name of the auth connection to use
:type connection_name: str
:param user_id: The user Id for which tokens are retrieved. If passing in None the userId is taken
:type user_id: str
:param include_filter: (Optional) Comma separated list of connection's to include.
Blank will return token status for all configured connections.
:type include_filter: str
:param oauth_app_credentials: (Optional) AppCredentials for OAuth.
:type oauth_app_credentials: :class:`botframework.connector.auth.AppCredential`
:returns: Array of :class:`botframework.connector.token_api.modelsTokenStatus`
"""
if not user_id and (
not context.activity.from_property or not context.activity.from_property.id
):
raise Exception(
"BotFrameworkAdapter.get_token_status(): missing from_property or from_property.id"
)
client = await self._create_token_api_client(context, oauth_app_credentials)
user_id = user_id or context.activity.from_property.id
return client.user_token.get_token_status(
user_id, context.activity.channel_id, include_filter
)
async def get_aad_tokens(
self,
context: TurnContext,
connection_name: str,
resource_urls: List[str],
user_id: str = None, # pylint: disable=unused-argument
oauth_app_credentials: AppCredentials = None,
) -> Dict[str, TokenResponse]:
"""
Retrieves Azure Active Directory tokens for particular resources on a configured connection.
:param context: Context for the current turn of conversation with the user
:type context: :class:`botbuilder.core.TurnContext`
:param connection_name: The name of the Azure Active Directory connection configured with this bot
:type connection_name: str
:param resource_urls: The list of resource URLs to retrieve tokens for
:type resource_urls: :class:`typing.List`
:param user_id: The user Id for which tokens are retrieved. If passing in null the userId is taken
from the Activity in the TurnContext.
:type user_id: str
:param oauth_app_credentials: (Optional) AppCredentials for OAuth.
:type oauth_app_credentials: :class:`botframework.connector.auth.AppCredential`
:returns: Dictionary of resource Urls to the corresponding :class:'botbuilder.schema.TokenResponse`
:rtype: :class:`typing.Dict`
"""
if not context.activity.from_property or not context.activity.from_property.id:
raise Exception(
"BotFrameworkAdapter.get_aad_tokens(): missing from_property or from_property.id"
)
client = await self._create_token_api_client(context, oauth_app_credentials)
return client.user_token.get_aad_tokens(
context.activity.from_property.id,
connection_name,
context.activity.channel_id,
resource_urls,
)
async def create_connector_client(
self, service_url: str, identity: ClaimsIdentity = None, audience: str = None
) -> ConnectorClient:
"""
Implementation of ConnectorClientProvider.create_connector_client.
:param service_url: The service URL
:param identity: The claims identity
:param audience:
:return: An instance of the :class:`ConnectorClient` class
"""
if not identity:
# This is different from C# where an exception is raised. In this case
# we are creating a ClaimsIdentity to retain compatibility with this
# method.
identity = ClaimsIdentity(
claims={
AuthenticationConstants.AUDIENCE_CLAIM: self.settings.app_id,
AuthenticationConstants.APP_ID_CLAIM: self.settings.app_id,
},
is_authenticated=True,
)
# For requests from channel App Id is in Audience claim of JWT token. For emulator it is in AppId claim.
# For unauthenticated requests we have anonymous claimsIdentity provided auth is disabled.
# For Activities coming from Emulator AppId claim contains the Bot's AAD AppId.
bot_app_id = identity.claims.get(
AuthenticationConstants.AUDIENCE_CLAIM
) or identity.claims.get(AuthenticationConstants.APP_ID_CLAIM)
# Anonymous claims and non-skill claims should fall through without modifying the scope.
credentials = None
if bot_app_id:
scope = audience
if not scope:
scope = (
JwtTokenValidation.get_app_id_from_claims(identity.claims)
if SkillValidation.is_skill_claim(identity.claims)
else self.__get_botframework_oauth_scope()
)
credentials = await self.__get_app_credentials(bot_app_id, scope)
return self._get_or_create_connector_client(service_url, credentials)
def _get_or_create_connector_client(
self, service_url: str, credentials: AppCredentials
) -> ConnectorClient:
if not credentials:
credentials = MicrosoftAppCredentials.empty()
# Get ConnectorClient from cache or create.
client_key = BotFrameworkAdapter.key_for_connector_client(
service_url, credentials.microsoft_app_id, credentials.oauth_scope
)
client = self._connector_client_cache.get(client_key)
if not client:
client = ConnectorClient(credentials, base_url=service_url)
client.config.add_user_agent(USER_AGENT)
self._connector_client_cache[client_key] = client
return client
async def get_sign_in_resource_from_user(
self,
turn_context: TurnContext,
connection_name: str,
user_id: str,
final_redirect: str = None,
) -> SignInUrlResponse:
return await self.get_sign_in_resource_from_user_and_credentials(
turn_context, None, connection_name, user_id, final_redirect
)
async def get_sign_in_resource_from_user_and_credentials(
self,
turn_context: TurnContext,
oauth_app_credentials: AppCredentials,
connection_name: str,
user_id: str,
final_redirect: str = None,
) -> SignInUrlResponse:
if not connection_name:
raise TypeError(
"BotFrameworkAdapter.get_sign_in_resource_from_user_and_credentials(): missing connection_name"
)
if not user_id:
raise TypeError(
"BotFrameworkAdapter.get_sign_in_resource_from_user_and_credentials(): missing user_id"
)
activity = turn_context.activity
app_id = self.__get_app_id(turn_context)
token_exchange_state = TokenExchangeState(
connection_name=connection_name,
conversation=ConversationReference(
activity_id=activity.id,
bot=activity.recipient,
channel_id=activity.channel_id,
conversation=activity.conversation,
locale=activity.locale,
service_url=activity.service_url,
user=activity.from_property,
),
relates_to=activity.relates_to,
ms_app_id=app_id,
)
state = base64.b64encode(
json.dumps(token_exchange_state.serialize()).encode(
encoding="UTF-8", errors="strict"
)
).decode()
client = await self._create_token_api_client(
turn_context, oauth_app_credentials
)
return client.bot_sign_in.get_sign_in_resource(
state, final_redirect=final_redirect
)
async def exchange_token(
self,
turn_context: TurnContext,
connection_name: str,
user_id: str,
exchange_request: TokenExchangeRequest,
) -> TokenResponse:
return await self.exchange_token_from_credentials(
turn_context, None, connection_name, user_id, exchange_request
)
async def exchange_token_from_credentials(
self,
turn_context: TurnContext,
oauth_app_credentials: AppCredentials,
connection_name: str,
user_id: str,
exchange_request: TokenExchangeRequest,
) -> TokenResponse:
# pylint: disable=no-member
if not connection_name:
raise TypeError(
"BotFrameworkAdapter.exchange_token(): missing connection_name"
)
if not user_id:
raise TypeError("BotFrameworkAdapter.exchange_token(): missing user_id")
if exchange_request and not exchange_request.token and not exchange_request.uri:
raise TypeError(
"BotFrameworkAdapter.exchange_token(): Either a Token or Uri property is required"
" on the TokenExchangeRequest"
)
client = await self._create_token_api_client(
turn_context, oauth_app_credentials
)
result = client.user_token.exchange_async(
user_id,
connection_name,
turn_context.activity.channel_id,
exchange_request.uri,
exchange_request.token,
)
if isinstance(result, ConnectorTokenResponse):
return TokenResponse(
channel_id=result.channel_id,
connection_name=result.connection_name,
token=result.token,
expiration=result.expiration,
)
raise TypeError(f"exchange token returned improper result: {type(result)}")
def can_process_outgoing_activity(
self, activity: Activity # pylint: disable=unused-argument
) -> bool:
return False
async def process_outgoing_activity(
self, turn_context: TurnContext, activity: Activity
) -> ResourceResponse:
raise Exception("NotImplemented")
@staticmethod
def key_for_connector_client(service_url: str, app_id: str, scope: str):
return f"{service_url if service_url else ''}:{app_id if app_id else ''}:{scope if scope else ''}"
async def _create_token_api_client(
self,
context: TurnContext,
oauth_app_credentials: AppCredentials = None,
) -> TokenApiClient:
if (
not self._is_emulating_oauth_cards
and context.activity.channel_id == "emulator"
and await self._credential_provider.is_authentication_disabled()
):
self._is_emulating_oauth_cards = True
app_id = self.__get_app_id(context)
scope = self.__get_botframework_oauth_scope()
app_credentials = oauth_app_credentials or await self.__get_app_credentials(
app_id, scope
)
if (
not self._is_emulating_oauth_cards
and context.activity.channel_id == "emulator"
and await self._credential_provider.is_authentication_disabled()
):
self._is_emulating_oauth_cards = True
# TODO: token_api_client cache
url = self.__oauth_api_url(context)
client = TokenApiClient(app_credentials, url)
client.config.add_user_agent(USER_AGENT)
if self._is_emulating_oauth_cards:
# intentionally not awaiting this call
EmulatorApiClient.emulate_oauth_cards(app_credentials, url, True)
return client
def __oauth_api_url(self, context_or_service_url: Union[TurnContext, str]) -> str:
url = None
if self._is_emulating_oauth_cards:
url = (
context_or_service_url.activity.service_url
if isinstance(context_or_service_url, object)
else context_or_service_url
)
else:
if self.settings.oauth_endpoint:
url = self.settings.oauth_endpoint
else:
url = (
US_GOV_OAUTH_ENDPOINT
if self.settings.channel_provider.is_government()
else OAUTH_ENDPOINT
)
return url
@staticmethod
def key_for_app_credentials(app_id: str, scope: str):
return f"{app_id}:{scope}"
async def __get_app_credentials(
self, app_id: str, oauth_scope: str
) -> AppCredentials:
if not app_id:
return MicrosoftAppCredentials.empty()
# get from the cache if it's there
cache_key = BotFrameworkAdapter.key_for_app_credentials(app_id, oauth_scope)
app_credentials = self._app_credential_map.get(cache_key)
if app_credentials:
return app_credentials
# If app credentials were provided, use them as they are the preferred choice moving forward
if self._credentials:
self._app_credential_map[cache_key] = self._credentials
return self._credentials
# Credentials not found in cache, build them
app_credentials = await self.__build_credentials(app_id, oauth_scope)
# Cache the credentials for later use
self._app_credential_map[cache_key] = app_credentials
return app_credentials
async def __build_credentials(
self, app_id: str, oauth_scope: str = None
) -> AppCredentials:
app_password = await self._credential_provider.get_app_password(app_id)
if self._channel_provider.is_government():
return MicrosoftGovernmentAppCredentials(
app_id,
app_password,
self.settings.channel_auth_tenant,
scope=oauth_scope,
)
return MicrosoftAppCredentials(
app_id,
app_password,
self.settings.channel_auth_tenant,
oauth_scope=oauth_scope,
)
def __get_botframework_oauth_scope(self) -> str:
if (
self.settings.channel_provider
and self.settings.channel_provider.is_government()
):
return GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE
return AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE
def __get_app_id(self, context: TurnContext) -> str:
identity = context.turn_state[BotAdapter.BOT_IDENTITY_KEY]
if not identity:
raise Exception("An IIdentity is required in TurnState for this operation.")
app_id = identity.claims.get(AuthenticationConstants.AUDIENCE_CLAIM)
if not app_id:
raise Exception("Unable to get the bot AppId from the audience claim.")
return app_id
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py",
"repo_id": "botbuilder-python",
"token_count": 24039
}
| 434 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import abstractmethod
from typing import Any, Awaitable, Callable, List
from botbuilder.core import Middleware, TurnContext
from botbuilder.schema import Activity, ConversationReference
from .trace_activity import from_activity, from_conversation_reference, from_error
class InterceptionMiddleware(Middleware):
async def on_turn(
self, context: TurnContext, logic: Callable[[TurnContext], Awaitable]
):
should_forward_to_application, should_intercept = await self._invoke_inbound(
context,
from_activity(context.activity, "ReceivedActivity", "Received Activity"),
)
if should_intercept:
async def aux_on_send(
ctx: TurnContext, activities: List[Activity], next_send: Callable
):
trace_activities = [
from_activity(activity, "SentActivity", "Sent Activity")
for activity in activities
]
await self._invoke_outbound(ctx, trace_activities)
return await next_send()
async def aux_on_update(
ctx: TurnContext, activity: Activity, next_update: Callable
):
trace_activity = from_activity(
activity, "MessageUpdate", "Updated Message"
)
await self._invoke_outbound(ctx, [trace_activity])
return await next_update()
async def aux_on_delete(
ctx: TurnContext,
reference: ConversationReference,
next_delete: Callable,
):
trace_activity = from_conversation_reference(reference)
await self._invoke_outbound(ctx, [trace_activity])
return await next_delete()
context.on_send_activities(aux_on_send)
context.on_update_activity(aux_on_update)
context.on_delete_activity(aux_on_delete)
if should_forward_to_application:
try:
await logic()
except Exception as err:
trace_activity = from_error(str(err))
await self._invoke_outbound(context, [trace_activity])
raise err
if should_intercept:
await self._invoke_trace_state(context)
@abstractmethod
async def _inbound(self, context: TurnContext, trace_activity: Activity) -> Any:
raise NotImplementedError()
@abstractmethod
async def _outbound(
self, context: TurnContext, trace_activities: List[Activity]
) -> Any:
raise NotImplementedError()
@abstractmethod
async def _trace_state(self, context: TurnContext) -> Any:
raise NotImplementedError()
async def _invoke_inbound(
self, context: TurnContext, trace_activity: Activity
) -> Any:
try:
return await self._inbound(context, trace_activity)
except Exception as err:
print(f"Exception in inbound interception {str(err)}")
return True, False
async def _invoke_outbound(
self, context: TurnContext, trace_activities: List[Activity]
) -> Any:
try:
return await self._outbound(context, trace_activities)
except Exception as err:
print(f"Exception in outbound interception {str(err)}")
async def _invoke_trace_state(self, context: TurnContext) -> Any:
try:
return await self._trace_state(context)
except Exception as err:
print(f"Exception in state interception {str(err)}")
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/inspection/interception_middleware.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/inspection/interception_middleware.py",
"repo_id": "botbuilder-python",
"token_count": 1591
}
| 435 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .bot_state import BotState
from .turn_context import TurnContext
from .storage import Storage
class PrivateConversationState(BotState):
def __init__(self, storage: Storage, namespace: str = ""):
async def aux_func(context: TurnContext) -> str:
nonlocal self
return await self.get_storage_key(context)
self.namespace = namespace
super().__init__(storage, aux_func)
def get_storage_key(self, turn_context: TurnContext) -> str:
activity = turn_context.activity
channel_id = activity.channel_id if activity is not None else None
if not channel_id:
raise Exception("missing activity.channel_id")
if activity and activity.conversation and activity.conversation.id is not None:
conversation_id = activity.conversation.id
else:
raise Exception("missing activity.conversation.id")
if (
activity
and activity.from_property
and activity.from_property.id is not None
):
user_id = activity.from_property.id
else:
raise Exception("missing activity.from_property.id")
return f"{channel_id}/conversations/{ conversation_id }/users/{ user_id }/{ self.namespace }"
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/private_conversation_state.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/private_conversation_state.py",
"repo_id": "botbuilder-python",
"token_count": 529
}
| 436 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.schema import Activity
from .bot_framework_skill import BotFrameworkSkill
class SkillConversationIdFactoryOptions:
def __init__(
self,
from_bot_oauth_scope: str,
from_bot_id: str,
activity: Activity,
bot_framework_skill: BotFrameworkSkill,
):
self.from_bot_oauth_scope = from_bot_oauth_scope
self.from_bot_id = from_bot_id
self.activity = activity
self.bot_framework_skill = bot_framework_skill
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/skill_conversation_id_factory_options.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/skill_conversation_id_factory_options.py",
"repo_id": "botbuilder-python",
"token_count": 227
}
| 437 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Tuple
from botframework.connector import Channels
from botframework.connector.aio import ConnectorClient
from botframework.connector.teams import TeamsConnectorClient
from botbuilder.core.teams.teams_activity_extensions import (
teams_get_meeting_info,
teams_get_channel_data,
)
from botbuilder.core import (
CloudAdapterBase,
BotFrameworkAdapter,
TurnContext,
BotAdapter,
)
from botbuilder.schema import Activity, ConversationParameters, ConversationReference
from botbuilder.schema.teams import (
ChannelInfo,
MeetingInfo,
TeamDetails,
TeamsChannelData,
TeamsChannelAccount,
TeamsPagedMembersResult,
TeamsMeetingParticipant,
)
class TeamsInfo:
@staticmethod
async def send_message_to_teams_channel(
turn_context: TurnContext,
activity: Activity,
teams_channel_id: str,
*,
bot_app_id: str = None,
) -> Tuple[ConversationReference, str]:
if not turn_context:
raise ValueError("The turn_context cannot be None")
if not turn_context.activity:
raise ValueError("The activity inside turn context cannot be None")
if not activity:
raise ValueError("The activity cannot be None")
if not teams_channel_id:
raise ValueError("The teams_channel_id cannot be None or empty")
if not bot_app_id:
return await TeamsInfo._legacy_send_message_to_teams_channel(
turn_context, activity, teams_channel_id
)
conversation_reference: ConversationReference = None
new_activity_id = ""
service_url = turn_context.activity.service_url
conversation_parameters = ConversationParameters(
is_group=True,
channel_data=TeamsChannelData(channel=ChannelInfo(id=teams_channel_id)),
activity=activity,
)
async def aux_callback(
new_turn_context,
):
nonlocal new_activity_id
nonlocal conversation_reference
new_activity_id = new_turn_context.activity.id
conversation_reference = TurnContext.get_conversation_reference(
new_turn_context.activity
)
adapter: CloudAdapterBase = turn_context.adapter
await adapter.create_conversation(
bot_app_id,
aux_callback,
conversation_parameters,
Channels.ms_teams,
service_url,
None,
)
return (conversation_reference, new_activity_id)
@staticmethod
async def _legacy_send_message_to_teams_channel(
turn_context: TurnContext, activity: Activity, teams_channel_id: str
) -> Tuple[ConversationReference, str]:
old_ref = TurnContext.get_conversation_reference(turn_context.activity)
conversation_parameters = ConversationParameters(
is_group=True,
channel_data={"channel": {"id": teams_channel_id}},
activity=activity,
)
# if this version of the method is called the adapter probably wont be CloudAdapter
adapter: BotFrameworkAdapter = turn_context.adapter
result = await adapter.create_conversation(
old_ref, TeamsInfo._create_conversation_callback, conversation_parameters
)
return (result[0], result[1])
@staticmethod
async def _create_conversation_callback(
new_turn_context,
) -> Tuple[ConversationReference, str]:
new_activity_id = new_turn_context.activity.id
conversation_reference = TurnContext.get_conversation_reference(
new_turn_context.activity
)
return (conversation_reference, new_activity_id)
@staticmethod
async def get_team_details(
turn_context: TurnContext, team_id: str = ""
) -> TeamDetails:
if not team_id:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
raise TypeError(
"TeamsInfo.get_team_details: method is only valid within the scope of MS Teams Team."
)
teams_connector = await TeamsInfo.get_teams_connector_client(turn_context)
return teams_connector.teams.get_team_details(team_id)
@staticmethod
async def get_team_channels(
turn_context: TurnContext, team_id: str = ""
) -> List[ChannelInfo]:
if not team_id:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
raise TypeError(
"TeamsInfo.get_team_channels: method is only valid within the scope of MS Teams Team."
)
teams_connector = await TeamsInfo.get_teams_connector_client(turn_context)
return teams_connector.teams.get_teams_channels(team_id).conversations
@staticmethod
async def get_team_members(
turn_context: TurnContext, team_id: str = ""
) -> List[TeamsChannelAccount]:
if not team_id:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
raise TypeError(
"TeamsInfo.get_team_members: method is only valid within the scope of MS Teams Team."
)
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_members(
connector_client,
turn_context.activity.conversation.id,
)
@staticmethod
async def get_members(turn_context: TurnContext) -> List[TeamsChannelAccount]:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
conversation_id = turn_context.activity.conversation.id
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_members(connector_client, conversation_id)
return await TeamsInfo.get_team_members(turn_context, team_id)
@staticmethod
async def get_paged_team_members(
turn_context: TurnContext,
team_id: str = "",
continuation_token: str = None,
page_size: int = None,
) -> List[TeamsPagedMembersResult]:
if not team_id:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
raise TypeError(
"TeamsInfo.get_team_members: method is only valid within the scope of MS Teams Team."
)
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_paged_members(
connector_client,
team_id,
continuation_token,
page_size,
)
@staticmethod
async def get_paged_members(
turn_context: TurnContext, continuation_token: str = None, page_size: int = None
) -> List[TeamsPagedMembersResult]:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
conversation_id = turn_context.activity.conversation.id
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_paged_members(
connector_client, conversation_id, continuation_token, page_size
)
return await TeamsInfo.get_paged_team_members(
turn_context, team_id, continuation_token, page_size
)
@staticmethod
async def get_team_member(
turn_context: TurnContext, team_id: str = "", member_id: str = None
) -> TeamsChannelAccount:
if not team_id:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
raise TypeError(
"TeamsInfo.get_team_member: method is only valid within the scope of MS Teams Team."
)
if not member_id:
raise TypeError("TeamsInfo.get_team_member: method requires a member_id")
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_member(
connector_client, turn_context.activity.conversation.id, member_id
)
@staticmethod
async def get_member(
turn_context: TurnContext, member_id: str
) -> TeamsChannelAccount:
team_id = TeamsInfo.get_team_id(turn_context)
if not team_id:
conversation_id = turn_context.activity.conversation.id
connector_client = await TeamsInfo._get_connector_client(turn_context)
return await TeamsInfo._get_member(
connector_client, conversation_id, member_id
)
return await TeamsInfo.get_team_member(turn_context, team_id, member_id)
@staticmethod
async def get_meeting_participant(
turn_context: TurnContext,
meeting_id: str = None,
participant_id: str = None,
tenant_id: str = None,
) -> TeamsMeetingParticipant:
meeting_id = (
meeting_id
if meeting_id
else teams_get_meeting_info(turn_context.activity).id
)
if meeting_id is None:
raise TypeError(
"TeamsInfo._get_meeting_participant: method requires a meeting_id"
)
participant_id = (
participant_id
if participant_id
else turn_context.activity.from_property.aad_object_id
)
if participant_id is None:
raise TypeError(
"TeamsInfo._get_meeting_participant: method requires a participant_id"
)
tenant_id = (
tenant_id
if tenant_id
else teams_get_channel_data(turn_context.activity).tenant.id
)
if tenant_id is None:
raise TypeError(
"TeamsInfo._get_meeting_participant: method requires a tenant_id"
)
connector_client = await TeamsInfo.get_teams_connector_client(turn_context)
return connector_client.teams.fetch_participant(
meeting_id, participant_id, tenant_id
)
@staticmethod
async def get_meeting_info(
turn_context: TurnContext, meeting_id: str = None
) -> MeetingInfo:
meeting_id = (
meeting_id
if meeting_id
else teams_get_meeting_info(turn_context.activity).id
)
if meeting_id is None:
raise TypeError(
"TeamsInfo._get_meeting_participant: method requires a meeting_id or "
"TurnContext that contains a meeting id"
)
connector_client = await TeamsInfo.get_teams_connector_client(turn_context)
return connector_client.teams.fetch_meeting(meeting_id)
@staticmethod
async def get_teams_connector_client(
turn_context: TurnContext,
) -> TeamsConnectorClient:
# A normal connector client is retrieved in order to use the credentials
# while creating a TeamsConnectorClient below
connector_client = await TeamsInfo._get_connector_client(turn_context)
return TeamsConnectorClient(
connector_client.config.credentials,
turn_context.activity.service_url,
)
@staticmethod
def get_team_id(turn_context: TurnContext):
channel_data = TeamsChannelData(**turn_context.activity.channel_data)
if channel_data.team:
return channel_data.team["id"]
return ""
@staticmethod
async def _get_connector_client(turn_context: TurnContext) -> ConnectorClient:
connector_client = turn_context.turn_state.get(
BotAdapter.BOT_CONNECTOR_CLIENT_KEY
)
if connector_client is None:
raise ValueError("This method requires a connector client.")
return connector_client
@staticmethod
async def _get_members(
connector_client: ConnectorClient, conversation_id: str
) -> List[TeamsChannelAccount]:
if connector_client is None:
raise TypeError("TeamsInfo._get_members.connector_client: cannot be None.")
if not conversation_id:
raise TypeError("TeamsInfo._get_members.conversation_id: cannot be empty.")
teams_members = []
members = await connector_client.conversations.get_conversation_members(
conversation_id
)
for member in members:
teams_members.append(
TeamsChannelAccount().deserialize(
dict(member.serialize(), **member.additional_properties)
)
)
return teams_members
@staticmethod
async def _get_paged_members(
connector_client: ConnectorClient,
conversation_id: str,
continuation_token: str = None,
page_size: int = None,
) -> List[TeamsPagedMembersResult]:
if connector_client is None:
raise TypeError(
"TeamsInfo._get_paged_members.connector_client: cannot be None."
)
if not conversation_id:
raise TypeError(
"TeamsInfo._get_paged_members.conversation_id: cannot be empty."
)
return (
await connector_client.conversations.get_teams_conversation_paged_members(
conversation_id, page_size, continuation_token
)
)
@staticmethod
async def _get_member(
connector_client: ConnectorClient, conversation_id: str, member_id: str
) -> TeamsChannelAccount:
if connector_client is None:
raise TypeError("TeamsInfo._get_member.connector_client: cannot be None.")
if not conversation_id:
raise TypeError("TeamsInfo._get_member.conversation_id: cannot be empty.")
if not member_id:
raise TypeError("TeamsInfo._get_member.member_id: cannot be empty.")
member: TeamsChannelAccount = (
await connector_client.conversations.get_conversation_member(
conversation_id, member_id
)
)
return TeamsChannelAccount().deserialize(
dict(member.serialize(), **member.additional_properties)
)
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/teams/teams_info.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/teams/teams_info.py",
"repo_id": "botbuilder-python",
"token_count": 6076
}
| 438 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from unittest.mock import Mock
from typing import Any
import aiounittest
from botbuilder.core.streaming import StreamingRequestHandler
from botframework.streaming.transport.web_socket import (
WebSocket,
WebSocketState,
WebSocketCloseStatus,
WebSocketMessage,
WebSocketMessageType,
)
class MockWebSocket(WebSocket):
# pylint: disable=unused-argument
def __init__(self):
super(MockWebSocket, self).__init__()
self.receive_called = False
def dispose(self):
return
async def close(self, close_status: WebSocketCloseStatus, status_description: str):
return
async def receive(self) -> WebSocketMessage:
self.receive_called = True
async def send(
self, buffer: Any, message_type: WebSocketMessageType, end_of_message: bool
):
raise Exception
@property
def status(self) -> WebSocketState:
return WebSocketState.OPEN
class TestStramingRequestHandler(aiounittest.AsyncTestCase):
async def test_listen(self):
mock_bot = Mock()
mock_activity_processor = Mock()
mock_web_socket = MockWebSocket()
sut = StreamingRequestHandler(
mock_bot, mock_activity_processor, mock_web_socket
)
await sut.listen()
assert mock_web_socket.receive_called
|
botbuilder-python/libraries/botbuilder-core/tests/streaming/test_streaming_request_handler.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/streaming/test_streaming_request_handler.py",
"repo_id": "botbuilder-python",
"token_count": 527
}
| 439 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import pytest
from botbuilder.core import MemoryStorage, StoreItem
from botbuilder.testing import StorageBaseTests
def get_storage():
return MemoryStorage()
class SimpleStoreItem(StoreItem):
def __init__(self, counter=1, e_tag="*"):
super(SimpleStoreItem, self).__init__()
self.counter = counter
self.e_tag = e_tag
class TestMemoryStorageConstructor:
def test_initializing_memory_storage_without_data_should_still_have_memory(self):
storage = MemoryStorage()
assert storage.memory is not None
assert isinstance(storage.memory, dict)
def test_memory_storage__e_tag_should_start_at_0(self):
storage = MemoryStorage()
assert storage._e_tag == 0 # pylint: disable=protected-access
@pytest.mark.asyncio
async def test_memory_storage_initialized_with_memory_should_have_accessible_data(
self,
):
storage = MemoryStorage({"test": SimpleStoreItem()})
data = await storage.read(["test"])
assert "test" in data
assert data["test"].counter == 1
assert len(data.keys()) == 1
class TestMemoryStorageBaseTests:
@pytest.mark.asyncio
async def test_return_empty_object_when_reading_unknown_key(self):
test_ran = await StorageBaseTests.return_empty_object_when_reading_unknown_key(
get_storage()
)
assert test_ran
@pytest.mark.asyncio
async def test_handle_null_keys_when_reading(self):
test_ran = await StorageBaseTests.handle_null_keys_when_reading(get_storage())
assert test_ran
@pytest.mark.asyncio
async def test_handle_null_keys_when_writing(self):
test_ran = await StorageBaseTests.handle_null_keys_when_writing(get_storage())
assert test_ran
@pytest.mark.asyncio
async def test_does_not_raise_when_writing_no_items(self):
test_ran = await StorageBaseTests.does_not_raise_when_writing_no_items(
get_storage()
)
assert test_ran
@pytest.mark.asyncio
async def test_create_object(self):
test_ran = await StorageBaseTests.create_object(get_storage())
assert test_ran
@pytest.mark.asyncio
async def test_handle_crazy_keys(self):
test_ran = await StorageBaseTests.handle_crazy_keys(get_storage())
assert test_ran
@pytest.mark.asyncio
async def test_update_object(self):
test_ran = await StorageBaseTests.update_object(get_storage())
assert test_ran
@pytest.mark.asyncio
async def test_delete_object(self):
test_ran = await StorageBaseTests.delete_object(get_storage())
assert test_ran
@pytest.mark.asyncio
async def test_perform_batch_operations(self):
test_ran = await StorageBaseTests.perform_batch_operations(get_storage())
assert test_ran
@pytest.mark.asyncio
async def test_proceeds_through_waterfall(self):
test_ran = await StorageBaseTests.proceeds_through_waterfall(get_storage())
assert test_ran
class TestMemoryStorage:
@pytest.mark.asyncio
async def test_memory_storage_write_should_overwrite_when_new_e_tag_is_an_asterisk_1(
self,
):
storage = MemoryStorage()
await storage.write({"user": SimpleStoreItem(e_tag="1")})
await storage.write({"user": SimpleStoreItem(counter=10, e_tag="*")})
data = await storage.read(["user"])
assert data["user"].counter == 10
@pytest.mark.asyncio
async def test_memory_storage_write_should_overwrite_when_new_e_tag_is_an_asterisk_2(
self,
):
storage = MemoryStorage()
await storage.write({"user": SimpleStoreItem(e_tag="1")})
await storage.write({"user": SimpleStoreItem(counter=5, e_tag="1")})
data = await storage.read(["user"])
assert data["user"].counter == 5
@pytest.mark.asyncio
async def test_memory_storage_read_with_invalid_key_should_return_empty_dict(self):
storage = MemoryStorage()
data = await storage.read(["test"])
assert isinstance(data, dict)
assert not data.keys()
@pytest.mark.asyncio
async def test_memory_storage_delete_should_delete_according_cached_data(self):
storage = MemoryStorage({"test": "test"})
try:
await storage.delete(["test"])
except Exception as error:
raise error
else:
data = await storage.read(["test"])
assert isinstance(data, dict)
assert not data.keys()
@pytest.mark.asyncio
async def test_memory_storage_delete_should_delete_multiple_values_when_given_multiple_valid_keys(
self,
):
storage = MemoryStorage(
{"test": SimpleStoreItem(), "test2": SimpleStoreItem(2, "2")}
)
await storage.delete(["test", "test2"])
data = await storage.read(["test", "test2"])
assert not data.keys()
@pytest.mark.asyncio
async def test_memory_storage_delete_should_delete_values_when_given_multiple_valid_keys_and_ignore_other_data(
self,
):
storage = MemoryStorage(
{
"test": SimpleStoreItem(),
"test2": SimpleStoreItem(2, "2"),
"test3": SimpleStoreItem(3, "3"),
}
)
await storage.delete(["test", "test2"])
data = await storage.read(["test", "test2", "test3"])
assert len(data.keys()) == 1
@pytest.mark.asyncio
async def test_memory_storage_delete_invalid_key_should_do_nothing_and_not_affect_cached_data(
self,
):
storage = MemoryStorage({"test": "test"})
await storage.delete(["foo"])
data = await storage.read(["test"])
assert len(data.keys()) == 1
data = await storage.read(["foo"])
assert not data.keys()
@pytest.mark.asyncio
async def test_memory_storage_delete_invalid_keys_should_do_nothing_and_not_affect_cached_data(
self,
):
storage = MemoryStorage({"test": "test"})
await storage.delete(["foo", "bar"])
data = await storage.read(["test"])
assert len(data.keys()) == 1
|
botbuilder-python/libraries/botbuilder-core/tests/test_memory_storage.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_memory_storage.py",
"repo_id": "botbuilder-python",
"token_count": 2614
}
| 440 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Union
from .token import Token
class Tokenizer:
"""Provides a default tokenizer implementation."""
@staticmethod
def default_tokenizer( # pylint: disable=unused-argument
text: str, locale: str = None
) -> [Token]:
"""
Simple tokenizer that breaks on spaces and punctuation. The only normalization is to lowercase.
Parameter:
---------
text: The input text.
locale: (Optional) Identifies the locale of the input text.
"""
tokens: [Token] = []
token: Union[Token, None] = None
# Parse text
length: int = len(text) if text else 0
i: int = 0
while i < length:
# Get both the UNICODE value of the current character and the complete character itself
# which can potentially be multiple segments
code_point = ord(text[i])
char = chr(code_point)
# Process current character
if Tokenizer._is_breaking_char(code_point):
# Character is in Unicode Plane 0 and is in an excluded block
Tokenizer._append_token(tokens, token, i - 1)
token = None
elif code_point > 0xFFFF:
# Character is in a Supplementary Unicode Plane. This is where emoji live so
# we're going to just break each character in this range out as its own token
Tokenizer._append_token(tokens, token, i - 1)
token = None
tokens.append(Token(start=i, end=i, text=char, normalized=char))
elif token is None:
# Start a new token
token = Token(start=i, end=0, text=char, normalized=None)
else:
# Add onto current token
token.text += char
i += 1
Tokenizer._append_token(tokens, token, length - 1)
return tokens
@staticmethod
def _is_breaking_char(code_point) -> bool:
return (
Tokenizer._is_between(code_point, 0x0000, 0x002F)
or Tokenizer._is_between(code_point, 0x003A, 0x0040)
or Tokenizer._is_between(code_point, 0x005B, 0x0060)
or Tokenizer._is_between(code_point, 0x007B, 0x00BF)
or Tokenizer._is_between(code_point, 0x02B9, 0x036F)
or Tokenizer._is_between(code_point, 0x2000, 0x2BFF)
or Tokenizer._is_between(code_point, 0x2E00, 0x2E7F)
)
@staticmethod
def _is_between(value: int, from_val: int, to_val: int) -> bool:
"""
Parameters:
-----------
value: number value
from: low range
to: high range
"""
return from_val <= value <= to_val
@staticmethod
def _append_token(tokens: [Token], token: Token, end: int):
if token is not None:
token.end = end
token.normalized = token.text.lower()
tokens.append(token)
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/tokenizer.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/tokenizer.py",
"repo_id": "botbuilder-python",
"token_count": 1390
}
| 441 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Iterable
from botbuilder.core import ComponentRegistration
from botbuilder.dialogs.memory import (
ComponentMemoryScopesBase,
ComponentPathResolversBase,
PathResolverBase,
)
from botbuilder.dialogs.memory.scopes import (
TurnMemoryScope,
SettingsMemoryScope,
DialogMemoryScope,
DialogContextMemoryScope,
DialogClassMemoryScope,
ClassMemoryScope,
MemoryScope,
ThisMemoryScope,
ConversationMemoryScope,
UserMemoryScope,
)
from botbuilder.dialogs.memory.path_resolvers import (
AtAtPathResolver,
AtPathResolver,
DollarPathResolver,
HashPathResolver,
PercentPathResolver,
)
class DialogsComponentRegistration(
ComponentRegistration, ComponentMemoryScopesBase, ComponentPathResolversBase
):
def get_memory_scopes(self) -> Iterable[MemoryScope]:
yield TurnMemoryScope()
yield SettingsMemoryScope()
yield DialogMemoryScope()
yield DialogContextMemoryScope()
yield DialogClassMemoryScope()
yield ClassMemoryScope()
yield ThisMemoryScope()
yield ConversationMemoryScope()
yield UserMemoryScope()
def get_path_resolvers(self) -> Iterable[PathResolverBase]:
yield AtAtPathResolver()
yield AtPathResolver()
yield DollarPathResolver()
yield HashPathResolver()
yield PercentPathResolver()
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialogs_component_registration.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialogs_component_registration.py",
"repo_id": "botbuilder-python",
"token_count": 514
}
| 442 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .bot_state_memory_scope import BotStateMemoryScope
from .class_memory_scope import ClassMemoryScope
from .conversation_memory_scope import ConversationMemoryScope
from .dialog_class_memory_scope import DialogClassMemoryScope
from .dialog_context_memory_scope import DialogContextMemoryScope
from .dialog_memory_scope import DialogMemoryScope
from .memory_scope import MemoryScope
from .settings_memory_scope import SettingsMemoryScope
from .this_memory_scope import ThisMemoryScope
from .turn_memory_scope import TurnMemoryScope
from .user_memory_scope import UserMemoryScope
__all__ = [
"BotStateMemoryScope",
"ClassMemoryScope",
"ConversationMemoryScope",
"DialogClassMemoryScope",
"DialogContextMemoryScope",
"DialogMemoryScope",
"MemoryScope",
"SettingsMemoryScope",
"ThisMemoryScope",
"TurnMemoryScope",
"UserMemoryScope",
]
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 308
}
| 443 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Callable, Dict
from botbuilder.core import TurnContext
from botbuilder.dialogs import (
Dialog,
DialogContext,
DialogInstance,
DialogReason,
DialogTurnResult,
)
from botbuilder.schema import ActivityTypes, InputHints
from .prompt import Prompt
from .prompt_options import PromptOptions
from .prompt_recognizer_result import PromptRecognizerResult
from .prompt_validator_context import PromptValidatorContext
class ActivityPrompt(Dialog):
"""
Waits for an activity to be received.
.. remarks::
This prompt requires a validator be passed in and is useful when waiting for non-message
activities like an event to be received. The validator can ignore received events until the
expected activity is received.
:var persisted_options:
:typevar persisted_options: str
:var persisted_state:
:vartype persisted_state: str
"""
persisted_options = "options"
persisted_state = "state"
def __init__(
self, dialog_id: str, validator: Callable[[PromptValidatorContext], bool]
):
"""
Initializes a new instance of the :class:`ActivityPrompt` class.
:param dialog_id: Unique ID of the dialog within its parent :class:`DialogSet` or :class:`ComponentDialog`.
:type dialog_id: str
:param validator: Validator that will be called each time a new activity is received.
:type validator: :class:`typing.Callable[[:class:`PromptValidatorContext`], bool]`
"""
Dialog.__init__(self, dialog_id)
if validator is None:
raise TypeError("validator was expected but received None")
self._validator = validator
async def begin_dialog(
self, dialog_context: DialogContext, options: PromptOptions = None
) -> DialogTurnResult:
"""
Called when a prompt dialog is pushed onto the dialog stack and is being activated.
:param dialog_context: The dialog context for the current turn of the conversation.
:type dialog_context: :class:`DialogContext`
:param options: Optional, additional information to pass to the prompt being started.
:type options: :class:`PromptOptions`
:return Dialog.end_of_turn:
:rtype Dialog.end_of_turn: :class:`Dialog.DialogTurnResult`
"""
if not dialog_context:
raise TypeError("ActivityPrompt.begin_dialog(): dc cannot be None.")
if not isinstance(options, PromptOptions):
raise TypeError(
"ActivityPrompt.begin_dialog(): Prompt options are required for ActivityPrompts."
)
# Ensure prompts have input hint set
if options.prompt is not None and not options.prompt.input_hint:
options.prompt.input_hint = InputHints.expecting_input
if options.retry_prompt is not None and not options.retry_prompt.input_hint:
options.retry_prompt.input_hint = InputHints.expecting_input
# Initialize prompt state
state: Dict[str, object] = dialog_context.active_dialog.state
state[self.persisted_options] = options
state[self.persisted_state] = {Prompt.ATTEMPT_COUNT_KEY: 0}
# Send initial prompt
await self.on_prompt(
dialog_context.context,
state[self.persisted_state],
state[self.persisted_options],
False,
)
return Dialog.end_of_turn
async def continue_dialog(self, dialog_context: DialogContext) -> DialogTurnResult:
"""
Called when a prompt dialog is the active dialog and the user replied with a new activity.
:param dialog_context: The dialog context for the current turn of the conversation.
:type dialog_context: :class:`DialogContext`
:return Dialog.end_of_turn:
:rtype Dialog.end_of_turn: :class:`Dialog.DialogTurnResult`
"""
if not dialog_context:
raise TypeError(
"ActivityPrompt.continue_dialog(): DialogContext cannot be None."
)
# Perform base recognition
instance = dialog_context.active_dialog
state: Dict[str, object] = instance.state[self.persisted_state]
options: Dict[str, object] = instance.state[self.persisted_options]
recognized: PromptRecognizerResult = await self.on_recognize(
dialog_context.context, state, options
)
# Increment attempt count
state[Prompt.ATTEMPT_COUNT_KEY] += 1
# Validate the return value
is_valid = False
if self._validator is not None:
prompt_context = PromptValidatorContext(
dialog_context.context, recognized, state, options
)
is_valid = await self._validator(prompt_context)
if options is None:
options = PromptOptions()
options.number_of_attempts += 1
elif recognized.succeeded:
is_valid = True
# Return recognized value or re-prompt
if is_valid:
return await dialog_context.end_dialog(recognized.value)
if (
dialog_context.context.activity.type == ActivityTypes.message
and not dialog_context.context.responded
):
await self.on_prompt(dialog_context.context, state, options, True)
return Dialog.end_of_turn
async def resume_dialog( # pylint: disable=unused-argument
self, dialog_context: DialogContext, reason: DialogReason, result: object = None
):
"""
Called when a prompt dialog resumes being the active dialog on the dialog stack, such
as when the previous active dialog on the stack completes.
.. remarks::
Prompts are typically leaf nodes on the stack but the dev is free to push other dialogs
on top of the stack which will result in the prompt receiving an unexpected call to
:meth:`ActivityPrompt.resume_dialog()` when the pushed on dialog ends.
To avoid the prompt prematurely ending, we need to implement this method and
simply re-prompt the user.
:param dialog_context: The dialog context for the current turn of the conversation
:type dialog_context: :class:`DialogContext`
:param reason: An enum indicating why the dialog resumed.
:type reason: :class:`DialogReason`
:param result: Optional, value returned from the previous dialog on the stack.
:type result: object
"""
await self.reprompt_dialog(dialog_context.context, dialog_context.active_dialog)
return Dialog.end_of_turn
async def reprompt_dialog(self, context: TurnContext, instance: DialogInstance):
state: Dict[str, object] = instance.state[self.persisted_state]
options: PromptOptions = instance.state[self.persisted_options]
await self.on_prompt(context, state, options, False)
async def on_prompt(
self,
context: TurnContext,
state: Dict[str, dict], # pylint: disable=unused-argument
options: PromptOptions,
is_retry: bool = False,
):
"""
Called anytime the derived class should send the user a prompt.
:param dialog_context: The dialog context for the current turn of the conversation
:type dialog_context: :class:`DialogContext`
:param state: Additional state being persisted for the prompt.
:type state: :class:`typing.Dict[str, dict]`
:param options: Options that the prompt started with in the call to :meth:`DialogContext.prompt()`.
:type options: :class:`PromptOptions`
:param isRetry: If `true` the users response wasn't recognized and the re-prompt should be sent.
:type isRetry: bool
"""
if is_retry and options.retry_prompt:
options.retry_prompt.input_hint = InputHints.expecting_input
await context.send_activity(options.retry_prompt)
elif options.prompt:
options.prompt.input_hint = InputHints.expecting_input
await context.send_activity(options.prompt)
async def on_recognize( # pylint: disable=unused-argument
self, context: TurnContext, state: Dict[str, object], options: PromptOptions
) -> PromptRecognizerResult:
"""
When overridden in a derived class, attempts to recognize the incoming activity.
:param context: Context for the current turn of conversation with the user.
:type context: :class:`botbuilder.core.TurnContext`
:param state: Contains state for the current instance of the prompt on the dialog stack.
:type state: :class:`typing.Dict[str, dict]`
:param options: A prompt options object
:type options: :class:`PromptOptions`
:return result: constructed from the options initially provided in the call to :meth:`async def on_prompt()`
:rtype result: :class:`PromptRecognizerResult`
"""
result = PromptRecognizerResult()
result.succeeded = (True,)
result.value = context.activity
return result
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/activity_prompt.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/activity_prompt.py",
"repo_id": "botbuilder-python",
"token_count": 3539
}
| 444 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=pointless-string-statement
from collections import namedtuple
import aiounittest
from botbuilder.core import ConversationState, MemoryStorage, TurnContext, UserState
from botbuilder.core.adapters import TestAdapter
from botbuilder.dialogs import (
Dialog,
DialogContext,
DialogContainer,
DialogInstance,
DialogSet,
DialogState,
ObjectPath,
)
from botbuilder.dialogs.memory.scopes import (
ClassMemoryScope,
ConversationMemoryScope,
DialogMemoryScope,
UserMemoryScope,
SettingsMemoryScope,
ThisMemoryScope,
TurnMemoryScope,
)
from botbuilder.schema import (
Activity,
ActivityTypes,
ChannelAccount,
ConversationAccount,
)
class TestDialog(Dialog):
def __init__(self, id: str, message: str):
super().__init__(id)
def aux_try_get_value(state): # pylint: disable=unused-argument
return "resolved value"
ExpressionObject = namedtuple("ExpressionObject", "try_get_value")
self.message = message
self.expression = ExpressionObject(aux_try_get_value)
async def begin_dialog(self, dialog_context: DialogContext, options: object = None):
dialog_context.active_dialog.state["is_dialog"] = True
await dialog_context.context.send_activity(self.message)
return Dialog.end_of_turn
class TestContainer(DialogContainer):
def __init__(self, id: str, child: Dialog = None):
super().__init__(id)
self.child_id = None
if child:
self.dialogs.add(child)
self.child_id = child.id
async def begin_dialog(self, dialog_context: DialogContext, options: object = None):
state = dialog_context.active_dialog.state
state["is_container"] = True
if self.child_id:
state["dialog"] = DialogState()
child_dc = self.create_child_context(dialog_context)
return await child_dc.begin_dialog(self.child_id, options)
return Dialog.end_of_turn
async def continue_dialog(self, dialog_context: DialogContext):
child_dc = self.create_child_context(dialog_context)
if child_dc:
return await child_dc.continue_dialog()
return Dialog.end_of_turn
def create_child_context(self, dialog_context: DialogContext):
state = dialog_context.active_dialog.state
if state["dialog"] is not None:
child_dc = DialogContext(
self.dialogs, dialog_context.context, state["dialog"]
)
child_dc.parent = dialog_context
return child_dc
return None
class MemoryScopesTests(aiounittest.AsyncTestCase):
begin_message = Activity(
text="begin",
type=ActivityTypes.message,
channel_id="test",
from_property=ChannelAccount(id="user"),
recipient=ChannelAccount(id="bot"),
conversation=ConversationAccount(id="convo1"),
)
async def test_class_memory_scope_should_find_registered_dialog(self):
# Create ConversationState with MemoryStorage and register the state as middleware.
conversation_state = ConversationState(MemoryStorage())
# Create a DialogState property, DialogSet and register the dialogs.
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
await dialog_state.set(
context, DialogState(stack=[DialogInstance(id="test", state={})])
)
dialog_context = await dialogs.create_context(context)
# Run test
scope = ClassMemoryScope()
memory = scope.get_memory(dialog_context)
self.assertTrue(memory, "memory not returned")
self.assertEqual("test message", memory.message)
self.assertEqual("resolved value", memory.expression)
async def test_class_memory_scope_should_not_allow_set_memory_call(self):
# Create ConversationState with MemoryStorage and register the state as middleware.
conversation_state = ConversationState(MemoryStorage())
# Create a DialogState property, DialogSet and register the dialogs.
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
await dialog_state.set(
context, DialogState(stack=[DialogInstance(id="test", state={})])
)
dialog_context = await dialogs.create_context(context)
# Run test
scope = ClassMemoryScope()
with self.assertRaises(Exception) as context:
scope.set_memory(dialog_context, {})
self.assertTrue("not supported" in str(context.exception))
async def test_class_memory_scope_should_not_allow_load_and_save_changes_calls(
self,
):
# Create ConversationState with MemoryStorage and register the state as middleware.
conversation_state = ConversationState(MemoryStorage())
# Create a DialogState property, DialogSet and register the dialogs.
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
await dialog_state.set(
context, DialogState(stack=[DialogInstance(id="test", state={})])
)
dialog_context = await dialogs.create_context(context)
# Run test
scope = ClassMemoryScope()
await scope.load(dialog_context)
memory = scope.get_memory(dialog_context)
with self.assertRaises(AttributeError) as context:
memory.message = "foo"
self.assertTrue("can't set attribute" in str(context.exception))
await scope.save_changes(dialog_context)
self.assertEqual("test message", dialog.message)
async def test_conversation_memory_scope_should_return_conversation_state(self):
# Create ConversationState with MemoryStorage and register the state as middleware.
conversation_state = ConversationState(MemoryStorage())
# Create a DialogState property, DialogSet and register the dialogs.
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
context.turn_state["ConversationState"] = conversation_state
dialog_context = await dialogs.create_context(context)
# Initialize conversation state
foo_cls = namedtuple("TestObject", "foo")
conversation_prop = conversation_state.create_property("conversation")
await conversation_prop.set(context, foo_cls(foo="bar"))
await conversation_state.save_changes(context)
# Run test
scope = ConversationMemoryScope()
memory = scope.get_memory(dialog_context)
self.assertTrue(memory, "memory not returned")
# TODO: Make get_path_value take conversation.foo
test_obj = ObjectPath.get_path_value(memory, "conversation")
self.assertEqual("bar", test_obj.foo)
async def test_user_memory_scope_should_not_return_state_if_not_loaded(self):
# Initialize user state
storage = MemoryStorage()
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
user_state = UserState(storage)
context.turn_state["UserState"] = user_state
foo_cls = namedtuple("TestObject", "foo")
user_prop = user_state.create_property("conversation")
await user_prop.set(context, foo_cls(foo="bar"))
await user_state.save_changes(context)
# Replace context and user_state with new instances
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
user_state = UserState(storage)
context.turn_state["UserState"] = user_state
# Create a DialogState property, DialogSet and register the dialogs.
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
dialog_context = await dialogs.create_context(context)
# Run test
scope = UserMemoryScope()
memory = scope.get_memory(dialog_context)
self.assertIsNone(memory, "state returned")
async def test_user_memory_scope_should_return_state_once_loaded(self):
# Initialize user state
storage = MemoryStorage()
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
user_state = UserState(storage)
context.turn_state["UserState"] = user_state
foo_cls = namedtuple("TestObject", "foo")
user_prop = user_state.create_property("conversation")
await user_prop.set(context, foo_cls(foo="bar"))
await user_state.save_changes(context)
# Replace context and conversation_state with instances
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
user_state = UserState(storage)
context.turn_state["UserState"] = user_state
# Create a DialogState property, DialogSet and register the dialogs.
conversation_state = ConversationState(storage)
context.turn_state["ConversationState"] = conversation_state
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
dialog_context = await dialogs.create_context(context)
# Run test
scope = UserMemoryScope()
memory = scope.get_memory(dialog_context)
self.assertIsNone(memory, "state returned")
await scope.load(dialog_context)
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
# TODO: Make get_path_value take conversation.foo
test_obj = ObjectPath.get_path_value(memory, "conversation")
self.assertEqual("bar", test_obj.foo)
async def test_dialog_memory_scope_should_return_containers_state(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container")
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = DialogMemoryScope()
await dialog_context.begin_dialog("container")
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
self.assertTrue(memory["is_container"])
async def test_dialog_memory_scope_should_return_parent_containers_state_for_children(
self,
):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container", TestDialog("child", "test message"))
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = DialogMemoryScope()
await dialog_context.begin_dialog("container")
child_dc = dialog_context.child
self.assertIsNotNone(child_dc, "No child DC")
memory = scope.get_memory(child_dc)
self.assertIsNotNone(memory, "state not returned")
self.assertTrue(memory["is_container"])
async def test_dialog_memory_scope_should_return_childs_state_when_no_parent(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = DialogMemoryScope()
await dialog_context.begin_dialog("test")
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
self.assertTrue(memory["is_dialog"])
async def test_dialog_memory_scope_should_overwrite_parents_memory(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container", TestDialog("child", "test message"))
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = DialogMemoryScope()
await dialog_context.begin_dialog("container")
child_dc = dialog_context.child
self.assertIsNotNone(child_dc, "No child DC")
foo_cls = namedtuple("TestObject", "foo")
scope.set_memory(child_dc, foo_cls("bar"))
memory = scope.get_memory(child_dc)
self.assertIsNotNone(memory, "state not returned")
self.assertEqual(memory.foo, "bar")
async def test_dialog_memory_scope_should_overwrite_active_dialogs_memory(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container")
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = DialogMemoryScope()
await dialog_context.begin_dialog("container")
foo_cls = namedtuple("TestObject", "foo")
scope.set_memory(dialog_context, foo_cls("bar"))
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
self.assertEqual(memory.foo, "bar")
async def test_dialog_memory_scope_should_raise_error_if_set_memory_called_without_memory(
self,
):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container")
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
with self.assertRaises(Exception):
scope = DialogMemoryScope()
await dialog_context.begin_dialog("container")
scope.set_memory(dialog_context, None)
async def test_settings_memory_scope_should_return_content_of_settings(self):
# pylint: disable=import-outside-toplevel
from test_settings import DefaultConfig
# Create a DialogState property, DialogSet and register the dialogs.
conversation_state = ConversationState(MemoryStorage())
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state).add(TestDialog("test", "test message"))
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
settings = DefaultConfig()
dialog_context.context.turn_state["settings"] = settings
# Run test
scope = SettingsMemoryScope()
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory)
self.assertEqual(memory.STRING, "test")
self.assertEqual(memory.INT, 3)
self.assertEqual(memory.LIST[0], "zero")
self.assertEqual(memory.LIST[1], "one")
self.assertEqual(memory.LIST[2], "two")
self.assertEqual(memory.LIST[3], "three")
async def test_this_memory_scope_should_return_active_dialogs_state(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = ThisMemoryScope()
await dialog_context.begin_dialog("test")
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
self.assertTrue(memory["is_dialog"])
async def test_this_memory_scope_should_overwrite_active_dialogs_memory(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container")
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = ThisMemoryScope()
await dialog_context.begin_dialog("container")
foo_cls = namedtuple("TestObject", "foo")
scope.set_memory(dialog_context, foo_cls("bar"))
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
self.assertEqual(memory.foo, "bar")
async def test_this_memory_scope_should_raise_error_if_set_memory_called_without_memory(
self,
):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container")
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
with self.assertRaises(Exception):
scope = ThisMemoryScope()
await dialog_context.begin_dialog("container")
scope.set_memory(dialog_context, None)
async def test_this_memory_scope_should_raise_error_if_set_memory_called_without_active_dialog(
self,
):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
container = TestContainer("container")
dialogs.add(container)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
with self.assertRaises(Exception):
scope = ThisMemoryScope()
foo_cls = namedtuple("TestObject", "foo")
scope.set_memory(dialog_context, foo_cls("bar"))
async def test_turn_memory_scope_should_persist_changes_to_turn_state(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = TurnMemoryScope()
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
memory["foo"] = "bar"
memory = scope.get_memory(dialog_context)
self.assertEqual(memory["foo"], "bar")
async def test_turn_memory_scope_should_overwrite_values_in_turn_state(self):
# Create a DialogState property, DialogSet and register the dialogs.
storage = MemoryStorage()
conversation_state = ConversationState(storage)
dialog_state = conversation_state.create_property("dialogs")
dialogs = DialogSet(dialog_state)
dialog = TestDialog("test", "test message")
dialogs.add(dialog)
# Create test context
context = TurnContext(TestAdapter(), MemoryScopesTests.begin_message)
dialog_context = await dialogs.create_context(context)
# Run test
scope = TurnMemoryScope()
foo_cls = namedtuple("TestObject", "foo")
scope.set_memory(dialog_context, foo_cls("bar"))
memory = scope.get_memory(dialog_context)
self.assertIsNotNone(memory, "state not returned")
self.assertEqual(memory.foo, "bar")
|
botbuilder-python/libraries/botbuilder-dialogs/tests/memory/scopes/test_memory_scopes.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/memory/scopes/test_memory_scopes.py",
"repo_id": "botbuilder-python",
"token_count": 8837
}
| 445 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from enum import Enum
class RoleTypes(str, Enum):
user = "user"
bot = "bot"
skill = "skill"
class ActivityTypes(str, Enum):
message = "message"
contact_relation_update = "contactRelationUpdate"
conversation_update = "conversationUpdate"
typing = "typing"
end_of_conversation = "endOfConversation"
event = "event"
invoke = "invoke"
invoke_response = "invokeResponse"
delete_user_data = "deleteUserData"
message_update = "messageUpdate"
message_delete = "messageDelete"
installation_update = "installationUpdate"
message_reaction = "messageReaction"
suggestion = "suggestion"
trace = "trace"
handoff = "handoff"
command = "command"
command_result = "commandResult"
class TextFormatTypes(str, Enum):
markdown = "markdown"
plain = "plain"
xml = "xml"
class AttachmentLayoutTypes(str, Enum):
list = "list"
carousel = "carousel"
class MessageReactionTypes(str, Enum):
like = "like"
plus_one = "plusOne"
class InputHints(str, Enum):
accepting_input = "acceptingInput"
ignoring_input = "ignoringInput"
expecting_input = "expectingInput"
class ActionTypes(str, Enum):
open_url = "openUrl"
im_back = "imBack"
post_back = "postBack"
play_audio = "playAudio"
play_video = "playVideo"
show_image = "showImage"
download_file = "downloadFile"
signin = "signin"
call = "call"
message_back = "messageBack"
class EndOfConversationCodes(str, Enum):
unknown = "unknown"
completed_successfully = "completedSuccessfully"
user_cancelled = "userCancelled"
bot_timed_out = "botTimedOut"
bot_issued_invalid_message = "botIssuedInvalidMessage"
channel_failed = "channelFailed"
class ActivityImportance(str, Enum):
low = "low"
normal = "normal"
high = "high"
class DeliveryModes(str, Enum):
normal = "normal"
notification = "notification"
expect_replies = "expectReplies"
ephemeral = "ephemeral"
class ContactRelationUpdateActionTypes(str, Enum):
add = "add"
remove = "remove"
class InstallationUpdateActionTypes(str, Enum):
add = "add"
remove = "remove"
class SemanticActionStates(str, Enum):
start_action = "start"
continue_action = "continue"
done_action = "done"
|
botbuilder-python/libraries/botbuilder-schema/botbuilder/schema/_connector_client_enums.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-schema/botbuilder/schema/_connector_client_enums.py",
"repo_id": "botbuilder-python",
"token_count": 891
}
| 446 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Union
from botbuilder.core import (
AutoSaveStateMiddleware,
ConversationState,
MemoryStorage,
Middleware,
StatePropertyAccessor,
TurnContext,
)
from botbuilder.core.adapters import TestAdapter
from botbuilder.dialogs import Dialog, DialogSet, DialogTurnResult, DialogTurnStatus
from botbuilder.schema import Activity, ConversationReference
class DialogTestClient:
"""A client for testing dialogs in isolation."""
def __init__(
self,
channel_or_adapter: Union[str, TestAdapter],
target_dialog: Dialog,
initial_dialog_options: object = None,
middlewares: List[Middleware] = None,
conversation_state: ConversationState = None,
):
"""
Create a DialogTestClient to test a dialog without having to create a full-fledged adapter.
```python
client = DialogTestClient("test", MY_DIALOG, MY_OPTIONS)
reply = await client.send_activity("first message")
self.assertEqual(reply.text, "first reply", "reply failed")
```
:param channel_or_adapter: The channel Id or test adapter to be used for the test.
For channel Id, use 'emulator' or 'test' if you are uncertain of the channel you are targeting.
Otherwise, it is recommended that you use the id for the channel(s) your bot will be using and
write a test case for each channel.
Or, a test adapter instance can be used.
:type channel_or_adapter: Union[str, TestAdapter]
:param target_dialog: The dialog to be tested. This will be the root dialog for the test client.
:type target_dialog: Dialog
:param initial_dialog_options: (Optional) additional argument(s) to pass to the dialog being started.
:type initial_dialog_options: object
:param middlewares: (Optional) The test adapter to use. If this parameter is not provided, the test client will
use a default TestAdapter.
:type middlewares: List[Middleware]
:param conversation_state: (Optional) A ConversationState instance to use in the test client.
:type conversation_state: ConversationState
"""
self.dialog_turn_result: DialogTurnResult = None
self.dialog_context = None
self.conversation_state: ConversationState = (
ConversationState(MemoryStorage())
if conversation_state is None
else conversation_state
)
dialog_state = self.conversation_state.create_property("DialogState")
self._callback = self._get_default_callback(
target_dialog, initial_dialog_options, dialog_state
)
if isinstance(channel_or_adapter, str):
conversation_reference = ConversationReference(
channel_id=channel_or_adapter
)
self.test_adapter = TestAdapter(self._callback, conversation_reference)
self.test_adapter.use(
AutoSaveStateMiddleware().add(self.conversation_state)
)
else:
self.test_adapter = channel_or_adapter
self._add_user_middlewares(middlewares)
async def send_activity(self, activity) -> Activity:
"""
Send an activity into the dialog.
:param activity: an activity potentially with text.
:type activity:
:return: a TestFlow that can be used to assert replies etc.
:rtype: Activity
"""
await self.test_adapter.receive_activity(activity)
return self.test_adapter.get_next_activity()
def get_next_reply(self) -> Activity:
"""
Get the next reply waiting to be delivered (if one exists)
:return: a TestFlow that can be used to assert replies etc.
:rtype: Activity
"""
return self.test_adapter.get_next_activity()
def _get_default_callback(
self,
target_dialog: Dialog,
initial_dialog_options: object,
dialog_state: StatePropertyAccessor,
):
async def default_callback(turn_context: TurnContext) -> None:
dialog_set = DialogSet(dialog_state)
dialog_set.add(target_dialog)
self.dialog_context = await dialog_set.create_context(turn_context)
self.dialog_turn_result = await self.dialog_context.continue_dialog()
if self.dialog_turn_result.status == DialogTurnStatus.Empty:
self.dialog_turn_result = await self.dialog_context.begin_dialog(
target_dialog.id, initial_dialog_options
)
return default_callback
def _add_user_middlewares(self, middlewares: List[Middleware]) -> None:
if middlewares is not None:
for middleware in middlewares:
self.test_adapter.use(middleware)
|
botbuilder-python/libraries/botbuilder-testing/botbuilder/testing/dialog_test_client.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-testing/botbuilder/testing/dialog_test_client.py",
"repo_id": "botbuilder-python",
"token_count": 1926
}
| 447 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from msrest.pipeline import ClientRawResponse
from ... import models
class AttachmentsOperations:
"""AttachmentsOperations async operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach
it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: The API version to use for the request. Constant value: "v3".
"""
models = models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = config
self.api_version = "v3"
async def get_attachment_info(
self, attachment_id, *, custom_headers=None, raw=False, **operation_config
):
"""GetAttachmentInfo.
Get AttachmentInfo structure describing the attachment views.
:param attachment_id: attachment id
:type attachment_id: 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: AttachmentInfo or ClientRawResponse if raw=true
:rtype: ~botframework.connector.models.AttachmentInfo or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
"""
# Construct URL
url = self.get_attachment_info.metadata["url"]
path_format_arguments = {
"attachmentId": self._serialize.url("attachment_id", attachment_id, "str")
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# 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 = await self._client.async_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("AttachmentInfo", response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_attachment_info.metadata = {"url": "/v3/attachments/{attachmentId}"}
async def get_attachment(
self,
attachment_id,
view_id,
*,
custom_headers=None,
raw=False,
callback=None,
**operation_config
):
"""GetAttachment.
Get the named view as binary content.
:param attachment_id: attachment id
:type attachment_id: str
:param view_id: View id from attachmentInfo
:type view_id: 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 callback: When specified, will be called with each chunk of
data that is streamed. The callback should take two arguments, the
bytes of the current chunk of data and the response object. If the
data is uploading, response will be None.
:type callback: Callable[Bytes, response=None]
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: object or ClientRawResponse if raw=true
:rtype: Generator or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<botframework.connector.models.ErrorResponseException>`
"""
# Construct URL
url = self.get_attachment.metadata["url"]
path_format_arguments = {
"attachmentId": self._serialize.url("attachment_id", attachment_id, "str"),
"viewId": self._serialize.url("view_id", view_id, "str"),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# 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 = await self._client.async_send(
request, stream=True, **operation_config
)
if response.status_code not in [200, 301, 302]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = self._client.stream_download_async(response, callback)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get_attachment.metadata = {"url": "/v3/attachments/{attachmentId}/views/{viewId}"}
|
botbuilder-python/libraries/botframework-connector/botframework/connector/aio/operations_async/_attachments_operations_async.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/aio/operations_async/_attachments_operations_async.py",
"repo_id": "botbuilder-python",
"token_count": 2208
}
| 448 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
class AuthenticationConstants(ABC):
# TO CHANNEL FROM BOT: Login URL
#
# DEPRECATED: DO NOT USE
TO_CHANNEL_FROM_BOT_LOGIN_URL = (
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token"
)
# TO CHANNEL FROM BOT: Login URL prefix
TO_CHANNEL_FROM_BOT_LOGIN_URL_PREFIX = "https://login.microsoftonline.com/"
# TO CHANNEL FROM BOT: Login URL token endpoint path
TO_CHANNEL_FROM_BOT_TOKEN_ENDPOINT_PATH = "/oauth2/v2.0/token"
# TO CHANNEL FROM BOT: Default tenant from which to obtain a token for bot to channel communication
DEFAULT_CHANNEL_AUTH_TENANT = "botframework.com"
# TO CHANNEL FROM BOT: OAuth scope to request
TO_CHANNEL_FROM_BOT_OAUTH_SCOPE = "https://api.botframework.com"
# TO BOT FROM CHANNEL: Token issuer
TO_BOT_FROM_CHANNEL_TOKEN_ISSUER = "https://api.botframework.com"
"""
OAuth Url used to get a token from OAuthApiClient.
"""
OAUTH_URL = "https://api.botframework.com"
# Application Setting Key for the OpenIdMetadataUrl value.
BOT_OPEN_ID_METADATA_KEY = "BotOpenIdMetadata"
# Application Setting Key for the ChannelService value.
CHANNEL_SERVICE = "ChannelService"
# Application Setting Key for the OAuthUrl value.
OAUTH_URL_KEY = "OAuthApiEndpoint"
# Application Settings Key for whether to emulate OAuthCards when using the emulator.
EMULATE_OAUTH_CARDS_KEY = "EmulateOAuthCards"
# TO BOT FROM CHANNEL: OpenID metadata document for tokens coming from MSA
TO_BOT_FROM_CHANNEL_OPENID_METADATA_URL = (
"https://login.botframework.com/v1/.well-known/openidconfiguration"
)
# TO BOT FROM ENTERPRISE CHANNEL: OpenID metadata document for tokens coming from MSA
TO_BOT_FROM_ENTERPRISE_CHANNEL_OPEN_ID_METADATA_URL_FORMAT = (
"https://{channelService}.enterprisechannel.botframework.com"
"/v1/.well-known/openidconfiguration"
)
# TO BOT FROM EMULATOR: OpenID metadata document for tokens coming from MSA
TO_BOT_FROM_EMULATOR_OPENID_METADATA_URL = (
"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"
)
# The V1 Azure AD token issuer URL template that will contain the tenant id where
# the token was issued from.
VALID_TOKEN_ISSUER_URL_TEMPLATE_V1 = "https://sts.windows.net/{0}/"
# The V2 Azure AD token issuer URL template that will contain the tenant id where
# the token was issued from.
VALID_TOKEN_ISSUER_URL_TEMPLATE_V2 = "https://login.microsoftonline.com/{0}/v2.0"
# The Government V1 Azure AD token issuer URL template that will contain the tenant id
# where the token was issued from.
VALID_GOVERNMENT_TOKEN_ISSUER_URL_TEMPLATE_V1 = (
"https://login.microsoftonline.us/{0}/"
)
# The Government V2 Azure AD token issuer URL template that will contain the tenant id
# where the token was issued from.
VALID_GOVERNMENT_TOKEN_ISSUER_URL_TEMPLATE_V2 = (
"https://login.microsoftonline.us/{0}/v2.0"
)
# Allowed token signing algorithms. Tokens come from channels to the bot. The code
# that uses this also supports tokens coming from the emulator.
ALLOWED_SIGNING_ALGORITHMS = ["RS256", "RS384", "RS512"]
# "azp" Claim.
# Authorized party - the party to which the ID Token was issued.
# This claim follows the general format set forth in the OpenID Spec.
# http://openid.net/specs/openid-connect-core-1_0.html#IDToken
AUTHORIZED_PARTY = "azp"
"""
Audience Claim. From RFC 7519.
https://tools.ietf.org/html/rfc7519#section-4.1.3
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim.If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected.In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value.In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value.The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
"""
AUDIENCE_CLAIM = "aud"
"""
Issuer Claim. From RFC 7519.
https://tools.ietf.org/html/rfc7519#section-4.1.1
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
"""
ISSUER_CLAIM = "iss"
"""
From RFC 7515
https://tools.ietf.org/html/rfc7515#section-4.1.4
The "kid" (key ID) Header Parameter is a hint indicating which key
was used to secure the JWS. This parameter allows originators to
explicitly signal a change of key to recipients. The structure of
the "kid" value is unspecified. Its value MUST be a case-sensitive
string. Use of this Header Parameter is OPTIONAL.
When used with a JWK, the "kid" value is used to match a JWK "kid"
parameter value.
"""
KEY_ID_HEADER = "kid"
# Token version claim name. As used in Microsoft AAD tokens.
VERSION_CLAIM = "ver"
# App ID claim name. As used in Microsoft AAD 1.0 tokens.
APP_ID_CLAIM = "appid"
# Service URL claim name. As used in Microsoft Bot Framework v3.1 auth.
SERVICE_URL_CLAIM = "serviceurl"
# AppId used for creating skill claims when there is no appId and password configured.
ANONYMOUS_SKILL_APP_ID = "AnonymousSkill"
# Indicates that ClaimsIdentity.authentication_type is anonymous (no app Id and password were provided).
ANONYMOUS_AUTH_TYPE = "anonymous"
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/authentication_constants.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/authentication_constants.py",
"repo_id": "botbuilder-python",
"token_count": 2147
}
| 449 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
from msal import ConfidentialClientApplication
from .app_credentials import AppCredentials
class MicrosoftAppCredentials(AppCredentials, ABC):
"""
AppCredentials implementation using application ID and password.
"""
def __init__(
self,
app_id: str,
password: str,
channel_auth_tenant: str = None,
oauth_scope: str = None,
):
# super will set proper scope and endpoint.
super().__init__(
app_id=app_id,
channel_auth_tenant=channel_auth_tenant,
oauth_scope=oauth_scope,
)
self.microsoft_app_password = password
self.app = None
@staticmethod
def empty():
return MicrosoftAppCredentials("", "")
def get_access_token(self, force_refresh: bool = False) -> str:
"""
Implementation of AppCredentials.get_token.
:return: The access token for the given app id and password.
"""
scope = self.oauth_scope
if not scope.endswith("/.default"):
scope += "/.default"
scopes = [scope]
# Firstly, looks up a token from cache
# Since we are looking for token for the current app, NOT for an end user,
# notice we give account parameter as None.
auth_token = self.__get_msal_app().acquire_token_silent(scopes, account=None)
if not auth_token:
# No suitable token exists in cache. Let's get a new one from AAD.
auth_token = self.__get_msal_app().acquire_token_for_client(scopes=scopes)
return auth_token["access_token"]
def __get_msal_app(self):
if not self.app:
self.app = ConfidentialClientApplication(
client_id=self.microsoft_app_id,
client_credential=self.microsoft_app_password,
authority=self.oauth_endpoint,
)
return self.app
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/microsoft_app_credentials.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/microsoft_app_credentials.py",
"repo_id": "botbuilder-python",
"token_count": 859
}
| 450 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from botbuilder.schema import *
from botbuilder.schema.teams import *
|
botbuilder-python/libraries/botframework-connector/botframework/connector/models/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/models/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 72
}
| 451 |
interactions:
- request:
body: null
headers:
Accept: [application/json]
Accept-Encoding: ['gzip, deflate']
Connection: [keep-alive]
Content-Type: [application/json; charset=utf-8]
User-Agent: [python/3.6.2 (Windows-10-10.0.16299-SP0) requests/2.18.1 msrest/0.4.23
azure-botframework-connector/3.0]
method: GET
uri: https://slack.botframework.com/v3/attachments/bt13796-GJS4yaxDLI/views/original
response:
body: {string: ''}
headers:
cache-control: [no-cache]
content-length: ['0']
date: ['Fri, 29 Dec 2017 18:29:54 GMT']
expires: ['-1']
pragma: [no-cache]
request-context: ['appId=cid-v1:6814484e-c0d5-40ea-9dba-74ff29ca4f62']
server: [Microsoft-IIS/10.0]
strict-transport-security: [max-age=31536000]
x-powered-by: [ASP.NET]
status: {code: 404, message: Not Found}
version: 1
|
botbuilder-python/libraries/botframework-connector/tests/recordings/test_attachments_get_attachment_view_with_invalid_attachment_id_fails.yaml/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/recordings/test_attachments_get_attachment_view_with_invalid_attachment_id_fails.yaml",
"repo_id": "botbuilder-python",
"token_count": 423
}
| 452 |
interactions:
- request:
body: null
headers:
Accept: [application/json]
Accept-Encoding: ['gzip, deflate']
Connection: [keep-alive]
Content-Type: [application/json; charset=utf-8]
User-Agent: [python/3.6.2 (Windows-10-10.0.16299-SP0) requests/2.18.1 msrest/0.4.23
azure-botframework-connector/3.0]
method: GET
uri: https://slack.botframework.com/v3/conversations/INVALID_ID/members
response:
body: {string: "{\r\n \"error\": {\r\n \"code\": \"ServiceError\",\r\n \
\ \"message\": \"Invalid ConversationId: INVALID_ID\"\r\n }\r\n}"}
headers:
cache-control: [no-cache]
content-length: ['105']
content-type: [application/json; charset=utf-8]
date: ['Fri, 29 Dec 2017 15:38:35 GMT']
expires: ['-1']
pragma: [no-cache]
request-context: ['appId=cid-v1:6814484e-c0d5-40ea-9dba-74ff29ca4f62']
server: [Microsoft-IIS/10.0]
strict-transport-security: [max-age=31536000]
x-powered-by: [ASP.NET]
status: {code: 400, message: Bad Request}
version: 1
|
botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_get_conversation_members_invalid_id_fails.yaml/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_get_conversation_members_invalid_id_fails.yaml",
"repo_id": "botbuilder-python",
"token_count": 501
}
| 453 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import asyncio
import pytest
from botbuilder.schema import (
Activity,
ActivityTypes,
Attachment,
AttachmentLayoutTypes,
CardImage,
ChannelAccount,
ConversationParameters,
ErrorResponseException,
HeroCard,
)
from botframework.connector import ConnectorClient
from botframework.connector.auth import MicrosoftAppCredentials
from authentication_stub import MicrosoftTokenAuthenticationStub
SERVICE_URL = "https://slack.botframework.com"
CHANNEL_ID = "slack"
BOT_NAME = "botbuilder-pc-bot"
BOT_ID = "B21UTEF8S:T03CWQ0QB"
RECIPIENT_ID = "U19KH8EHJ:T03CWQ0QB"
CONVERSATION_ID = "B21UTEF8S:T03CWQ0QB:D2369CT7C"
async def get_auth_token():
try:
# pylint: disable=import-outside-toplevel
from .app_creds_real import MICROSOFT_APP_ID, MICROSOFT_APP_PASSWORD
# Define a "app_creds_real.py" file with your bot credentials as follows:
# MICROSOFT_APP_ID = '...'
# MICROSOFT_APP_PASSWORD = '...'
return await MicrosoftAppCredentials(
MICROSOFT_APP_ID, MICROSOFT_APP_PASSWORD
).get_access_token()
except ImportError:
return "STUB_ACCESS_TOKEN"
LOOP = asyncio.get_event_loop()
AUTH_TOKEN = LOOP.run_until_complete(get_auth_token())
class ConversationTest:
def __init__(self): # pylint: disable=useless-super-delegation
super(ConversationTest, self).__init__()
@property
def credentials(self):
return MicrosoftTokenAuthenticationStub(AUTH_TOKEN)
def test_conversations_create_conversation(self):
test_object = ChannelAccount(id=RECIPIENT_ID)
create_conversation = ConversationParameters(
bot=ChannelAccount(id=BOT_ID),
members=[test_object],
activity=Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
from_property=ChannelAccount(id=BOT_ID),
recipient=test_object,
text="Hi there!",
),
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
conversation = connector.conversations.create_conversation(create_conversation)
assert conversation.id is not None
def test_conversations_create_conversation_with_invalid_bot_id_fails(self):
test_object = ChannelAccount(id=RECIPIENT_ID)
create_conversation = ConversationParameters(
bot=ChannelAccount(id="INVALID"),
members=[test_object],
activity=Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
from_property=ChannelAccount(id="INVALID"),
recipient=test_object,
text="Hi there!",
),
)
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
connector.conversations.create_conversation(create_conversation)
assert excinfo.value.error.error.code == "ServiceError"
assert "Invalid userId" in str(excinfo.value.error.error.message)
def test_conversations_create_conversation_without_members_fails(self):
create_conversation = ConversationParameters(
bot=ChannelAccount(id=BOT_ID),
activity=Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
from_property=ChannelAccount(id=BOT_ID),
text="Hi there!",
),
members=[],
)
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
connector.conversations.create_conversation(create_conversation)
assert excinfo.value.error.error.code == "BadArgument"
assert "Conversations" in str(excinfo.value.error.error.message)
def test_conversations_create_conversation_with_bot_as_only_member_fails(self):
test_object = ChannelAccount(id=BOT_ID)
sender = ChannelAccount(id=BOT_ID)
create_conversation = ConversationParameters(
bot=sender,
members=[test_object],
activity=Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
from_property=sender,
recipient=test_object,
text="Hi there!",
),
)
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
connector.conversations.create_conversation(create_conversation)
assert excinfo.value.error.error.code == "BadArgument"
assert "Bots cannot IM other bots" in str(excinfo.value.error.error.message)
def test_conversations_send_to_conversation(self):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Hello again!",
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
assert response is not None
def test_conversations_send_to_conversation_with_attachment(self):
card1 = HeroCard(
title="A static image",
text="JPEG image",
images=[
CardImage(
url="https://docs.com/en-us/bot-framework/media/designing-bots/core/dialogs-screens.png"
)
],
)
card2 = HeroCard(
title="An animation",
subtitle="GIF image",
images=[CardImage(url="http://i.giphy.com/Ki55RUbOV5njy.gif")],
)
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
attachment_layout=AttachmentLayoutTypes.list,
attachments=[
Attachment(content_type="application/vnd.card.hero", content=card1),
Attachment(content_type="application/vnd.card.hero", content=card2),
],
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
assert response is not None
def test_conversations_send_to_conversation_with_invalid_conversation_id_fails(
self,
):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Error!",
)
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
connector.conversations.send_to_conversation("123", activity)
assert excinfo.value.error.error.code == "ServiceError"
assert "cannot send messages to this id" in str(
excinfo.value.error.error.message
) or "Invalid ConversationId" in str(excinfo.value.error.error.message)
def test_conversations_get_conversation_members(self):
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
members = connector.conversations.get_conversation_members(CONVERSATION_ID)
assert len(members) == 2
assert members[0].name == BOT_NAME
assert members[0].id == BOT_ID
def test_conversations_get_conversation_members_invalid_id_fails(self):
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
connector.conversations.get_conversation_members("INVALID_ID")
assert excinfo.value.error.error.code == "ServiceError"
assert "cannot send messages to this id" in str(
excinfo.value.error.error.message
) or "Invalid ConversationId" in str(excinfo.value.error.error.message)
def test_conversations_update_activity(self):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Updating activity...",
)
activity_update = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Activity updated.",
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
activity_id = response.id
response = connector.conversations.update_activity(
CONVERSATION_ID, activity_id, activity_update
)
assert response is not None
assert response.id == activity_id
def test_conversations_update_activity_invalid_conversation_id_fails(self):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Updating activity...",
)
activity_update = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Activity updated.",
)
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
activity_id = response.id
connector.conversations.update_activity(
"INVALID_ID", activity_id, activity_update
)
assert excinfo.value.error.error.code == "ServiceError"
assert "Invalid ConversationId" in str(excinfo.value.error.error.message)
def test_conversations_reply_to_activity(self):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Thread activity",
)
child_activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Child activity.",
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
activity_id = response.id
response = connector.conversations.reply_to_activity(
CONVERSATION_ID, activity_id, child_activity
)
assert response is not None
assert response.id != activity_id
def test_conversations_reply_to_activity_with_invalid_conversation_id_fails(self):
child_activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Child activity.",
)
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
connector.conversations.reply_to_activity(
"INVALID_ID", "INVALID_ID", child_activity
)
assert excinfo.value.error.error.code == "ServiceError"
assert "Invalid ConversationId" in str(excinfo.value.error.error.message)
def test_conversations_delete_activity(self):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Activity to be deleted..",
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
activity_id = response.id
response = connector.conversations.delete_activity(CONVERSATION_ID, activity_id)
assert response is None
def test_conversations_delete_activity_with_invalid_conversation_id_fails(self):
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
connector.conversations.delete_activity("INVALID_ID", "INVALID_ID")
assert excinfo.value.error.error.code == "ServiceError"
assert "Invalid ConversationId" in str(excinfo.value.error.error.message)
def test_conversations_get_activity_members(self):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Test Activity",
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
members = connector.conversations.get_activity_members(
CONVERSATION_ID, response.id
)
assert len(members) == 2
assert members[0].name == BOT_NAME
assert members[0].id == BOT_ID
def test_conversations_get_activity_members_invalid_conversation_id_fails(self):
activity = Activity(
type=ActivityTypes.message,
channel_id=CHANNEL_ID,
recipient=ChannelAccount(id=RECIPIENT_ID),
from_property=ChannelAccount(id=BOT_ID),
text="Test Activity",
)
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = connector.conversations.send_to_conversation(
CONVERSATION_ID, activity
)
connector.conversations.get_activity_members("INVALID_ID", response.id)
assert excinfo.value.error.error.code == "ServiceError"
assert "Invalid ConversationId" in str(excinfo.value.error.error.message)
|
botbuilder-python/libraries/botframework-connector/tests/test_conversations.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/test_conversations.py",
"repo_id": "botbuilder-python",
"token_count": 6719
}
| 454 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
from uuid import UUID
from typing import List
from botframework.streaming.payloads.models import Header
class Assembler(ABC):
def __init__(self, end: bool, identifier: UUID):
self.end = end
self.identifier = identifier
def close(self):
raise NotImplementedError()
def create_stream_from_payload(self) -> List[int]:
raise NotImplementedError()
def get_payload_as_stream(self) -> List[int]:
raise NotImplementedError()
def on_receive(
self, header: Header, stream: List[int], content_length: int
) -> List[int]:
raise NotImplementedError()
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/assemblers/assembler.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/assemblers/assembler.py",
"repo_id": "botbuilder-python",
"token_count": 268
}
| 455 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
from typing import List
from .serializable import Serializable
from .stream_description import StreamDescription
class ResponsePayload(Serializable):
def __init__(
self, *, status_code: int = None, streams: List[StreamDescription] = None
):
self.status_code = status_code
self.streams = streams
def to_json(self) -> str:
obj = {"statusCode": self.status_code}
if self.streams:
obj["streams"] = [stream.to_dict() for stream in self.streams]
return json.dumps(obj)
def from_json(self, json_str: str) -> "ResponsePayload":
obj = json.loads(json_str)
self.status_code = obj.get("statusCode")
stream_list = obj.get("streams")
if stream_list:
self.streams = [
StreamDescription().from_dict(stream_dict)
for stream_dict in stream_list
]
return self
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/models/response_payload.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/models/response_payload.py",
"repo_id": "botbuilder-python",
"token_count": 415
}
| 456 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
class StreamingTransportService(ABC):
async def start(self):
raise NotImplementedError()
async def send(self, request):
raise NotImplementedError()
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/streaming_transport_service.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/streaming_transport_service.py",
"repo_id": "botbuilder-python",
"token_count": 90
}
| 457 |
from unittest import TestCase
from uuid import UUID, uuid4
from botframework.streaming.payloads import StreamManager
from botframework.streaming.payloads.assemblers import PayloadStreamAssembler
from botframework.streaming.payloads.models import Header
class TestPayloadAssembler(TestCase):
def test_ctor_id(self):
identifier: UUID = uuid4()
stream_manager = StreamManager()
assembler = PayloadStreamAssembler(stream_manager, identifier)
self.assertEqual(identifier, assembler.identifier)
def test_ctor_end_false(self):
identifier: UUID = uuid4()
stream_manager = StreamManager()
assembler = PayloadStreamAssembler(stream_manager, identifier)
self.assertFalse(assembler.end)
def test_get_stream(self):
identifier: UUID = uuid4()
stream_manager = StreamManager()
assembler = PayloadStreamAssembler(stream_manager, identifier)
stream = assembler.get_payload_as_stream()
self.assertIsNotNone(stream)
def test_get_stream_does_not_make_new_each_time(self):
identifier: UUID = uuid4()
stream_manager = StreamManager()
assembler = PayloadStreamAssembler(stream_manager, identifier)
stream1 = assembler.get_payload_as_stream()
stream2 = assembler.get_payload_as_stream()
self.assertEqual(stream1, stream2)
def test_on_receive_sets_end(self):
identifier: UUID = uuid4()
stream_manager = StreamManager()
assembler = PayloadStreamAssembler(stream_manager, identifier)
header = Header()
header.end = True
assembler.get_payload_as_stream()
assembler.on_receive(header, [], 100)
self.assertTrue(assembler.end)
def test_close_does_not_set_end(self):
identifier: UUID = uuid4()
stream_manager = StreamManager()
assembler = PayloadStreamAssembler(stream_manager, identifier)
assembler.close()
self.assertFalse(assembler.end)
|
botbuilder-python/libraries/botframework-streaming/tests/test_payload_assembler.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/tests/test_payload_assembler.py",
"repo_id": "botbuilder-python",
"token_count": 781
}
| 458 |
# BotFramework Connector
> see https://aka.ms/autorest
Configuration for generating BotFramework Connector SDK.
``` yaml
add-credentials: true
openapi-type: data-plane
```
The current release for the BotFramework Connector is v3.0.
# Releases
## Connector API 3.0
``` yaml
input-file: ConnectorAPI.json
```
### Connector API 3.0 - Python Settings
These settings apply only when `--python` is specified on the command line.
DO NOT use `--basic-setup-py` as this will overwrite the existing setup.py files.
If you upgrade autorest from npm you may need to run `autorest ---reset` before continuing.
``` yaml $(python)
python:
license-header: MICROSOFT_MIT_NO_VERSION
add-credentials: true
payload-flattening-threshold: 2
namespace: botframework.connector
package-name: botframework-connector
override-client-name: ConnectorClient
clear-output-folder: true
output-folder: ./generated
```
|
botbuilder-python/swagger/README.md/0
|
{
"file_path": "botbuilder-python/swagger/README.md",
"repo_id": "botbuilder-python",
"token_count": 284
}
| 459 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import logging
import sys
import traceback
from datetime import datetime
from aiohttp import web
from aiohttp.web import Request, Response
from botbuilder.core import (
BotFrameworkAdapterSettings,
BotFrameworkHttpClient,
ConversationState,
MemoryStorage,
TurnContext,
UserState,
BotFrameworkAdapter,
)
from botbuilder.core.integration import (
aiohttp_error_middleware,
)
from botbuilder.schema import Activity, ActivityTypes
from botframework.connector.auth import (
SimpleCredentialProvider,
)
from bots import ParentBot
from config import DefaultConfig
from dialogs import MainDialog
CONFIG = DefaultConfig()
STORAGE = MemoryStorage()
CONVERSATION_STATE = ConversationState(STORAGE)
USER_STATE = UserState(STORAGE)
CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
CLIENT = BotFrameworkHttpClient(CREDENTIAL_PROVIDER)
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
ADAPTER = BotFrameworkAdapter(SETTINGS)
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
traceback.print_exc()
# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
ADAPTER.on_turn_error = on_error
DIALOG = MainDialog(CONFIG)
# Create the Bot
BOT = ParentBot(CLIENT, CONFIG, DIALOG, CONVERSATION_STATE, USER_STATE)
# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
# Main bot message handler.
if "application/json" in req.headers["Content-Type"]:
body = await req.json()
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
try:
await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
return Response(status=201)
except Exception as exception:
raise exception
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
if __name__ == "__main__":
try:
logging.basicConfig(level=logging.DEBUG)
web.run_app(APP, host="localhost", port=CONFIG.PORT)
except Exception as error:
raise error
|
botbuilder-python/tests/experimental/sso/parent/app.py/0
|
{
"file_path": "botbuilder-python/tests/experimental/sso/parent/app.py",
"repo_id": "botbuilder-python",
"token_count": 1186
}
| 460 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .app import APP
__all__ = ["APP"]
|
botbuilder-python/tests/functional-tests/functionaltestbot/flask_bot_app/__init__.py/0
|
{
"file_path": "botbuilder-python/tests/functional-tests/functionaltestbot/flask_bot_app/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 37
}
| 461 |
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"botName": {
"defaultValue": "nightly-build-python-linux",
"type": "string",
"minLength": 2
},
"sku": {
"defaultValue": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
},
"type": "object"
},
"linuxFxVersion": {
"type": "string",
"defaultValue": "PYTHON|3.6"
},
"location": {
"type": "string",
"defaultValue": "West US",
"metadata": {
"description": "Location for all resources."
}
},
"appId": {
"defaultValue": "1234",
"type": "string"
},
"appSecret": {
"defaultValue": "blank",
"type": "string"
}
},
"variables": {
"siteHost": "[concat(parameters('botName'), '.azurewebsites.net')]",
"botEndpoint": "[concat('https://', variables('siteHost'), '/api/mybot')]"
},
"resources": [
{
"type": "Microsoft.Web/serverfarms",
"apiVersion": "2017-08-01",
"name": "[parameters('botName')]",
"kind": "linux",
"location": "[parameters('location')]",
"sku": "[parameters('sku')]",
"properties": {
"name": "[parameters('botName')]",
"reserved": true,
"perSiteScaling": false,
"targetWorkerCount": 0,
"targetWorkerSizeId": 0
}
},
{
"type": "Microsoft.Web/sites",
"apiVersion": "2016-08-01",
"name": "[parameters('botName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms', parameters('botName'))]"
],
"kind": "app,linux",
"properties": {
"enabled": true,
"hostNameSslStates": [
{
"name": "[concat(parameters('botName'), '.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Standard"
},
{
"name": "[concat(parameters('botName'), '.scm.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Repository"
}
],
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', parameters('botName'))]",
"siteConfig": {
"linuxFxVersion": "[parameters('linuxFxVersion')]",
"appSettings": [
{
"name": "WEBSITE_NODE_DEFAULT_VERSION",
"value": "10.14.1"
},
{
"name": "MicrosoftAppId",
"value": "[parameters('appId')]"
},
{
"name": "MicrosoftAppPassword",
"value": "[parameters('appSecret')]"
}
]
},
"reserved": true,
"scmSiteAlsoStopped": false,
"clientAffinityEnabled": true,
"clientCertEnabled": false,
"hostNamesDisabled": false,
"containerSize": 0,
"dailyMemoryTimeQuota": 0,
"httpsOnly": false
}
},
{
"type": "Microsoft.Web/sites/config",
"apiVersion": "2016-08-01",
"name": "[concat(parameters('botName'), '/web')]",
"location": "West US",
"dependsOn": [
"[resourceId('Microsoft.Web/sites', parameters('botName'))]"
],
"properties": {
"numberOfWorkers": 1,
"defaultDocuments": [
"Default.htm",
"Default.html",
"Default.asp",
"index.htm",
"index.html",
"iisstart.htm",
"default.aspx",
"index.php",
"hostingstart.html"
],
"netFrameworkVersion": "v4.0",
"phpVersion": "",
"pythonVersion": "",
"nodeVersion": "",
"linuxFxVersion": "[parameters('linuxFxVersion')]",
"requestTracingEnabled": false,
"remoteDebuggingEnabled": false,
"httpLoggingEnabled": false,
"logsDirectorySizeLimit": 35,
"detailedErrorLoggingEnabled": false,
"publishingUsername": "parameters('botName')",
"scmType": "LocalGit",
"use32BitWorkerProcess": true,
"webSocketsEnabled": false,
"alwaysOn": true,
"appCommandLine": "",
"managedPipelineMode": "Integrated",
"virtualApplications": [
{
"virtualPath": "/",
"physicalPath": "site\\wwwroot",
"preloadEnabled": true,
"virtualDirectories": null
}
],
"winAuthAdminState": 0,
"winAuthTenantState": 0,
"customAppPoolIdentityAdminState": false,
"customAppPoolIdentityTenantState": false,
"loadBalancing": "LeastRequests",
"routingRules": [],
"experiments": {
"rampUpRules": []
},
"autoHealEnabled": false,
"vnetName": "",
"siteAuthEnabled": false,
"siteAuthSettings": {
"enabled": null,
"unauthenticatedClientAction": null,
"tokenStoreEnabled": null,
"allowedExternalRedirectUrls": null,
"defaultProvider": null,
"clientId": null,
"clientSecret": null,
"clientSecretCertificateThumbprint": null,
"issuer": null,
"allowedAudiences": null,
"additionalLoginParams": null,
"isAadAutoProvisioned": false,
"googleClientId": null,
"googleClientSecret": null,
"googleOAuthScopes": null,
"facebookAppId": null,
"facebookAppSecret": null,
"facebookOAuthScopes": null,
"twitterConsumerKey": null,
"twitterConsumerSecret": null,
"microsoftAccountClientId": null,
"microsoftAccountClientSecret": null,
"microsoftAccountOAuthScopes": null
},
"localMySqlEnabled": false,
"http20Enabled": true,
"minTlsVersion": "1.2",
"ftpsState": "AllAllowed",
"reservedInstanceCount": 0
}
},
{
"apiVersion": "2017-12-01",
"type": "Microsoft.BotService/botServices",
"name": "[parameters('botName')]",
"location": "global",
"kind": "bot",
"sku": {
"name": "[parameters('botName')]"
},
"properties": {
"name": "[parameters('botName')]",
"displayName": "[parameters('botName')]",
"endpoint": "[variables('botEndpoint')]",
"msaAppId": "[parameters('appId')]",
"developerAppInsightsApplicationId": null,
"developerAppInsightKey": null,
"publishingCredentials": null,
"storageResourceId": null
},
"dependsOn": [
"[resourceId('Microsoft.Web/sites/', parameters('botName'))]"
]
},
{
"type": "Microsoft.Web/sites/hostNameBindings",
"apiVersion": "2016-08-01",
"name": "[concat(parameters('botName'), '/', parameters('botName'), '.azurewebsites.net')]",
"location": "West US",
"dependsOn": [
"[resourceId('Microsoft.Web/sites', parameters('botName'))]"
],
"properties": {
"siteName": "parameters('botName')",
"hostNameType": "Verified"
}
}
]
}
|
botbuilder-python/tests/functional-tests/functionaltestbot/template/linux/template.json/0
|
{
"file_path": "botbuilder-python/tests/functional-tests/functionaltestbot/template/linux/template.json",
"repo_id": "botbuilder-python",
"token_count": 5164
}
| 462 |
# EchoBot
Bot Framework v4 echo bot sample.
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
## Running the sample
- Clone the repository
```bash
git clone https://github.com/Microsoft/botbuilder-python.git
```
- Activate your desired virtual environment
- Bring up a terminal, navigate to `botbuilder-python\samples\02.echo-bot` folder
- In the terminal, type `pip install -r requirements.txt`
- In the terminal, type `python app.py`
## Testing the bot using Bot Framework Emulator
[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
### Connect to bot using Bot Framework Emulator
- Launch Bot Framework Emulator
- Paste this URL in the emulator window - http://localhost:3978/api/messages
## Further reading
- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
|
botbuilder-python/tests/skills/skills-prototypes/dialog-to-dialog/authentication-bot/README.md/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-prototypes/dialog-to-dialog/authentication-bot/README.md",
"repo_id": "botbuilder-python",
"token_count": 388
}
| 463 |
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
""" Bot Configuration """
class DefaultConfig:
""" Bot Configuration """
PORT = 3978
APP_ID = os.environ.get("MicrosoftAppId", "")
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
|
botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-child-bot/config.py/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-child-bot/config.py",
"repo_id": "botbuilder-python",
"token_count": 108
}
| 464 |

# About Cascadia Code
Cascadia is a fun new coding font that comes bundled with [Windows Terminal](https://github.com/microsoft/terminal), and is now the default font in Visual Studio as well.
# Font Variants
- `Cascadia Code`: standard version of Cascadia
- `Cascadia Mono`: a version of Cascadia that doesn't have ligatures
- `Cascadia (Code|Mono) PL`: a version of Cascadia that has embedded Powerline symbols
- `Cascadia (Code|Mono) NF`: a version of Cascadia that has Nerd Font symbols
For the italic, there is a standard `italic` and a `cursive` variant accessible via `ss01` (see [below](https://github.com/microsoft/cascadia-code/blob/main/README.md#to-enable-the-cursive-form-of-the-italic-heres-the-code-you-should-use)).
# Font features



Enabling stylistic sets will [vary between applications](https://github.com/tonsky/FiraCode/wiki/How-to-enable-stylistic-sets). For example, in VS Code, you can enable stylistic sets (and other OpenType features) via `settings.json`:
```
"editor.fontLigatures": "'ss01', 'ss02', 'ss03', 'ss19', 'ss20'"
```
#### To enable the Cursive form of the italic, here's the code you should use:
```
"editor.fontLigatures": "'calt', 'ss01'",
```
If you're using an environment that does not support the `ss01` OT feature, one option to consider is [opentype-feature-freezer](https://github.com/twardoch/fonttools-opentype-feature-freezer/).
# Character Sets



# Installation
**You can download the latest version of Cascadia Code from the releases page here:** [https://github.com/microsoft/cascadia-code/releases](https://github.com/microsoft/cascadia-code/releases)
##### Font formats:
- `ttf variable`: we recommend this version for **all users,** and particularly those on Windows or any other OS that employs TrueType hinting. It offers the greatest diversity of weight options (anything from 200-700).
- `ttf static`: in the rare situation where the above variable font version is not supported, or a singular weight is preferred to the entire range, static formats are supplied. However, please note they do not have the same degree of hinting quality as the variable font versions.
- `otf static`: for users who prefer OTF format fonts, otf static instances are provided. At this time we do not have a variable font OTF version.
- `WOFF2`: These versions are provided for the purposes of web use, and are available both as variable fonts, and static instances.
Once unzipped, right-click the font file and click `Install for all users`. This will install the font onto your machine.
👉 **Note:** If you have previously installed a version of Cascadia Code, please uninstall the previous version *prior* to installing a new version. Not doing so can result in improper rendering.
For more details and app-specific instructions, [please check the wiki](https://github.com/microsoft/cascadia-code/wiki/Installing-Cascadia-Code).
# Get involved
Instructions on how to modify and submit an update to the Cascadia Code source is [available in the wiki](https://github.com/microsoft/cascadia-code/wiki/Modifying-Cascadia-Code).
# Communicating with the Team
The easiest way to communicate with the team is via GitHub Issues. Please file new issues, feature requests and suggestions, but **DO search for similar open/closed pre-existing issues before you do**.
Please help us keep this repository clean, inclusive, and fun! We will not tolerate any abusive, rude, disrespectful or inappropriate behavior. Read our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/) for more details.
If you would like to ask a question that you feel doesn't warrant an issue (yet), please reach out to us via Twitter:
Aaron Bell, Font Designer: [@aaronbell](https://twitter.com/aaronbell)
Christopher Nguyen, Product Manager: [@nguyen_dows](https://twitter.com/nguyen_dows)
Dustin Howett, Software Engineer: [@DHowett](https://twitter.com/DHowett)
_Special thanks_ to:
- Fira Code – OpenType code for the coding ligatures – [github](https://github.com/tonsky/FiraCode)
- Nerd Fonts – Centralizing app iconography – [github](https://github.com/ryanoasis/nerd-fonts)
- Viktoriya Grabowska – Designer of Cyrillic Italic and Consultant – [@vika_grabowska](https://twitter.com/vika_grabowska)
- Mohamad Dakak - Arabic designer - [@mohamaddakak](https://twitter.com/mohamaddakak)
- Liron Lavi Turkenich - Hebrew designer - [@LironLaviTur](https://twitter.com/LironLaviTur)
- Gerry Leonidas – Greek Consultant – [@gerryleonidas](https://twitter.com/gerryleonidas)
- Donny Trương – Vietnamese Consultant – [Vietnamese Typography](https://vietnamesetypography.com)
# Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
|
cascadia-code/README.md/0
|
{
"file_path": "cascadia-code/README.md",
"repo_id": "cascadia-code",
"token_count": 1565
}
| 465 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="AEacute" format="2">
<advance width="1200"/>
<unicode hex="01FC"/>
<outline>
<component base="AE"/>
<component base="acutecomb.case" xOffset="119"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_E_acute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_E_acute.glif",
"repo_id": "cascadia-code",
"token_count": 96
}
| 466 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Beta" format="2">
<advance width="1200"/>
<unicode hex="0392"/>
<outline>
<component base="B"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/B_eta.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/B_eta.glif",
"repo_id": "cascadia-code",
"token_count": 74
}
| 467 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Dafrican" format="2">
<advance width="1200"/>
<unicode hex="0189"/>
<outline>
<component base="Eth"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/D_african.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/D_african.glif",
"repo_id": "cascadia-code",
"token_count": 76
}
| 468 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ecircumflexacute" format="2">
<advance width="1200"/>
<unicode hex="1EBE"/>
<outline>
<component base="E"/>
<component base="circumflexcomb.case" xOffset="30"/>
<component base="acutecomb.case" xOffset="493" yOffset="248"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top_viet</string>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>acutecomb.case</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_circumflexacute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_circumflexacute.glif",
"repo_id": "cascadia-code",
"token_count": 327
}
| 469 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="En-cy" format="2">
<advance width="1200"/>
<unicode hex="041D"/>
<outline>
<component base="H"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_n-cy.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_n-cy.glif",
"repo_id": "cascadia-code",
"token_count": 76
}
| 470 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Gheupturn-cy" format="2">
<advance width="1200"/>
<unicode hex="0490"/>
<anchor x="600" y="0" name="bottom"/>
<anchor x="600" y="1420" name="top"/>
<outline>
<contour>
<point x="163" y="0" type="line"/>
<point x="427" y="0" type="line"/>
<point x="427" y="1420" type="line"/>
<point x="163" y="1420" type="line"/>
</contour>
<contour>
<point x="163" y="1177" type="line"/>
<point x="1110" y="1177" type="line"/>
<point x="1110" y="1420" type="line"/>
<point x="163" y="1420" type="line"/>
</contour>
<contour>
<point x="847" y="1270" type="line"/>
<point x="1110" y="1270" type="line"/>
<point x="1110" y="1730" type="line"/>
<point x="847" y="1730" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/G_heupturn-cy.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/G_heupturn-cy.glif",
"repo_id": "cascadia-code",
"token_count": 408
}
| 471 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Imacron-cy" format="2">
<advance width="1200"/>
<unicode hex="04E2"/>
<outline>
<component base="Ii-cy"/>
<component base="macroncomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/I_macron-cy.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/I_macron-cy.glif",
"repo_id": "cascadia-code",
"token_count": 96
}
| 472 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="K.half" format="2">
<advance width="840"/>
<outline>
<contour>
<point x="202" y="167" type="line"/>
<point x="565" y="167"/>
<point x="775" y="437"/>
<point x="775" y="639" type="curve"/>
<point x="619" y="639" type="line"/>
<point x="619" y="516"/>
<point x="497" y="305"/>
<point x="215" y="305" type="curve"/>
</contour>
<contour>
<point x="109" y="0" type="line"/>
<point x="260" y="0" type="line"/>
<point x="260" y="639" type="line"/>
<point x="109" y="639" type="line"/>
</contour>
<contour>
<point x="639" y="0" type="line"/>
<point x="823" y="0" type="line"/>
<point x="567" y="387" type="line"/>
<point x="430" y="324" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/K_.half.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/K_.half.glif",
"repo_id": "cascadia-code",
"token_count": 419
}
| 473 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Lcaron" format="2">
<advance width="1200"/>
<unicode hex="013D"/>
<outline>
<contour>
<point x="704" y="1188" type="line"/>
<point x="951" y="1188" type="line"/>
<point x="1041" y="1568" type="line"/>
<point x="754" y="1568" type="line"/>
</contour>
<component base="L"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>L</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/L_caron.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/L_caron.glif",
"repo_id": "cascadia-code",
"token_count": 372
}
| 474 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ncaron" format="2">
<advance width="1200"/>
<unicode hex="0147"/>
<outline>
<component base="N"/>
<component base="caroncomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/N_caron.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/N_caron.glif",
"repo_id": "cascadia-code",
"token_count": 90
}
| 475 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ocircumflexacute" format="2">
<advance width="1200"/>
<unicode hex="1ED0"/>
<outline>
<component base="O"/>
<component base="circumflexcomb.case"/>
<component base="acutecomb.case" xOffset="463" yOffset="248"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top_viet</string>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>acutecomb.case</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_circumflexacute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_circumflexacute.glif",
"repo_id": "cascadia-code",
"token_count": 322
}
| 476 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ohungarumlaut" format="2">
<advance width="1200"/>
<unicode hex="0150"/>
<outline>
<component base="O"/>
<component base="hungarumlautcomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_hungarumlaut.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_hungarumlaut.glif",
"repo_id": "cascadia-code",
"token_count": 96
}
| 477 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Sacute.loclPLK" format="2">
<advance width="1200"/>
<outline>
<component base="S"/>
<component base="acutecomb.case.loclPLK" xOffset="20"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/S_acute.loclP_L_K_.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/S_acute.loclP_L_K_.glif",
"repo_id": "cascadia-code",
"token_count": 95
}
| 478 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Tbar" format="2">
<advance width="1200"/>
<unicode hex="0166"/>
<outline>
<contour>
<point x="172" y="561" type="line"/>
<point x="1028" y="561" type="line"/>
<point x="1028" y="803" type="line"/>
<point x="172" y="803" type="line"/>
</contour>
<component base="T"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>T</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/T_bar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/T_bar.glif",
"repo_id": "cascadia-code",
"token_count": 368
}
| 479 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ucircumflex" format="2">
<advance width="1200"/>
<unicode hex="00DB"/>
<outline>
<component base="U"/>
<component base="circumflexcomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/U_circumflex.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/U_circumflex.glif",
"repo_id": "cascadia-code",
"token_count": 92
}
| 480 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ytilde" format="2">
<advance width="1200"/>
<unicode hex="1EF8"/>
<outline>
<component base="Y"/>
<component base="tildecomb.case" xOffset="10"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/Y_tilde.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/Y_tilde.glif",
"repo_id": "cascadia-code",
"token_count": 97
}
| 481 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="_fourdotscenter-ar" format="2">
<advance width="1200"/>
<outline>
<component base="dotbelow-ar" xScale="0.9" yScale="0.9" xOffset="-60" yOffset="681"/>
<component base="dotbelow-ar" xScale="0.9" yScale="0.9" xOffset="-63" yOffset="434"/>
<component base="dotbelow-ar" xScale="0.9" yScale="0.9" xOffset="183" yOffset="682"/>
<component base="dotbelow-ar" xScale="0.9" yScale="0.9" xOffset="180" yOffset="435"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>dotbelow-ar</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>dotbelow-ar</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>3</integer>
<key>name</key>
<string>dotbelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_fourdotscenter-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_fourdotscenter-ar.glif",
"repo_id": "cascadia-code",
"token_count": 707
}
| 482 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ae-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="heh-ar.fina"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ae-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ae-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 140
}
| 483 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ainThreedotsdownabove-ar" format="2">
<advance width="1200"/>
<unicode hex="075E"/>
<anchor x="511" y="1704" name="top"/>
<outline>
<component base="ain-ar"/>
<component base="threedotsdownabove-ar" xScale="1.001" xOffset="-94" yOffset="476"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>threedotsdownabove-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_hreedotsdownabove-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_hreedotsdownabove-ar.glif",
"repo_id": "cascadia-code",
"token_count": 378
}
| 484 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefMadda-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="alef-ar.fina.short"/>
<component base="madda-ar" xOffset="-187" yOffset="81"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefM_adda-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefM_adda-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 485 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefTwoabove-ar.fina.alt" format="2">
<anchor x="0" y="0" name="_overlap"/>
<anchor x="319" y="-141" name="bottom"/>
<anchor x="59" y="1570" name="top"/>
<outline>
<component base="two-persian.small01" xOffset="-582" yOffset="-83"/>
<component base="alef-ar.fina.short.alt" xOffset="6"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>two-persian.small01</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>alef-ar.fina.short.alt</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefT_woabove-ar.fina.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefT_woabove-ar.fina.alt.glif",
"repo_id": "cascadia-code",
"token_count": 541
}
| 486 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefabove-ar" format="2">
<unicode hex="0670"/>
<anchor x="621" y="527" name="_top"/>
<anchor x="620" y="414" name="_top.dot"/>
<anchor x="573" y="1025" name="top"/>
<outline>
<component base="_alefabove" xOffset="-1" yOffset="3"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>_alefabove</string>
</dict>
</array>
<key>com.schriftgestaltung.Glyphs.originalWidth</key>
<integer>1200</integer>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefabove-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefabove-ar.glif",
"repo_id": "cascadia-code",
"token_count": 420
}
| 487 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="approxequal" format="2">
<advance width="1200"/>
<unicode hex="2248"/>
<outline>
<component base="asciitilde" yOffset="290"/>
<component base="asciitilde" yOffset="-290"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>asciitilde</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>asciitilde</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/approxequal.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/approxequal.glif",
"repo_id": "cascadia-code",
"token_count": 430
}
| 488 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="asterisk_asterisk_asterisk.liga" format="2">
<advance width="1200"/>
<outline>
<component base="asterisk" xOffset="2340"/>
<component base="asterisk" xOffset="60"/>
<component base="asterisk" xOffset="1208" yOffset="300"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>asterisk</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>asterisk</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>asterisk</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/asterisk_asterisk_asterisk.liga.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/asterisk_asterisk_asterisk.liga.glif",
"repo_id": "cascadia-code",
"token_count": 568
}
| 489 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="bar_bar.liga" format="2">
<advance width="1200"/>
<outline>
<component base="bar" xOffset="1070"/>
<component base="bar" xOffset="130"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>bar</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>bar</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_bar.liga.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_bar.liga.glif",
"repo_id": "cascadia-code",
"token_count": 410
}
| 490 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="bar_hyphen_end.seq" format="2">
<advance width="1200"/>
<outline>
<contour>
<point x="-20" y="584" type="line"/>
<point x="604" y="584" type="line"/>
<point x="604" y="834" type="line"/>
<point x="-20" y="834" type="line"/>
</contour>
<component base="bar"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_hyphen_end.seq.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_hyphen_end.seq.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 491 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="beh-ar" format="2">
<advance width="1200"/>
<unicode hex="0628"/>
<outline>
<component base="behDotless-ar"/>
<component base="dotbelow-ar" xOffset="-20" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beh-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beh-ar.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 492 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behThreedotsupbelow-ar.alt" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.alt"/>
<component base="threedotsupbelow-ar" xOffset="-620" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotsupbelow-ar.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotsupbelow-ar.alt.glif",
"repo_id": "cascadia-code",
"token_count": 173
}
| 493 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behVabove-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.fina"/>
<component base="vabove-ar" xOffset="-10" yOffset="93"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>vabove-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_above-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_above-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 343
}
| 494 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behVinvertedbelow-ar.init.alt" format="2">
<advance width="1200"/>
<anchor x="0" y="0" name="overlap"/>
<outline>
<component base="behDotless-ar.init.alt"/>
<component base="_vinvertedbelow-ar" xOffset="210" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_invertedbelow-ar.init.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_invertedbelow-ar.init.alt.glif",
"repo_id": "cascadia-code",
"token_count": 192
}
| 495 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="bellControl" format="2">
<advance width="1200"/>
<unicode hex="2407"/>
<outline>
<component base="B.half" xOffset="-10" yOffset="781"/>
<component base="L.half" xOffset="370"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>B.half</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>L.half</string>
</dict>
</array>
<key>com.schriftgestaltung.Glyphs.glyph.widthMetricsKey</key>
<string>space</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bellC_ontrol.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bellC_ontrol.glif",
"repo_id": "cascadia-code",
"token_count": 475
}
| 496 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="colon_colon.liga" format="2">
<advance width="1200"/>
<outline>
<component base="colon" xOffset="140"/>
<component base="colon" xOffset="1060"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>colon</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>colon</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/colon_colon.liga.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/colon_colon.liga.glif",
"repo_id": "cascadia-code",
"token_count": 416
}
| 497 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dadDotbelow-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="dad-ar.medi"/>
<component base="dotbelow-ar" xOffset="50" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dadD_otbelow-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dadD_otbelow-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 164
}
| 498 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dalThreedotsbelow-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="dal-ar.fina"/>
<component base="threedotsdownbelow-ar" xOffset="-40" yOffset="-4"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalT_hreedotsbelow-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalT_hreedotsbelow-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 499 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dataLinkEscapeControl.ss20" format="2">
<advance width="1200"/>
<outline>
<contour>
<point x="109" y="635" type="line"/>
<point x="1091" y="635" type="line"/>
<point x="1091" y="785" type="line"/>
<point x="109" y="785" type="line"/>
</contour>
<component base="whiteSquare" yScale="-1" yOffset="1420"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.glyph.widthMetricsKey</key>
<string>space</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dataL_inkE_scapeC_ontrol.ss20.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dataL_inkE_scapeC_ontrol.ss20.glif",
"repo_id": "cascadia-code",
"token_count": 251
}
| 500 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="deviceControlFourControl" format="2">
<advance width="1200"/>
<unicode hex="2414"/>
<outline>
<component base="D.half" xOffset="-10" yOffset="781"/>
<component base="four.half" xOffset="370"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>D.half</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>four.half</string>
</dict>
</array>
<key>com.schriftgestaltung.Glyphs.glyph.widthMetricsKey</key>
<string>space</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/deviceC_ontrolF_ourC_ontrol.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/deviceC_ontrolF_ourC_ontrol.glif",
"repo_id": "cascadia-code",
"token_count": 477
}
| 501 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="e-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="beeh-ar.medi"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/e-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/e-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 138
}
| 502 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ellipsis" format="2">
<advance width="1200"/>
<unicode hex="2026"/>
<outline>
<component base="period" xOffset="-398"/>
<component base="period" xOffset="398"/>
<component base="period"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>period</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>period</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>period</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ellipsis.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ellipsis.glif",
"repo_id": "cascadia-code",
"token_count": 554
}
| 503 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="feh-ar.init.alt" format="2">
<advance width="1200"/>
<anchor x="0" y="0" name="overlap"/>
<outline>
<component base="fehDotless-ar.init.alt"/>
<component base="dotabove-ar" xOffset="164" yOffset="460"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/feh-ar.init.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/feh-ar.init.alt.glif",
"repo_id": "cascadia-code",
"token_count": 187
}
| 504 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="fehDotbelowThreedotsabove-ar.fina.alt" format="2">
<advance width="1200"/>
<guideline x="-457" y="-107" angle="0"/>
<outline>
<component base="fehDotless-ar.fina.alt"/>
<component base="dotbelow-ar" xOffset="-37" yOffset="-24"/>
<component base="threedotsupabove-ar" xOffset="2" yOffset="347"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>dotbelow-ar</string>
</dict>
<dict>
<key>anchor</key>
<string>top.dot</string>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>threedotsupabove-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehD_otbelowT_hreedotsabove-ar.fina.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehD_otbelowT_hreedotsabove-ar.fina.alt.glif",
"repo_id": "cascadia-code",
"token_count": 534
}
| 505 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="fehThreedotsbelow-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="fehDotless-ar.init"/>
<component base="threedotsdownbelow-ar" xOffset="13" yOffset="-4"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehT_hreedotsbelow-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehT_hreedotsbelow-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 173
}
| 506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.