Google Translator API - api

I am using Google Translator API to translate English resource file to Spanish. I have around 6000 keys in my resource file. Right now I am passing keys one by one and getting the result. After some frequent hits(after some 1000 keys) to Google site I get 403 Terms of service abuse error.
Is there any other way I could translate all 6000 key values to Spanish?
I am using GoogleTranslateAPI_0.4_alpha API and below is the code.
ResXResourceReader rsxr = new ResXResourceReader (filename);
rsxr.UseResXDataNodes=true;
ResXDataNode node;
AssemblyName[] assemblies;
string value=string.Empty;
string comment=string.Empty;
foreach (DictionaryEntry d in rsxr)
{
node = (ResXDataNode)d.Value;
assemblies = Assembly.GetExecutingAssembly ().GetReferencedAssemblies ();
value=node.GetValue (assemblies).ToString ();
try
{
if (!string.IsNullOrEmpty (value))
{
TranslateClient client = new TranslateClient ("my proxy address");
value=client.Translate (value.ToString () ,"en" ,"es");
}
}
catch (Exception ex)
{
value="dummy";
}
}
rsxr.Close ();

We can't help you violate the Google terms of service, so your bet bet is to get a human to do it.
There are commercial programs that do translation, but I have not found any I like or even feel adequately do the job (a Google search will turn up a number of them and you can pick one).
Anyway, machine translations generally don't do so well with user interfaces because they are tuned for general conversation and not for the shorter blobs of text (not sentences) that you generally find in a program (so says a guy I know who works for Google).

Pay for it:
http://code.google.com/apis/language/translate/v2/pricing.html
See also Microsoft Translator:
https://datamarket.azure.com/dataset/1899a118-d202-492c-aa16-ba21c33c06cb

Related

Wit.ai seems to be jumping randomly between stories

I have two separate simple stories on my Wit.ai bot,
the first one takes in the word "Debug", sends "test" then runs a function that outputs context stuff to the console called test_context()
the second one takes in an address, runs a function that changes the context called new_session(), then sends a confirmation of the change to the user structured like "your location has been changed to {address}"
when I type directly into the wit.ai test console it seems to correctly detect the stories and run the corresponding functions, but when I try to use it through the Node.js API it seems to act completely randomly.
Sometimes when typing in an address it will run test_context() followed by new_session(), then output no text, sometimes it will just output the test text followed by the address text and run no functions, sometimes it will act correctly.
The same behavior happens when inputting "Debug" as well.
The back end is set up correctly, as 2 other stories seem to be working perfectly fine.
Both of these stories were working fine earlier today, I have made no changes to the wit stories themselves and no change to the back-end has even touched the debug function.
Is this a known issue?
I encountered this problem as well.
It appears to me as when you do not handle setting context variables in the story from wit.ai correctly (by setting them to null for example), it messes up the story. As a developer it is your own responsability to handle the story correctly "client side", so I can understand wit.ai lets weird stuff happen when you do not do this. Maybe wit.ai decided to jump stories to keep their bot from crashing, still remains a bit mysterious to me. Maybe your problem is of a different kind, just sharing a similair observation and my solution.
Exactly for reasons of testing I created three stories;
handle greetings
tell what the weather in city x is
identify when you want to plan a meeting
The bot is connected to facebook and I handle actions (like planning a meeting) on my nodejs express server.
I said to the bot "I want to plan a meeting tomorrow", resulting in a wit date/time. One timeslot by the way. This is going ok. Then I sent the message "I want to plan a meeting this morning". This resulted in TWO date/time variables in the wit.ai context. In turn, my code could not handle this; two timestamps resulted in null (probably json message getting more complicated and I try to get the wrong field). This in turn resulted in null for the context variable that had to be returned.
So what I did is to catch the error for when the context variable is not filled and just fill in [wit.js could not find date]. This fixed the problem, even though I now of course need to handle this error better.
Old code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
},}
New, working code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
if(myDateTime){
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
} else {
context.appointmentText = '[wit.js could not find date]'
return resolve(context);
}
});
},
Hope this helps

How to call more than 1000 web APIs with a main API with very less response time

I have to implement MVC .Net Web api (say "Main" api) which includes two parts.
1) Database call to fetch the record.
2) And more than 1000s of another web api call(response time 100 ms on avg. for each) which will use records returned by above db call.
Also, the Main api will be called in every 3 seconds continuously. I tried implementing using async/await method but didn't find much progress and when trying to test it using Apache Benchmark tool, it throws timeout specified has expired error.
Is there any way to achieve this? Please suggest.
Code snippet
[HttpGet]
public async Task<string> doTaskasync()
{
TripDetails obj = new TripDetails();
GPSCoordinates objGPS = new GPSCoordinates();
try
{
/* uriArray Contains more than 1000 APIs which needs to be exectued. */
string[] uriArray = await dolongrunningtaskasync();
IEnumerable<Task<GPSCoordinates>> allTasks = uriArray .Select(u => GetLocationsAsync(u));
IEnumerable<GPSCoordinates> allResults = await Task.WhenAll(allTasks);
}
catch (Exception ex)
{
return ex.Message ;
}
return "success";
}
Ab.exe test
There is nothing wrong programmatically with your code - except that this is practically a DOS attack on the second (location) API. You should definitely add caching to avoid at least part of the 1000 api calls, especially if you call the main api often (as you wrote).
What I would do is to make the inner api calls a centralized operation instead of making these calls individually inside your web api method. For example you could use a central list for location api calls (tasks) that have been started (but not finished), and another list for results that have been already finished. Both list could be a concurrent dictionary by the unique urls you use for the location api calls.

