unable to create a document with raw content on dialog flow knowledge bases - google-cloud-platform

i am using com.google.cloud.dialogflow.v2beta1.Document to create document through java rpc,we have a setContent() method which is used creating document with raw content, when i try to create document i am getting below exception.
Caused by: com.google.api.gax.rpc.InvalidArgumentException: Operation
with name
"projects/agent-fa5be/operations/ks-add_document-NDQ0NDQ3MjI5MDA3NTIxMzgyNA"
failed with status = GrpcStatusCode{transportCode=INVALID_ARGUMENT}
and message = CSV documents must have exactly two columns. The
provided document has 1 columns.
when i check dialogflow.v2beta1 Documentation there clearly mentioned content is deprecated use raw_content instead of content. but there is no supported method for raw_content in com.google.cloud.dialogflow.v2beta1.Document

I was experimenting a similar issue. I tried different libraries and techniques until I found something that worked. In my case I've to parse each row as follows:
let input = ['Question1', 'Answer1\n'];
let input2 = ['Question2', 'Answer2\n'];
let base64data = input.toString('base64') + input2.toString('base64');
const request = {
parent: 'projects/PROJECT_ID/knowledgeBases/KNOWLEDGEBASE_ID',
document: {
knowledgeTypes: ['FAQ'],
displayName: 'Echele',
content: base64data,
source: 'rawContent',
mimeType: 'text/csv',
},
};
This allowed my to submit the document, hope it works for you too!
Regards

