vania-janet/multiturn-rag-retrieval-data huggingface dataset:
For more information, see [Endpoints](https://cloud.ibm.com/docs/atracker?topic=atracker-endpointsendpoints_api).

The following is an example when the migration is 50% complete ("progress": 50).

{
"progress": 50,
"status": "in-process",
"migration_items": [
{
"resource_type": "route",
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"status": "completed",
"detailed_status":
"migration of this resource is successful."
],
"error" : "",
},
{
"resource_type": "target",
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"status": "pending",
"detailed_status":
"migration of this resource is not started yet."
],
"error" : ""
},
]
}





 Step 5. Initialize the CLI plugin to use the V2 API after migrating 

Initialize the Activity Tracker Event Routing CLI plugin to use the API version 2. Run the following command:

ibmcloud atracker init version





 HTTP response codes 

When you use the Activity Tracker Event Routing REST API, you can get standard HTTP response codes to indicate whether a method completed successfully.



* A 200 response always indicates success.
* A 4xx response indicates a failure.
* A 5xx response usually indicates an internal system error.



See the following table for some HTTP response codes:



Table 4. List of HTTP response codes

 Status code Status Description 

 200 OK The request was successful. 
 201 OK The request was successful. A resource is created. 
 400 Bad Request The request was unsuccessful. You might be missing a parameter that is required. 
 401 Unauthorized The IAM token that is used in the API request is invalid or expired.
ListObjectsV2Request request = new ListObjectsV2Request()
.withBucketName(bucketName)
.withMaxKeys(maxKeys)
.withContinuationToken(nextToken);

ListObjectsV2Result result = _cosClient.listObjectsV2(request);
for(S3ObjectSummary objectSummary : result.getObjectSummaries()) {
System.out.printf("Item: %s (%s bytes)n", objectSummary.getKey(), objectSummary.getSize());
deleteItem(bucketName, objectSummary.getKey());
}

if (result.isTruncated()) {
nextToken = result.getNextContinuationToken();
System.out.println("...More results in next batch!n");
}
else {
nextToken = "";
moreResults = false;
}
}
System.out.println("...No more results!");
}

public static void deleteItem(String bucketName, String itemName) {
System.out.printf("Deleting item: %sn", itemName);
_cosClient.deleteObject(bucketName, itemName);
System.out.printf("Item: %s deleted!n", itemName);
}

}

Show more

import ibm_boto3
from ibm_botocore.client import Config, ClientError

 Constants for IBM COS values
COS_ENDPOINT = "<endpoint>" Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints
Resolve those errors and run the script until you are able to get a valid response and generate a plan.
8. If you want to check the logs of the action, see [Retrieving action logs with Schematics API](https://cloud.ibm.com/docs/ibm-spectrum-lsf?topic=ibm-spectrum-lsf-retrieve-action-logs) to retrieve the logs. The response contains the status of the action, and it appears in either a COMPLETED or FAILED state.





 Example Python request 

 Generate a plan using Schematics Python API

import json, logging

from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_schematics.schematics_v1 import SchematicsV1

logging.basicConfig()
logging.root.setLevel(logging.NOTSET)
logging.basicConfig(level=logging.NOTSET)

authenticator = IAMAuthenticator('<ibmcloud-api-key>')

schematics_service = SchematicsV1(authenticator = authenticator)

schematics_service.set_service_url('https://us.schematics.cloud.ibm.com')

logging.info("Started Generating Schematic Plan")

workspace_activity_plan_result = schematics_service.plan_workspace_command(
    w_id='<workspace id>',
    refresh_token='<refresh-token>'
).get_result()

print(json.dumps(workspace_activity_plan_result, indent=2))

logging.info("Completed Generating Schematic Plan")





 Example Python response 

INFO:root:Started Generating Schematic Plan
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): iam.cloud.ibm.com:443
DEBUG:urllib3.connectionpool:https://iam.cloud.ibm.com:443 "POST /identity/token HTTP/1.1" 200 985
* The response must be a JSON object (Accept: application/json).
* The call must return in 8 seconds or less. If invoked more than once in a single message call through [dialog nodes](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-webhooksdialog-webhooks-dialog-node-callout), all of those invocations must return in 8 seconds or less.