Why won't the Google Maps Directions API example in the 'Google Maps' book work for me?

I'm using the Petrousos 'Google Maps' book, and trying to run the example in the CHAPTER17/HTML/Directions Service.html downloaded from the book's website at www.mhprofessional.com at item 0071823026.
I had to adjust the table dimensions to get it to display properly, but otherwise made no changes. I'm running it through Firefox.
I set the origin and destination and clicked "Show Directions", at which point nothing happened.
The event called the following function:
function showDirections() {
var start = document.getElementById("origin").value;
var end = document.getElementById("destination").value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
printDirections(result);
}
});
}
I get as far as the directionsService.route call, but it is apparently not being executed, and status and result are not defined.
I have no idea how to debug this further, not having access to the API code..
Could the syntax of the call in the example be outdated?
I don't have an API key, but I understand it is not necessary, and I have run other examples without one.
Do you old examples still work? If not, then it's because you don't have an API key. Google will shut you down after you surpassed the quota. I believe the quota is at 50 requests per hours.
Google has the most recent documentation (and it's impressively well documented)
https://developers.google.com/maps/documentation/directions/intro#Audience
Also, can you look at what the object returns? If so, that will usually indicate the quote being surpassed. You can do this by setting a breakpoint at the link
if (status == google.maps.DirectionsStatus.OK) {
If you're using Chrome, you can get to the debugger by right-clicking on the page adn choosing 'Inspect Element', then go to sources, find your line of code and click the link number to set a breakpoint.

Web Service that converts address to lat/Long

I was wondering if anyone knows of a good web service that I can supply an address and it returns a Lat/Long in decimal degrees? I have been trying to play with the Google Maps API, but I cannot find the documentation for using a desktop app(Winforms) to return the data. I have used both WebClient and the WebRequest/WebResponse ways without success. The error is '610:Invalid key' though I am staring at the key and just copy/pasted it into the parameters - including making a new one. It seems Google is not an easy route and I would like a diff option if poss. Any ideas would be great. Thanks for looking.
You're looking for Google Geocoding API v3
There is no separate things for Desktop application. So you're looking exactly for this
"https://maps.googleapis.com/maps/api/geocode/xml?address=
your encodedAddress&sensor=false"
Here is a simple example I used in C#:
string address = "your address";
encodedAddress = HttpUtility.UrlEncode(address).Replace("+", "%20");
string googleApiURL = "https://maps.googleapis.com/maps/api/geocode/" + "xml?address=" + encodedAddress + "&sensor=false";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(googleApiURL);
request.Timeout = 10000;
request.Method = "GET";
WebResponse response = request.GetResponse();
if (response != null)
{
//Parse here to to capture the lat and long
}
else
{
//Handle if don't get response
}
For you, it won't be difficult to convert it to VB.NET.
The major part here is how you are going to parse the XML/JSON response, As I already bold faced in URL
Google provide two different response xml or json.
Don't forget to encode the address.
NOTE: Use of the Google Geocoding API is subject to a query limit of 2,500 requests per day.
Hope you got some idea.

check the availability of the WCF Web Service

I want to check the availability of the WCF web service i.c service is up or down through the C# code. How to achieve that?
When you call Client.Open if it is down that should throw an exception which you can trap.
What I prefer to do is implement a method which returns a boolean called Ping. The code basically just does return true; so it returns as quickly as possible. On the client side I call it and trap exceptions, if I get any then I know the web service is down.
You can extend the pattern to do things like PingCheckDB or PingCheckX which can do a fake/sample test run so you enable/disable functionality on the client based on what is available.
To elaborate on the previous answer: the only way to determine if a service is "available" is to first determine what you mean by "available". For instance, a service that depends on an external resource like a database may be perfectly available, but if the database cannot be accessed, then the service will be available but useless.
You should also ask what you are going to do with the information about availability. In particular, what would happen if you decided that the service was "available" yet, when you call it, you find that it is not really "available". An example would be if the above service was available and the database was available, but there was one particular stored procedure which would always fail. Is the service "available" in this case? How bad would it be if you indicated that it was available, but this one stored procedure failed?
In many cases, it's best to simply go ahead and make the calls to the web service, then handle any exceptions. If you've validated the parameters you're sending to the service, then, from the point of view of the end user, any failure of the service amounts to the service being unavailable.
It is not available to be successfully used, you see.
This is what I'm using and it works great. And ServiceController lives in namespace 'System.ServiceProcess' if you want to use a Using statement at the top to qualify it.
try
{
ServiceController sc = new ServiceController("Service Name", "Computer's IP Address");
Console.WriteLine("The service status is currently set to {0}",
sc.Status.ToString());
if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
(sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
Console.WriteLine("Service is Stopped, Ending the application...");
Console.Read();
EndApplication();
}
else
{
Console.WriteLine("Service is Started...");
}
}
catch (Exception)
{
Console.WriteLine("Error Occurred trying to access the Server service...");
Console.Read();
EndApplication();
}
I use the following code. It's simple and works...
public bool IsServiceRunning()
{
try
{
System.Net.WebClient wc = new System.Net.WebClient();
string s = wc.DownloadString(new Uri("http://localhost:27777/whatever/services/GatherDataService?wsdl"));
}
catch (Exception ex)
{
return false;
}
return true;
}
just take your endpoint uri and add the ?wsdl