Please find working solution
String documentName="test.csv";
try {
byte[] bytedata = filedata.toString().getBytes();
ByteString bytestring = ByteString.copyFrom(bytedata);
byte[] bytedata1 = "text/csv".getBytes();
ByteString mimestring = ByteString.copyFrom(bytedata1);
DocumentsSettings docuemtnSettings = DocumentsSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
DocumentsClient documentsClient = DocumentsClient.create(docuemtnSettings);
Document document = Document.newBuilder().setDisplayName(documentName).setContentBytes(bytestring)
.setMimeTypeBytes(mimestring).addKnowledgeTypes(KnowledgeType.FAQ).build();
CreateDocumentRequest createDocumentRequest = CreateDocumentRequest.newBuilder().setDocument(document)
.setParent(knowledgeBaseName).build();
OperationFuture<Document, KnowledgeOperationMetadata> response = documentsClient
.createDocumentAsync(createDocumentRequest);
Document createdDocument = response.get();
System.out.format(" - docuemnt created ID: %s\n", createdDocument.getName());

Related

PowerBI Query WebMethod.Post returns Expression.Error: We cannot convert the value "POST" to type Function

I'm using a website that requires that their API key AND query data be submitted using Webform.Post method. I'm able to get this to work in Python, C# and I'm even able to construct and execute a cURL command which returns a usable JSON file that Excel can parse. I am also using Postman to validate my parameters and everything looks good using all these methods. However, my goal is to build a query form that I can use within Excel but I can't get past this query syntax in PowerBi Query.
For now I am doing a simple query. That query looks like this:
let
url_1 = "https://api.[SomeWebSite].com/api/v1.0/search/keyword?apiKey=blah-blah-blah",
Body_1 = {
"SearchByKeywordRequest:
{
""keyword"": ""Hex Nuts"",
""records"": 0,
""startingRecord"": 0,
""searchOptions"": Null.Type,
""searchWithYourSignUpLanguage"": Null.Type
}"
},
Source = WebMethod.Post(url_1,Body_1)
in
Source
ScreenSnip showing valid syntax
It generates the following error:
Expression.Error: We cannot convert the value "POST" to type Function.
Details:
Value=POST
Type=[Type]
ScreenSnip of Error as it appears in PowerQuery Advanced Editor
I've spend the better part of the last two days trying to find either some example using this method or documentation. The Microsoft documentation simple states the follow:
WebMethod.Post
04/15/2018
2 minutes to read
About
Specifies the POST method for HTTP.
https://learn.microsoft.com/en-us/powerquery-m/webmethod-post
This is of no help and the only posts I have found so far criticize the poster for not using GET versus POST. I would do this but it is NOT supported by the website I'm using. If someone could just please either point me to a document which explains what I am doing wrong or suggest a solution, I would be grateful.
WebMethod.Post is not a function. It is a constant text value "POST". You can send POST request with either Web.Contents or WebAction.Request function.
A simple example that posts JSON and receives JSON:
let
url = "https://example.com/api/v1.0/some-resource-path",
headers = [#"Content-Type" = "application/json"],
body = Json.FromValue([Foo = 123]),
source = Json.Document(Web.Contents(url, [Headers = headers, Content = body])),
...
Added Nov 14, 19
Request body needs to be a binary type, and included as Content field of the second parameter of Web.Contents function.
You can construct a binary JSON value using Json.FromValue function. Conversely, you can convert a binary JSON value to a corresponding M type using Json.Document function.
Note {} is list type in M language, which is similar to JSON array. [] is record type, which is similar to JSON object.
With that said, your query should be something like this,
let
url_1 = "https://api.[SomeWebSite].com/api/v1.0/search/keyword?apiKey=blah-blah-blah",
Body_1 = Json.FromValue([
SearchByKeywordRequest = [
keyword = "Hex Nuts",
records = 0,
startingRecord = 0,
searchOptions = null,
searchWithYourSignUpLanguage = null
]
]),
headers = [#"Content-Type" = "application/json"],
source = Json.Document(Web.Contents(url_1, [Headers = headers, Content = Body_1])),
...
References:
Web.Contents (https://learn.microsoft.com/en-us/powerquery-m/web-contents)
Json.FromValue (https://learn.microsoft.com/en-us/powerquery-m/json-fromvalue)
Json.Document (https://learn.microsoft.com/en-us/powerquery-m/json-document)

Document Class of ASPOSE.WORDS.CLOUD

I am trying to convert a docx file to pdf using APOSE.WORDS-CLOUD SDK. But i am having the following error in Document class
Document doc = new Document("D:\Aspose\Template.docx");
error: 'Document' does not contain a constructor that takes 1 arguments
P.S please guide me to proper documentation/manual for using aspose.words.cloud SDK
#MetorGeek
There is no Document class in aspose-words-cloud .NET SDK. You may use the following example to convert Word document to PDF:
var format = "pdf";
using (var fileStream = File.OpenRead(BaseTestContext.GetDataDir(this.convertFolder) + "test_uploadfile.docx"))
{
var request = new PutConvertDocumentRequest(fileStream, format);
var result = this.WordsApi.PutConvertDocument(request);
}
Please check Converting a Document documentation section for a detailed description of Conversion APIs.

IBM Watson Alchemy news iOS SDK Swift

The IBM Watson iOS SDK using the Alchemy News service on Bluemix returns a string result which requires parsing to pull out the fields like url and cleaned title. ref: https://github.com/watson-developer-cloud/swift-sdk
I pull the string into an array and parse it in swift3 using some string methods but this is pretty ordinary and can produce unpredictable results
Is there a more elegant approach where I can access specific fields, like the url and cleaned title which I am passing to a UITableViewCell to select and segue to the url link.
sample code:
let alchemyDataNews = AlchemyDataNews(apiKey: apiKey)
let failure = { (error: Error) in print(error) }
let start = "now-14d" // 7 day ago
let end = "now" // today
let query = ["count": "15",
"dedup": "true",
"q.enriched.url.title": "[IBM]",
"return": "enriched.url.url,enriched.url.title" "enriched.url.title,enriched.url.entities.entity.text,enriched.url.entities.entity.type"]
Also I have noticed the search string [IBM] has a prefix of 0, i.e. 0[IBM] and have also seen an "A". What do these prefixes mean and where are they documented
Here is one way you can access the fields from a returned payload.
alchemyDataNews.getNews(from: "now-4d", to: "now", query: queryDict, failure: failWithError) { news in
for doc in (news.result?.docs)! {
var cleanedTitle = doc.source?.enriched?.url?.cleanedTitle
var author = doc.source?.enriched?.url?.author
var title = doc.source?.enriched?.url?.title
}}
Also, here is a nice API reference link for alchemy data which contains all of the request parameters and filters.
https://www.ibm.com/watson/developercloud/alchemydata-news/api/v1/

Multi-part form data upload with Akka HTTP

I'm trying to figure out how to create a multi-part form data request
with Akka HTTP (client API) but I can't find a way to express form data.
Does anyone know how to create form data that would take a file or input stream?
I guess a bit late right now, but this example, has both a client and a server.
I copy the relevant part
def createEntity(file: File): Future[RequestEntity] = {
require(file.exists())
val formData =
Multipart.FormData(
Source.single(
Multipart.FormData.BodyPart(
"test",
HttpEntity(MediaTypes.`application/octet-stream`, file.length(), SynchronousFileSource(file, chunkSize = 100000)), // the chunk size here is currently critical for performance
Map("filename" -> file.getName))))
Marshal(formData).to[RequestEntity]
}
def createRequest(target: Uri, file: File): Future[HttpRequest] =
for {
e ← createEntity(file)
} yield HttpRequest(HttpMethods.POST, uri = target, entity = e)
Simplest way to achieve this would be:
val formData = Multipart.FormData.
fromFile("<FORM_DATA_KEY>",
MediaTypes.`application/octet-stream`,
file = file,
100000)
val httpRequest = HttpRequest(HttpMethods.POST, uri = target, entity = formData.toEntity)
On the first line you can also use Multipart.FormData.fromPath which will accept file path instead of file object itself.

creating thumbnail from a pdf in coldfusion cfscript

I'm trying to create a thumbnail from a pdf in coldfusion, but no thumbnail gets created and no exception is thrown.
(coldfusion 9)
my code:
var source = "A:\testfolder\test.pdf";
var destination = "A:\testfolder\";
createImageFromPdf(source, destination);
createImageFromPdf function:
public void function createImageFromPdf(required string source, required string destination,
numeric pages = 1, string resolution = "low",
numeric scale = 100, boolean overwrite = true){
var pdf = new pdf();
pdf.setSource(arguments.source);
pdf.thumbnail(pages = arguments.pages, resolution = arguments.resolution,
scale = arguments.scale, overwrite = arguments.overwrite);
}
After running this code, i don't receive errors or exceptions, but no image was generated in A:\testfolder\
I'm probably missing something obvious here, but can't find it.
Also no log records are created in application or exception log, pdf is not protected and I'm sure that the folder is writable.
All help is appreciated.
Thanks.
You just forgot to pass along the destination
pdf.thumbnail(destination=arguments.destination
, pages = arguments.pages
, resolution = arguments.resolution
, scale = arguments.scale
, overwrite = arguments.overwrite);