MS Translator API Error - not working for Serbian/Croatian - translate

I have a question regarding MS Translator API. I followed "[Walkthrough: Microsoft Translator in a C# Console Application][1]" tutorial so I could use MS translate API from my app. When I try translating from "English" to "French" or some other language, everything works perfectly fine. But when translating from/to Serbian/Croatian, I get following error message: "Parameter: From has an invalid pattern of characters".
Since I am using automatic language detection, I didn't hard code any of the language acronyms:
string input = "Petar voli da ide u skolu"; // serbian
var sourceLanguage = Translator.DetectSourceLanguage(tc, input); // gets Croatian
var targetLanguage = PickRandomLanguage(tc); // select random language by using
// Handle the error condition
if (sourceLanguage != null)
{
var translationResult = Translator.TranslateString(tc, input, sourceLanguage, targetLanguage); // exception "Parameter: From has an invalid pattern of characters".
if (translationResult != null)
{
}
}
Is there a problem with the API, or Serbian/Croatian are not supported?

You use wrong or old script.
I use this script in php: Microsoft Translator doesn’t work in the Serbian and Croatian?
For C# use script from this page: https://msdn.microsoft.com/en-us/library/ff512421.aspx#csharpexample

Related

Microsoft speech to text is not identifying other than english language

I am using microsoft speech to text service. my requirement is to identify and convert any spoken language on microphone should converted on text . example if i speak spanish then i should get spanish language text as response.
here is my code and am setting config by providing subscription key and endpoint url
var config = SpeechConfig.FromHost(new Uri("ws://xxxxxxxx:5000/"));
using (var recognizer = new SpeechRecognizer(config))
{
Console.WriteLine("Say something...");
var result = await recognizer.RecognizeOnceAsync();
// Checks result.
if (result.Reason == ResultReason.RecognizedSpeech)
{
Console.WriteLine($"We recognized: {result.Text}");
}
}
Please help me how to get converted any speech to text languages.
A common task for speech recognition is specifying the input (or source) language. Let's take a look at how you would change the input language to German. In your code, find your SpeechConfig, then add this line directly below it.
speech_config.speech_recognition_language="de-DE"
speech_recognition_language is a parameter that takes a string as an argument. You can provide any value in the list of supported locales/languages.
Please use the locale in the table https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/language-support#speech-to-text
-Yutong
You can use language detection in the Speech Recognizer processing, see doc here
It has some limitations in terms of languages (see language support here).
How?
For a C# implementation, you should switch "Latency" to "Accuracy" depending on priority on the speechConfig object:
speechConfig.SetProperty(PropertyId.SpeechServiceConnection_SingleLanguageIdPriority, "Latency");
Add an AutoDetectSourceLanguageConfig config to your SpeechRecognizer:
Then you can have your result:
var autoDetectSourceLanguageConfig =
AutoDetectSourceLanguageConfig.FromLanguages(
new string[] { "en-US", "de-DE", "ja-JP", "de-DE" });
using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
using (var recognizer = new SpeechRecognizer(
speechConfig,
autoDetectSourceLanguageConfig,
audioConfig))
{
var speechRecognitionResult = await recognizer.RecognizeOnceAsync();
var autoDetectSourceLanguageResult =
AutoDetectSourceLanguageResult.FromResult(speechRecognitionResult);
var detectedLanguage = autoDetectSourceLanguageResult.Language;
}

PHP rawurlencode followed by JS decodeURIComponent gives malformed URI error

I have this piece of code that encodes an array of results from a database search:
foreach($searchResults[$i] as $key => $value) {
$searchResults[$i][$key] = rawurlencode($value);
}
I had to encode in order to pass the data as JSON to another page. On the other page, I'm trying to decode the resulting object like this in Javascript:
if (results !== null) {
for (var i = 0; i < results.length; i++) {
$.each(results[i], function (key, value) {
results[i][key] = decodeURIComponent(results[i][key]);
});
}
}
My problem is that I'm getting a URIError due to malformed URI. There are several pieces of data being passed, so my real question is if there is some method or tool that allows you to search an array of strings for the offending item. I have several results and don't relish the idea of having to go through them character by character to find the offending encoding. Does anyone have any suggestions? If I could figure out what character/characters is causing this error I would be on my way to figuring out a solution. I'm a coding newbie, so please forgive any incorrect use of terminology.
BTW - Sometimes this code works perfectly... I'm trying to find a way to narrow down the offending database items that are causing this error to occur periodically.

Autodesk Design Automation API extract Text from DWG file

