Can Microsoft Translator answer "does a word exist" queries? - microsoft-translator

I want to know if the API can do something like this:
I send a word in an predetermined language
API answer if the word exist in that language.
To add some context to the question, the idea is to develop a Scrabble like game, and I'm investigating a method to detect valid words, for all (or most common) languages that is.
I've already asked for a solution in one of their forums, but they are kind of dead.

I tested the MS translator service.
var result = MST.TranslateText("xyz", "en", "de"); // custom routine that calls MS service
var result2 = MST.TranslateText("dog", "en", "de");
var result2 = MST.TranslateText("sdfasfgd", "en", "de");
Result = XYZ // source xyz
Result2 = Hund // source dog
Result3 = sdfasfgd // sdfasfgd
Looks like when not found or a translation is not possible the string
is returned untouched.
The only strange behavior i've noted is conversion to uppercase for Some 3 letter scenarios that
arent obvious TLAs in either langauge.
public string TranslateText(string sourceText, string fromLang, string toLang) {
var httpRequestProperty = GetAuthorizationRequestHeader();
var msTransClient = new TranslatorService.LanguageServiceClient();
// Creates a block within which an OperationContext object is in scope.
using (var scope = new OperationContextScope(msTransClient.InnerChannel))
{
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
//Keep appId parameter blank as we are sending access token in authorization header.
var translationResult = msTransClient.Translate("", sourceText, fromLang, toLang, "text/plain", "");
return translationResult;
}
}

Related

Is there a simple way to have a local webpage display a variable passed in the URL?

I am experimenting with a Firefox extension that will load an arbitrary URL (only via HTTP or HTTPS) when certain conditions are met.
With certain conditions, I just want to display a message instead of requesting a URL from the internet.
I was thinking about simply hosting a local webpage that would display the message. The catch is that the message needs to include a variable.
Is there a simple way to craft a local web page so that it can display a variable passed to it in the URL? I would prefer to just use HTML and CSS, but adding a little inline javascript would be okay if absolutely needed.
As a simple example, when the extension calls something like:
folder/messageoutput.html?t=Text%20to%20display
I would like to see:
Message: Text to display
shown in the browser's viewport.
You can use the "search" property of the Location object to extract the variables from the end of your URL:
var a = window.location.search;
In your example, a will equal "?t=Text%20to%20display".
Next, you will want to strip the leading question mark from the beginning of the string. The if statement is just in case the browser doesn't include it in the search property:
var s = a.substr(0, 1);
if(s == "?"){s = substr(1);}
Just in case you get a URL with more than one variable, you may want to split the query string at ampersands to produce an array of name-value pair strings:
var R = s.split("&");
Next, split the name-value pair strings at the equal sign to separate the name from the value. Store the name as the key to an array, and the value as the array value corresponding to the key:
var L = R.length;
var NVP = new Array();
var temp = new Array();
for(var i = 0; i < L; i++){
temp = R[i].split("=");
NVP[temp[0]] = temp[1];
}
Almost done. Get the value with the name "t":
var t = NVP['t'];
Last, insert the variable text into the document. A simple example (that will need to be tweaked to match your document structure) is:
var containingDiv = document.getElementById("divToShowMessage");
var tn = document.createTextNode(t);
containingDiv.appendChild(tn);
getArg('t');
function getArg(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}

trying to get properties of objects inside object properties

Sometimes JavaScript is playing with me (although the deal was that I would be playing with it...) This test code below keeps resisting so I'm looking for a little help from more clever people around here.
Answering to a recent question I tried to create a readable list of all the color IDs useable in Google Advanced Calendar API.
The request is very simple : Calendar.Colors.get()
The response is an object with a couple of properties, each one being other objects with other properties.
I can go down to the second level but the last -and most useful in this case - level returns a disturbing "undefined" (see partial log below)
And that's my question...
code with comments :
function getColorList(){
var colors = Calendar.Colors.get();
//Logger.log(JSON.stringify(colors));
for(var cat in colors){
Logger.log("category "+cat+" = "+JSON.stringify(colors[cat])+'\n\n')
}
// from there I try the "event" category
var events = colors["event"];
Logger.log('object colors["event"] = '+ JSON.stringify(events))
// then I try to get every properties in this object
for(var val in events){
Logger.log("key "+val+" = "+JSON.stringify(events[val]))
}
}
Full log is viewable here (externalized to keep this reasonably short)
Looks like (key) may be indicating a read-only definition as Sandy was eluding to.
Just make your own object from colors to loop through after converting it to string:
var json = JSON.stringify(colors["event"]);
var myObj = JSON.parse(json);
for(var val in myObj){
Logger.log("key "+ val +" = "+JSON.stringify(myObj[val]))
}