If your external service supports only GET requests, or if you need to specify URL parameters dynamically at run time, consider creating an intermediate service that accepts a POST request with a JSON payload containing any runtime values. The intermediate service can then make a request to the target service, passing these values as URL parameters, and then return the response to the dialog.

If you need to call a service that might not return within 8 seconds, you can manage the call through a custom client application and pass the information to the dialog as a separate step. For more information, see [Calling a client application from a dialog node](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-actions-client).

To add the webhook details, complete the following steps:



1. From the skill where you want to add the webhook, click the Options tab.
2. Click Webhooks.
3. In the URL field, add the URL for the external application to which you want to send HTTP POST request callouts.

For example, to call the Language Translator service, specify the URL for your service instance.

https://api.us-south.language-translator.watson.cloud.ibm.com/v3/translate?version=2018-05-01

If the external application that you call returns a response, it must be able to send back a response in JSON format. For the Language Translator service, for example, you must specify the format in which you want the result to be returned. You can do so by passing a header to the service.
4.
"response": ]
},
{
"name": "Retrieve text file",
"event":
{
"listen": "test",
"script": {
"id": "58817cc7-7d15-45a9-b372-7712d2fd389d",
"type": "text/javascript",
"exec":
"pm.test("Request was successful", function() {",
" pm.response.to.be.success; ",
"});",
"",
"pm.test("Response contains expected body content", function() {",
" pm.expect(pm.response.text()).to.include("This is test data");",
"});",
"",
"pm.test("Response contains expected header", function() {",
" pm.response.to.have.header("ETag");",
"});"
]
}
}
],
"request": {
"auth": {
"type": "bearer",
"bearer":
{
"key": "token",
"value": "{{iamtoken}}",
"type": "string"
}
]
},
"method": "GET",
"header": ],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "https://{{endpoint-region}}cloud-object-storage.appdomain.cloud/{{bucket}}/testfile.txt",
"protocol": "https",
"host":
"{{endpoint-region}}",
"objectstorage",
"softlayer",
"net"
}).promise()
.then(() => {
console.log(Multi-part upload aborted for ${itemName});
})
.catch(logError);
}

// Constants for IBM COS values
const COS_ENDPOINT = "<endpoint>"; // example: s3.us-south.cloud-object-storage.appdomain.cloud
const COS_API_KEY_ID = "<api-key"; // example: xxxd12V2QHXbjaM99G9tWyYDgF_0gYdlQ8aWALIQxXx4
const COS_AUTH_ENDPOINT = "https://iam.cloud.ibm.com/identity/token";
const COS_SERVICE_CRN = "<resource-instance-id>"; // example: crn:v1:bluemix:public:cloud-object-storage:global:a/<CREDENTIAL_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::
const COS_STORAGE_CLASS = "<storage-class>"; // example: us-south-standard

// Init IBM COS library
var config = {
endpoint: COS_ENDPOINT,
apiKeyId: COS_API_KEY_ID,
ibmAuthEndpoint: COS_AUTH_ENDPOINT,
serviceInstanceId: COS_SERVICE_CRN,
signatureVersion: 'iam'
};

var cos = new ibm.S3(config);