I would like to use the Autodesk Design Automation API to extract all Text and Header information from a .dwg file into a json object. Is this possible with the Design Automation API?
Any example would help.
Thankyou
#Kaliph, yes, without a plugin in .NET/C++/Lisp code, it is impossible to extract block attributes by script only. I'd recommend .NET. It would be easier for you to get started with if you are not familiar with C++.
Firstly, I'd suggest you take a look at the training labs of AutoCAD .NET API:
https://www.autodesk.com/developer-network/platform-technologies/autocad
pick the latest version if you installed a latest version of AutoCAD. The main workflow of API is same across different versions, though. you can also pick C++ (ObjectARX) if you like.
In the tutorials above, it demos how to work with block. And the blog below talks about how to get attributes:
http://through-the-interface.typepad.com/through_the_interface/2006/09/getting_autocad.html
I copied here for convenience:
using Autodesk.AutoCAD;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
namespace MyApplication
{
public class DumpAttributes
{
[CommandMethod("LISTATT")]
public void ListAttributes()
{
Editor ed =
Application.DocumentManager.MdiActiveDocument.Editor;
Database db =
HostApplicationServices.WorkingDatabase;
Transaction tr =
db.TransactionManager.StartTransaction();
// Start the transaction
try
{
// Build a filter list so that only
// block references are selected
TypedValue[] filList = new TypedValue[1] {
new TypedValue((int)DxfCode.Start, "INSERT")
};
SelectionFilter filter =
new SelectionFilter(filList);
PromptSelectionOptions opts =
new PromptSelectionOptions();
opts.MessageForAdding = "Select block references: ";
PromptSelectionResult res =
ed.GetSelection(opts, filter);
// Do nothing if selection is unsuccessful
if (res.Status != PromptStatus.OK)
return;
SelectionSet selSet = res.Value;
ObjectId[] idArray = selSet.GetObjectIds();
foreach (ObjectId blkId in idArray)
{
BlockReference blkRef =
(BlockReference)tr.GetObject(blkId,
OpenMode.ForRead);
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
blkRef.BlockTableRecord,
OpenMode.ForRead
);
ed.WriteMessage(
"\nBlock: " + btr.Name
);
btr.Dispose();
AttributeCollection attCol =
blkRef.AttributeCollection;
foreach (ObjectId attId in attCol)
{
AttributeReference attRef =
(AttributeReference)tr.GetObject(attId,
OpenMode.ForRead);
string str =
("\n Attribute Tag: "
+ attRef.Tag
+ "\n Attribute String: "
+ attRef.TextString
);
ed.WriteMessage(str);
}
}
tr.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
ed.WriteMessage(("Exception: " + ex.Message));
}
finally
{
tr.Dispose();
}
}
}
}
I have a sample on making signs on a drawing. It covers getting attributes and modifying attributes:
https://forge.autodesk.com/cloud_and_mobile/2016/02/sign-title-block-of-dwg-file-with-autocad-io-view-data-api.html
And I also have a sample on getting Table cells of a drawing:
https://forge.autodesk.com/blog/get-cell-data-autocad-table-design-automation-api
Hope these could help you to make the plugin for your requirements.
What do you mean by "Header" information? Can you give an example?
Finding an extracting all text objects is relatively easy if you are familiar with the AutoCAD .NET API (or C++ or Lisp).
Here's an example that extracts blocks and layer names:
https://github.com/Autodesk-Forge/design.automation-.net-custom.activity.sample

In Microsoft Bot Framework session.conversationData.array of regexes changes to array of Object type after executing once

I am working with the below piece of code in Microsoft Bot Framework to access the list of regexes for global commands. This code is a part of botbuilder module:
if (typeof session.conversationData.globalCommands === "undefined") {
// An array which contains the list of all global commands
session.conversationData.globalCommands = [];
// Accessing the list of global commands
globalActions = session.library.actions.actions;
lenGlobalActions = Object.keys(globalActions).length;
// Assigning values to the above list
for (var i=0; i<lenGlobalActions; i++){
session.conversationData.globalCommands.push(globalActions[Object.keys(globalActions)[i]].options.matches);
}
}
// Checking if the incoming message from the user is a global command
var isGlobalCommand = session.conversationData.globalCommands.some(regex => regex.test(session.message.text));
The issue here is, the code runs fine for the first time and the values assigned to the variable session.conversationData.globalCommands are in the form given below:
However, after the first execution, the array converts to the below without any changes made in the code anywhere else:
Due to this, the line:
var isGlobalCommand = session.conversationData.globalCommands.some(regex => regex.test(session.message.text));
throws an exception "regex.test is not a function".
I am unable to understand why this should be happening and how do I solve this as I need this list separately for some processing.
I believe you cannot store complex types in the bot store (conversationData, etc). The object needs to be serializable to JSON and I don't believe a RegExp it is.
The workaround would be to store the regex as an string and then recreate the regex object using the constructor and the stored string expression.
Check the core-State sample to know more about the store capabilities.

How to hide code from editor using a projection