Character encoding issue when using Google Apps Script to extract data from web page

I have written a script using Google Apps Script to extract text from a web page into Google Sheets. I only need this script to work with a specific web page, so it does not need to be versatile. The script works almost exactly as I want it to except that I have run into a character encoding problem. I am extracting both Hebrew and English text. The meta tag in the HTML has charset=Windows-1255. The English extracts perfectly, but the Hebrew displays as black diamonds containing a question mark.
I found this question that says to pass the data into a blob then use the getDataAsString method to convert to another encoding. I tried converting to different encodings and got different results. UTF-8 displays the black diamonds with question marks, UTF-16 displays Korean, ISO 8859-8 returns an error and says it's not a valid parameter, and the original Windows-1255 displays one Hebrew character but a bunch of other gibberish.
However, I am able to copy and paste the Hebrew text into Google Sheets manually and it displays correctly.
I have even tested passing Hebrew directly from Google Apps Script code like so:
function passHebrew() {
return "וַיְדַבֵּר";
}
This displays the Hebrew text properly on Google Sheets.
My code is as follows:
function parseText(book, chapter) {
//var bk = book;
//var ch = chapter;
var bk = '04'; //hard-coded for testing purposes
var ch = '01'; //hard-coded for testing purposes
var url = 'http://www.mechon-mamre.org/p/pt/pt' + bk + ch + '.htm';
var xml = UrlFetchApp.fetch(url).getContentText();
//I had to "fix" these xml errors for XmlService.parse(xml) below
//to function.
xml = xml.replace('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">');
xml = xml.replace('<LINK REL="stylesheet" HREF="p.css" TYPE="text/css">', '<LINK REL="stylesheet" HREF="p.css" TYPE="text/css"></LINK>');
xml = xml.replace('<meta http-equiv="Content-Type" content="text/html; charset=Windows-1255">', '<meta http-equiv="Content-Type" content="text/html; charset=Windows-1255"></meta>');
xml = xml.replace(/ALIGN=CENTER/gi, 'ALIGN="CENTER"');
xml = xml.replace(/<BR>/gi, '<BR></BR>');
xml = xml.replace(/class=h/gi, 'class="h"');
//This section is the specific route to the table in the page I want
var document = XmlService.parse(xml);
var body = document.getRootElement().getChildren("BODY");
var maintable = body[0].getChildren("TABLE");
var maintablechildren = maintable[0].getChildren();
//This creates a two-dimensional array so that I can store the Hebrew
//in the first column and the English in the second column
var array = new Array(maintablechildren.length);
for (var i = 0; i < maintablechildren.length; i++) {
array[i] = new Array(2);
}
//This is where the table gets parsed into the array
for (var i = 0; i < maintablechildren.length; i++) {
var verse = maintablechildren[i].getChildren();
//This is where the encoding problem occurs.
//I originally tried verse[0].getText() but it didn't work.
array[i][0] = Utilities.newBlob(verse[0].getText()).getDataAsString('UTF-8');
//This array receives the English text and works fine.
array[i][1] = verse[1].getText();
}
return array;
}
What am I overlooking, misunderstanding, or doing wrong? I don't have a very good understanding of how encoding works so I don't understand why converting it to UTF-8 isn't working.
Your problem occurs before the lines you've commented as an encoding problem: because the default encoding for UrlFetchApp is munging the unicode text from the start.
You should use the variation of the .getContentText() method that Returns the content of an HTTP response encoded as a string of the given charset. For your case:
var xml = UrlFetchApp.fetch(url).getContentText("Windows-1255");
That should be all you need to change, although the blob() work-around is no longer needed. (It's harmless, though.) Other comments:
The logical OR operator (||) is very helpful for setting default values. I've tweaked the first few lines to enable testing but still let the function operate normally with arguments.
The way you're setting up an empty array before populating it with strings is Bad JavaScript; it's complex code that isn't needed, so toss it. Instead, we'll declare the array Array, then push() rows onto it.
The .replace() functions can be reduced with more clever RegExp use; I've included the URLs for demos of the really tricky ones.
There were \n newline characters in the text which I guessed were unnecessary for your purposes, so added a replace() for them as well.
Here's what you're left with:
function parseText(book, chapter) {
var bk = book || '04'; //hard-coded for testing purposes
var ch = chapter || '01'; //hard-coded for testing purposes
var url = 'http://www.mechon-mamre.org/p/pt/pt' + bk + ch + '.htm';
var xml = UrlFetchApp.fetch(url).getContentText("Windows-1255");
//I had to "fix" these xml errors for XmlService.parse(xml) below
//to function.
xml = xml.replace(/(<!DOCTYPE.*EN")>/gi, '$1 "">')
.replace(/(<(LINK|meta).*>)/gi,'$1</$2>') // https://regex101.com/r/nH3pU8/1
.replace(/(<.*?=)([^"']*?)([ >])/gi,'$1"$2"$3') // https://regex101.com/r/eP7wO7/1
.replace(/<BR>/gi, '<BR/>')
.replace(/\n/g, '')
//This section is the specific route to the table in the page I want
var document = XmlService.parse(xml);
var body = document.getRootElement().getChildren("BODY");
var maintable = body[0].getChildren("TABLE");
var maintablechildren = maintable[0].getChildren();
//This is where the table gets parsed into the array
var array = [];
for (var i = 0; i < maintablechildren.length; i++) {
var verse = maintablechildren[i].getChildren();
//I originally tried verse[0].getText() but it didn't work.** It does now!
var hebrew = verse[0].getText();
//This array receives the English text and works fine.
var english = verse[1].getText();
array.push([hebrew,english]);
}
return array;
}
Results
[
[
"  וַיְדַבֵּר יְהוָה אֶל-מֹשֶׁה בְּמִדְבַּר סִינַי, בְּאֹהֶל מוֹעֵד:  בְּאֶחָד לַחֹדֶשׁ הַשֵּׁנִי בַּשָּׁנָה הַשֵּׁנִית, לְצֵאתָם מֵאֶרֶץ מִצְרַיִם--לֵאמֹר.",
" And the LORD spoke unto Moses in the wilderness of Sinai, in the tent of meeting, on the first day of the second month, in the second year after they were come out of the land of Egypt, saying:"
],
[
"  שְׂאוּ, אֶת-רֹאשׁ כָּל-עֲדַת בְּנֵי-יִשְׂרָאֵל, לְמִשְׁפְּחֹתָם, לְבֵית אֲבֹתָם--בְּמִסְפַּר שֵׁמוֹת, כָּל-זָכָר לְגֻלְגְּלֹתָם.",
" 'Take ye the sum of all the congregation of the children of Israel, by their families, by their fathers' houses, according to the number of names, every male, by their polls;"
],
[
"  מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה, כָּל-יֹצֵא צָבָא בְּיִשְׂרָאֵל--תִּפְקְדוּ אֹתָם לְצִבְאֹתָם, אַתָּה וְאַהֲרֹן.",
" from twenty years old and upward, all that are able to go forth to war in Israel: ye shall number them by their hosts, even thou and Aaron."
],
...

Issue with OAuth and Flickr - cannot request token

I am currently trying to request a token from Flickr to then be able to do some calls to their OAuth methods. I know I must be doing something wrong, for I get a reply that the signature is wrong, but honestly I followed their instructions (http://www.flickr.com/services/api/auth.oauth.html, http://www.flickr.com/services/api/auth.oauth.html#request_token, http://www.flickr.com/services/api/flickr.auth.oauth.getAccessToken.html) but I still get an error:
oauth_problem=signature_invalid&debug_sbs=GET&http%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Frequest_token&oauth_callback%3D%26oauth_consumer_key%3Da0f20d2c9b0a142848cffdf9d9a5ad78%26oauth_nonce%3DFCBB713F-581E-4BC6-42FF-C50252D839EC%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1330450158%26oauth_version%3D1.0
I don't get how to create that signature nor how to put it in the request, could anybody point me in the right direction? Thanks!
I am currently working with AS3, below is my code:
// request params
var now:Date = new Date();
var requestParams:Object = {};
requestParams.oauth_callback = ""; // there is no callback, it's a desktop application
requestParams.oauth_consumer_key = API_KEY;
requestParams.oauth_nonce = UIDUtil.getUID(now);
requestParams.oauth_timestamp = String(now.time).substring(0, 10);
requestParams.oauth_signature_method = "HMAC-SHA1";
requestParams.oauth_version = "1.0";
// create an array to sort param names alphabetically
// mandatory to create signature
var sortedRequestParamNames:Array = [];
var name:String;
for(name in requestParams)
{
sortedRequestParamNames.push(name);
}
sortedRequestParamNames.sort();
// create signature
// see http://www.flickr.com/services/api/auth.spec.html#signing
var oauthSignature:String = API_SECRET;
var i:uint;
var numParams:uint = sortedRequestParamNames.length;
var paramName:String;
for(i = 0; i < numParams; i++)
{
paramName = sortedRequestParamNames[i];
oauthSignature += paramName + convertToPercentEntities(requestParams[paramName]);
}
oauthSignature = MD5.hash(oauthSignature);
// build request
var tokenRequestString:String = REQUEST_TOKEN_URL;
for(i = 0; i < numParams; i++)
{
paramName = sortedRequestParamNames[i];
tokenRequestString += (i == 0) ? "?" : "&";
tokenRequestString += paramName + "=" + requestParams[paramName];
}
tokenRequestString += "&oauth_signature=" + oauthSignature;
var tokenRequest:URLRequest = new URLRequest(tokenRequestString);
tokenRequest.method = URLRequestMethod.GET;
// load request
initLoader();
_loader.addEventListener(Event.COMPLETE, requestTokenLoadedHandler);
_loader.load(tokenRequest);
Basically, you need to use the HMAC-SHA1 algorithm instead of an MD5. I'll walk you through it.
1. Create the signature base string
You seem to be doing that (but you are assigning it directly to the signature variable). Compiling the base string is done by concatenating three different parts.
Convert the HTTP Method to uppercase and set the base string equal to this value. Example: GET
Append the '&' character to the base string.
Percent encode the URL (without parameters) and append it to the base string. Example: http%3A%2F%2Fexample.com%2Frequest
Append the '&' character to the base string.
Percent encode the sorted parameter string and append it to the base string.
It should end up looking like this:
GET&http%3A%2F%2Fexample.com%2Frequest&a2%3Dr%2520b%26a3%3D2%2520q
%26a3%3Da%26b5%3D%253D%25253D%26c%2540%3D%26c2%3D%26oauth_consumer_
key%3D9djdj82h48djs9d2%26oauth_nonce%3D7d8f3e4a%26oauth_signature_m
ethod%3DHMAC-SHA1%26oauth_timestamp%3D137131201%26oauth_token%3Dkkk
9d7dh3k39sj
Now you're done with the signature base string. Lets move on to
2. Figuring out your signing key.
Your signing key is on this format: CONSUMER_SECRET + "&" + TOKEN_SECRET. But since you do not have a token yet, the signing key is the consumer secret and an ampersand. Like this: CONSUMER_SECRET + "&".
For all requests, except the first one your will have a token though, either a request token or an access token.
3. Combine the key and the base string using the HMAC-SHA1 algorithm.
I have used http://code.google.com/p/as3crypto/ when signing with AS3. You can even test its HMAC-SHA1 algorithm on this demo page: http://crypto.hurlant.com/demo/.
Use the base string as input, and the signing key as key to the HMAC-SHA1 algorithm.
The output of the HMAC-SHA1 algorithme will be a binary string which needs to be base64 encoded to produce the final signature. It should look something like this:
NYIQGEwIomgCuVOIA28pMDMID78=
This should be send with the request as the oauth_signature parameter.
I had problem with it too, ended up using FlickrNet API.
http://flickrnet.codeplex.com/

Extracting links and twitter replies from a string

I am getting a string from Twitter into my Actionscript which is a unformatted string. I want to be able to extract any links and or any #replies from the string, then display it in htmlText.
So far I have this
var txt:String = "This is just some text http://www.thisisawebsite.com and some more text via #sumTwitter";
var twitterText:String = txt.slice(txt.indexOf("#"),txt.indexOf(" ",txt.indexOf("#")));
var urlText:String = txt.slice(txt.indexOf("http"),txt.indexOf(" ",txt.indexOf("http")));
var newURL:String = ""+urlText+"";
var arr:Array = txt.split(urlText);
var newString:String = arr[0] + newURL + arr[1];
var txtField:TextField = new TextField();
txtField.width = 500;
txtField.htmlText = newString;
addChild(txtField);
This is fine for extracting links, which finish with a space. But what if, like the #sumTwitter, it finishes at the end of the string. And also what if there are multiple links or #'s, is the best way to put it in a while loop?
Regular expressions are the best option for what you want, I think.
Check Grant Skinner's RegExr. You could write and test your own RegExp there, which is very convenient. But you also can find a lot of useful ready-to-use regexps created by different users. Check out the "community" tab in the right panel. There, search by some meaningful keywords like "twitter" and "url" and you'll get a good number of options.
For example,
Grab urls:
http://regexr.com?2s5m4
Capture twitter usernames:
http://regexr.com?2s5m7