// Main app
function main() {
try {
var newBucketName = "js.bucket." + getUUID();
var newTextFileName = "js_file_" + getUUID() + ".txt";
var newTextFileContents = "This is a test file from Node.js code sample!!!";
You can compute the success of the ZAP scan by setting an exit code based on whether the API scan or the UI scan was run. Any vulnerabilities found are also reported. This can be checked by tapping into the variables api-scan-result and ui-scan-result.

The possible values that these parameters can take are success or failure, and defaults to notRun.

ZAP_API_RESULT=$(get_env api-scan-result "notRun")
ZAP_UI_RESULT=$(get_env ui-scan-result "notRun")

if [ "${ZAP_API_RESULT}" = ^(success|notRun)$ && "${ZAP_UI_RESULT}" = ^(success|notRun)$ ]]; then
exit 0
else
exit 1
fi

A sample implementation can be found in the trigger_zap_scans file inside the scripts/zap directory inside [this repository](https://us-south.git.cloud.ibm.com/open-toolchain/hello-compliance-app).





 Configuring ZAP scan for CC pipeline 

Table 5 lists the additional parameters that are required to run ZAP scans inside the [CC pipeline](https://cloud.ibm.com/docs/devsecops?topic=devsecops-devsecops-cc-pipelinedevsecops-cc-pipeline-dynamic-scan).



Table 5. ZAP parameters in the CC pipeline

 Name Type Description Required or Optional 

 app-url String URL of the deployed application on which the ZAP scan runs. Use the staging url of the application. Required 
 repo-url String URL of the repository of the deployed application. Optional, if inventory repo has all the artifacts from only one application repo.
System.out.println(value);
break;
case BOOLEAN:
Boolean boolVal = (Boolean) feature.getCurrentValue(entityId, entityAttributes);
System.out.println(boolVal);
break;
case NUMERIC:
Integer intVal = (Integer) feature.getCurrentValue(entityId, entityAttributes);
System.out.println(intVal);
break;
}
}
Show more
* Get single property

Property property = appConfiguration.getProperty("propertyId");
* Get all properties

HashMap<String,Property> properties = appConfiguration.getProperties();
* Property evaluation

You can use the property.getCurrentValue() method to evaluate the value of the property. Pass a unique entityId as the parameter to perform the property evaluation. If the property is configured with segments in the App Configuration service, you can set the attributes values as a JSONObject.

JSONObject entityAttributes = new JSONObject();

try {
entityAttributes.put("city", "Bengaluru");
entityAttributes.put("country", "India");
} catch (JSONException e) {
e.printStackTrace();
}

AppConfiguration appConfiguration = AppConfiguration.getInstance();
Property property = appConfiguration.getProperty("propertyId");
String value = (String) property.getCurrentValue(entityId, entityAttributes);







 Supported data types 

App Configuration service configures the feature flag and properties in the following data types: Boolean, Numeric, String. The String data type can be of the format of a text string, JSON, or YAML. The SDK processes each format accordingly as shown in Table 1.



 Feature Flag
Resolve those errors and run the script until you are able to get a valid response and apply a plan.
7. If you want to check the logs of the action, see [Retrieving action logs with Schematics API](https://cloud.ibm.com/docs/hpc-spectrum-scale?topic=hpc-spectrum-scale-retrieve-action-logs) to retrieve the logs. The response contains the status of the action, and it appears in either a COMPLETED or FAILED state.



For more information on viewing successful or failed cluster deployments, see [Retrieving apply plan logs](https://cloud.ibm.com/docs/hpc-spectrum-scale?topic=hpc-spectrum-scale-retrieve-apply-plan-logs).



 Example Python request 

 Apply a plan using Schematics Python API

import json, logging

from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_schematics.schematics_v1 import SchematicsV1

logging.basicConfig()
logging.root.setLevel(logging.NOTSET)
logging.basicConfig(level=logging.NOTSET)

authenticator = IAMAuthenticator('<ibmcloud-api-key>')

schematics_service = SchematicsV1(authenticator = authenticator)

schematics_service.set_service_url('https://us.schematics.cloud.ibm.com')

logging.info("Started Applying Schematic Plan")

workspace_activity_apply_result = schematics_service.apply_workspace_command(
    w_id='<workspace id>',
    refresh_token='<refresh-token>'
).get_result()

print(json.dumps(workspace_activity_apply_result, indent=2))

logging.info("Completed Applying Schematic Plan")





 Example Python response 

INFO:root:Started Applying Schematic Plan
property.getPropertyDataFormat(); // YAML
property.getCurrentValue(entityId, entityAttributes); // Yaml String is returned
}
Show more





 Set listener for feature or property changes 

The SDK provides mechanism to notify you in real time when feature flag's or property's configuration changes. You can subscribe to configuration changes by using the same appConfigClient.

appConfigClient.registerConfigurationUpdateListener(new ConfigurationUpdateListener() {
@Override
public void onConfigurationUpdate() {
System.out.println("Received updated configurations");
// add your code
// To find the effect of any configuration changes, you can call the feature or property related methods

// Feature feature = appConfigClient.getFeature("numeric-feature");
// Integer newValue = (Integer) feature.getCurrentValue(entityId, entityAttributes);
}
});





 Fetch most recent data 

appConfigClient.fetchConfigurations();
When you use the IBM Cloud Activity Tracker Event Routing REST API, you can get standard HTTP response codes to indicate whether a method completed successfully.



* A 200 response always indicates success.
* A 4xx response indicates a failure.
* A 5xx response usually indicates an internal system error.



See the following table for some HTTP response codes:



Table 3. List of HTTP response codes

 Status code Status Description 

 200 OK The request was successful. 
 201 OK The request was successful. A resource is created. 
 400 Bad Request The request was unsuccessful. You might be missing a parameter that is required. 
 401 Unauthorized The IAM token that is used in the API request is invalid or expired. 
 403 Forbidden The operation is forbidden due to insufficient permissions. 
 404 Not Found The requested resource doesn't exist or is already deleted. 
 429 Too Many Requests Too many requests hit the API too quickly. 
 500 Internal Server Error Something went wrong in IBM Cloud Activity Tracker Event Routing processing.
fmt.Println("Feature Name", feature.GetFeatureName())
fmt.Println("Feature Id", feature.GetFeatureID())
fmt.Println("Feature Type", feature.GetFeatureDataType())
fmt.Println("Is feature enabled?", feature.IsEnabled())
}





 Feature evaluation 

You can use the feature.GetCurrentValue(entityId, entityAttributes) method to evaluate the value of the feature flag. GetCurrentValue returns one of the Enabled or Disabled or Overridden value based on the evaluation.

entityId := "john_doe"
entityAttributes := make(map[string]interface{})
entityAttributes["city"] = "Bangalore"
entityAttributes["country"] = "India"

featureVal := feature.GetCurrentValue(entityId, entityAttributes)



* entityId: entityId is a string identifier related to the Entity against which the feature will be evaluated. For example, an entity might be an instance of an app that runs on a mobile device, a microservice that runs on the cloud, or a component of infrastructure that runs that microservice. For any entity to interact with App Configuration, it must provide a unique entity ID.
* entityAttributes: entityAttributes is a map of type map[string]interface{} consisting of the attribute name and their values that defines the specified entity. This is an optional parameter if the feature flag is not configured with any targeting definition. If the targeting is configured, then entityAttributes must be provided for the rule evaluation. An attribute is a parameter that is used to define a segment. The SDK uses the attribute values to determine if the specified entity satisfies the targeting rules, and returns the appropriate feature flag value.







 Get single property 

property, err := appConfigClient.GetProperty("check-in-charges")
if err == nil {
curl -X POST -u "apikey:{apikey}" -H "Content-Type: application/json" -d "{"name": "my-first-collection", "description": "exploring collections", "configuration_id":"{configuration_id}" , "language": "en_us"}" "{url}/v1/environments/{environment_id}/collections?version=2019-04-30"

The API returns a response that includes information such as your collection ID, collection status, and how much storage your collection is using. Do not go on to the next step until your collection status is online. When you create the collection, if the status returns status:pending, use the GET /v1/environments/{environment_id}/collections/{collection_id} method to check the status until it is ready. In this example, replace {apikey} with your service credentials, replace {environment_id} with your environment ID, and replace {collection_id} with the collection ID that was returned earlier in this step.

curl -u "apikey:{apikey}" "{url}/v1/environments/{environment_id}/collections/{collection_id}?version=2019-04-30"





 Download example documents 

Download these documents:



* [test-doc1.html ![External link icon](https://cloud.ibm.com/docs-content/v1/content/ded4adc3ea0bd2a81b113c579f2b1183926da211/icons/launch-glyph.svg)](https://watson-developer-cloud.github.io/doc-tutorial-downloads/discovery/test-doc1.html)
* [test-doc2.html !
Reading a list of items from a KVS table (the order isn't guaranteed).
3. Writing thread-unsafe chaincode (query and invoke might be called in parallel).
4. Substituting global memory or cache storage for ledger state variables in chaincode.
5. Accessing external services, such as databases, directly from chaincode.
6. Using libraries or global variables that could introduce non-determinism (such as using "random" or "time").



Lastly, it is not recommended to write non-deterministic chaincode, which introduces risk to data consistency and integrity. The Hyperledger Fabric architecture is designed to counter against non-deterministic chaincode through a series of endorsement and validation checks. However, you are still urged to code deterministic functions that are not reliant on non-static global variables, such as time.
console.error(ERROR: ${e.code} - ${e.message}n);
});
}

SDK References



* [putObject](https://ibm.github.io/ibm-cos-sdk-js/AWS/S3.htmlputObject-property)







 List buckets 

function getBuckets() {
console.log('Retrieving list of buckets');
return cos.listBuckets()
.promise()
.then((data) => {
if (data.Buckets != null) {
for (var i = 0; i < data.Buckets.length; i++) {
console.log(Bucket Name: ${data.Buckets[i].Name});
}
}
})
.catch((e) => {
console.error(ERROR: ${e.code} - ${e.message}n);
});
}

SDK References



* [listBuckets](https://ibm.github.io/ibm-cos-sdk-js/AWS/S3.htmllistBuckets-property)







 List items in a bucket 

function getBucketContents(bucketName) {
console.log(Retrieving bucket contents from: ${bucketName});
return cos.listObjects(
{Bucket: bucketName},
).promise()
.then((data) => {
if (data != null && data.Contents != null) {
for (var i = 0; i < data.Contents.length; i++) {
var itemKey = data.Contents[i].Key;
var itemSize = data.Contents[i].Size;
console.log(Item: ${itemKey} (${itemSize} bytes).)
}
}
})
.catch((e) => {
" pm.response.to.be.success; ",
"});",
"",
"pm.test("Response contains expected header", function() {",
" pm.response.to.have.header("ETag");",
"});"
]
}
}
],
"request": {
"auth": {
"type": "bearer",
"bearer":
{
"key": "token",
"value": "{{iamtoken}}",
"type": "string"
}
]
},
"method": "PUT",
"header":
{
"key": "Content-Type",
"value": "application/x-www-form-urlencoded"
}
],
"body": {
"mode": "raw",
"raw": "This is test data for the text file."
},
"url": {
"raw": "https://{{endpoint-region}}cloud-object-storage.appdomain.cloud/{{bucket}}/testfile.txt",
"protocol": "https",
"host":
"{{endpoint-region}}",
"objectstorage",
"softlayer",
"net"
],
"path":
"{{bucket}}",
"testfile.txt"
]
},
"description": "Create a new text file in the bucket"
},
"response": ]
},
{
"name": "Create new binary file",
"event":
{
"listen": "test",
"script": {
The following JSON object shows a sample returned value.

{
"metadata": {
"collectionType": "application/vnd.ibm.kms.key+json",
"collectionTotal": 1
},
"resources": [
{
"type": "application/vnd.ibm.kms.key+json",
"id": "...",
"name": "Root-key",
"description": "...",
"state": 5,
"extractable": false,
"keyRingID": "default",
"crn": "...",
"imported": false,
"creationDate": "YYYY-MM-DDTHH:MM:SSZ",
"createdBy": "...",
"algorithmType": "AES",
"algorithmMetadata": {
"bitLength": 256,
"mode": "CBC_PAD"
},
"algorithmBitSize": 256,
"algorithmMode": "CBC_PAD",
"lastUpdateDate": "YYYY-MM-DDTHH:MM:SSZ",
"lastRotateDate": "YYYY-MM-DDTHH:MM:SSZ",
"dualAuthDelete": {
"enabled": true,
"keySetForDeletion": true,
"authExpiration": "YYYY-MM-DDTHH:MM:SSZ"
},
"deleted": true,
"deletionDate": "YYYY-MM-DDTHH:MM:SSZ",
"deletedBy": "...",
"purgeAllowed": true,
"purgeAllowedFrom": "YYYY-MM-DDTHH:MM:SSZ",
statusCode: 302
}
}





 Example 3: Generating a plain text response from a Function 

The following example illustrates how to generate a plain text response from a Function.

function main(params) {
var msg = 'You did not tell me who you are.';
if (params.name !== "") {
msg = Hello, ${params.name}!
}
return {
headers: { 'Content-Type': 'text/plain;charset=utf-8' },
body: ${msg}
}
}







 Error handling and debugging 

Function invocations can return system or application errors. For example, system errors indicate that the function code did not execute successfully, while application errors indicate a problem in the Function code itself.

When a system error occurs, an HTTP response code similar to the following codes is returned.



Table 1. HTTP response codes

 Code Description 

 409 The resources that are required by the Function could not be satisfied. 
 413 The request payload exceeds the defined maximum. 
 414 The invocation URI is too long. 
 416 The Function generated a response that exceeds the defined maximum. 
 422 The Function code could not be loaded from a specified source. 
 429 You exceeded your resource quota, could not schedule the Function. 
 431 The request headers exceed the defined maximum. 
 500 Internal server error. 
 502 Bad gateway. 
 503 Function currently unavailable, please try again later. 
 507 Insufficient storage to load the Function or Image. 



If Code Engine can execute the Functions code, it responds to the invocation with one of the following status codes.



Table 2. Status codes

 Code Description 

 200 Function invocation accepted, the Function will be executed delayed. 
 202 Function invocation accepted, the Function will be executed asynchronously. 
 299 The Function exceeded the specified or maximum runtime limit and was aborted. 



As a developer of a Function, you can generate any arbitrary HTTP status code, even the ones listed previously. Therefore, a response header indicates that the status code was generated by the Function code.
GenerateRandomResponse, err := cryptoClient.GenerateRandom(context.Background(), GenerateRandomRequest)
if err != nil {
return nil, fmt.Errorf("GenerateRandom error: %s", err)
}

iv := GenerateRandomResponse.Rnd[:ep11.AES_BLOCK_SIZE]
fmt.Println("Generated IV")

plainText := "Encrypt this message"
EncryptSingleRequest := &pb.EncryptSingleRequest{
Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
Key: GenerateKeyResponse.KeyBytes,
Plain: plainText,
}

EncryptSingleResponse, err := cryptoClient.EncryptSingle(context.Background(), EncryptSingleRequest)
Show more
* JavaScript code snippet

client.EncryptSingle({
Mech: {
Mechanism: ep11.CKM_AES_CBC_PAD,
ParameterB: iv
},
Key: aliceDerived.NewKey,
Plain: Buffer.from(message)
}, (err, response) => {
callback(err, response);
});







 ReencryptSingle 

With the ReencryptSingle function, you can decrypt data with the original key and then encrypt the raw data with a different key in a single call within the cloud HSM. The key types that are used for this operation can be the same or different. This function is an IBM EP11 extension to the standard PKCS #11 specification.