I am working on a custom language service. Code files of the language contain both metadata and source code, whereby metadata is stored as a header (at the beginning of the file; this requirement can´t be changed). The language service provides two logical views; one for the code and another one allowing to edit the metadata.
Now, the problem is that I want to hide the metadata from the code editor view - and I thought implementing it using projection is the way to go, but the Visual Studio SDK does neither contain any examples nor a good explanation on how to implement such functionality. Just a short explanation about the concept is given at: Inside the Editor, Projection
I also found a language service project at Codeplex: Python Tools for Visual Studio, which has Django support (in this project projection buffers are used to mix HTML markup and Python code), but this seems to be a different scenario...
This is what I tried...
Within my editor factory, I create an IVsTextLines instance that is used by the code editor view using the following code...
private IVsTextLines GetTextBuffer(IntPtr docDataExisting)
{
if (docDataExisting == IntPtr.Zero)
{
Type t = typeof(IVsTextLines);
Guid clsId = typeof(VsTextBufferClass).GUID;
Guid interfaceId = t.GUID;
IVsTextLines bufferInstance;
if ((bufferInstance = this.Package.CreateInstance(ref clsId, ref interfaceId, t) as IVsTextLines) != null)
{
object oleServiceProvider = this.GetService(typeof(IServiceProvider));
var withSite = (IObjectWithSite)bufferInstance;
withSite.SetSite(oleServiceProvider);
return bufferInstance;
}
}
return null;
}
From what I´ve seen so far is that the IVsTextLines interface is not compatible with IProjectionBuffer, ITextBuffer and so on. I learned from the Python Tools project that I can use a IVsEditorAdaptersFactoryService to get an ITextBuffer instance from the IVsTextLines object; the adapter factory service (as well as some other required service instances) gets injected into my editor factory via MEF...
IVsTextBuffer textBuffer = this.GetTextBuffer(...);
ITextBuffer documentBuffer = this.editorAdaptersFactoryService.GetDocumentBuffer(textBuffer);
The ITextBuffer can be used as a source buffer for projections... my idea is to create an elision buffer having to spans; one for the metadata and one for the code, whereby the metadata span will be elided which makes the code disapear, and use this elision buffer as the projection. This is what I tried...
private ITextBuffer CreateBuffer(
IProjectionEditResolver editResolver,
ITextBuffer documentBuffer)
{
IContentType contentType = this.ContentTypeRegistryService.GetContentType("...");
ITextSnapshot currentSnapshot = documentBuffer.CurrentSnapshot;
string text = currentSnapshot.GetText(0, currentSnapshot.Length);
TextRange textRange = Parser.GetMetadataTextRange(text); // parse code; return a text range representing the code to elide
ITrackingSpan elideSpan = currentSnapshot.CreateTrackingSpan(textRange.Start, textRange.Length, SpanTrackingMode.EdgeExclusive);
int offset = textRange.Start + textRange.Length;
ITrackingSpan expandSpan = currentSnapshot.CreateTrackingSpan(offset, currentSnapshot.Length - offset, SpanTrackingMode.EdgeInclusive);
SnapshotSpan elide = elideSpan.GetSpan(currentSnapshot);
SnapshotSpan expand = expandSpan.GetSpan(currentSnapshot);
var snapshotSpans = new List<SnapshotSpan>
{
elide,
expand
};
var spanCollection = new NormalizedSnapshotSpanCollection(snapshotSpans);
const ElisionBufferOptions BufferOptions = ElisionBufferOptions.FillInMappingMode;
IElisionBuffer buffer = this.ProjectionBufferFactoryService.CreateElisionBuffer(editResolver, spanCollection, BufferOptions, contentType);
buffer.ModifySpans(new NormalizedSpanCollection(elide), new NormalizedSpanCollection(expand));
return buffer;
}
Once the elision buffer is created, I use the SetDataBuffer method to connect it with the editor...
ITextBuffer buffer = this.CreateBuffer(..., documentBuffer);
this.editorAdaptersFactory.SetDataBuffer(textBuffer, buffer);
This works somehome; at least the metadata code disapears from the code editor, but as soon as try to edit the code, I got an InvalidOperationException, which is not the case, if I create the elision buffer with just a single span, or if I don´t hide the elideSpan.
The following error is reported to the ActivityLog:
System.InvalidOperationException: Shim buffer length mismatch. Document=11594 Surface=11577 Difference at 0
at
Microsoft.VisualStudio.Editor.Implementation.VsTextBufferAdapter.OnTextBufferChanged(Object sender, TextContentChangedEventArgs e)
at
Microsoft.VisualStudio.Text.Utilities.GuardedOperations.RaiseEvent[TArgs](Object sender, EventHandler`1 eventHandlers, TArgs args)
I think I am quite close to the final solution; so what I am doing wrong?

Resources