Watson language identification - ibm-watson

I had implemented the following curl code using RESTSharp to find the language of sentence "What is your name?".
I followed the "Identify language" under : http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/language-translation/api/v2/#identify
string source = "What is your name?";
string credentials;
string auth = string.Format("{0}:{1}", tuid, tpwd);
string auth64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
credentials = string.Format("{0} {1}", "Basic", auth64);
var langDet = new RestClient(detURL);
var requestDet = new RestRequest("?text={authToken}",Method.POST);
requestDet.Credentials = new NetworkCredential(tuid, tpwd);
requestDet.AddParameter("text", source, ParameterType.UrlSegment);
IRestResponse responseDet = langDet.Execute(requestDet);
However, when this code is executed I get a list of languages and confidence level while I still am not sure how to accurately specify which language the above sentence goes to. Please help me where I am wrong.
My detUrl variable above is: https://gateway.watsonplatform.net/language-translation/api/v2/identify

you can get what you want using the Alchemy API, which is also available in Bluemix. Here's an example using Java + Watson SDK
AlchemyLanguage service = new AlchemyLanguage();
service.setApiKey("XXXXXXXXX");
Map<String,Object> params = new HashMap<String, Object>();
params.put(AlchemyLanguage.TEXT, "What is your name?");
Language language = service.getLanguage(params);
System.out.println(language);
I use this Java SDK above, but there's a .NET port for it here
https://github.com/dennyboy/WatsonCSharp

Thank you !
I found the answer.
(1) In my code above, I have been passing the {authtoken} instead of the string I had wanted to send (string source in example below
var requestDet = new RestRequest("?text=" + source, Method.POST);
(2) Once done, I had to deserialize the output from "responseDet" and filter the first value (as below). I had used Jsonconvert class.
DataSet data = JsonConvert.DeserializeObject<DataSet>(responseDet.Content);
return data.Tables[0].Rows[0][0].ToString();
My code is working fine. Thanks for your help !

Related

How to get an array from appsettings.json file in .Net 6?

I've read this excellent SO post on how to get access to the appsettings.json file in a .Net 6 console app.
However, in my json file I have several arrays:
"logFilePaths": [
"\\\\server1\\c$\\folderA\\Logs\\file1.log",
"\\\\server2\\c$\\folderZ\\Logs\\file1A1.log",
"\\\\server3\\c$\\folderY\\Logs\\file122.log",
"\\\\server4\\c$\\folderABC\\Logs\\fileAB67.log"
],
And I get the results if I do something like this:
var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true);
var config = builder.Build();
string logFile1 = config["logFilePaths:0"];
string logFile2 = config["logFilePaths:1"];
string logFile3 = config["logFilePaths:2"];
But I don't want to have to code what is effectively an array into separate lines of code, as shown.
I want to do this:
string[] logFiles = config["logFilePaths"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
But it gives me an error on config["logFilePaths"] saying it's null.
Why would that be null?
To access the logFilePaths as an array, you want to use the Get<T> extension method:
string[] logFilePaths = config.GetSection("logFilePaths").Get<string[]>();
One option is to install Microsoft.Extensions.Configuration.Binder nuget and use Bind (do not forget to setup CopyToOutputDirectory for appsettings.json):
var list = new List<string>();
config.Bind("logFilePaths", list);
Another - via GetSection (using the same nuget to bind a collection):
var list = config.GetSection("logFilePaths").Get<List<string>>();

How to make a directory on iphone using codenameone?

This sounds like a ridiculous question but I cannot for the life of me make a directory on ios using codenameone. Has anyone done it ? Here is what I try (some dumb tests some not so dumb, im getting desperate here):
FileSystemStorage fs = FileSystemStorage.getInstance();
fs.mkdir("ZZZTESTA");
fs.mkdir("ZZZTESTB");
String testpath = fs.getAppHomePath()+"/xxxtesta";
fs.mkdir(testpath);
String testpathb = fs.getAppHomePath()+"xxxtestb";
fs.mkdir(testpathb);
String testpathC = fs.getAppHomePath()+"xxxtest/";
fs.mkdir(testpathC);
String nativetest = fs.toNativePath(testpathb);
fs.mkdir(nativetest);
String nativetestb = fs.toNativePath(testpathC);
fs.mkdir(nativetestb);
I have done all kinds of experiments but ALWAYS I get : Failed to create directory xxxxx.. I will fly to your location and shower you with gifts if you can help :)
These would work:
String testpathb = fs.getAppHomePath()+"xxxtestb";
fs.mkdir(testpathb);
String testpathC = fs.getAppHomePath()+"xxxtest/";
fs.mkdir(testpathC);

Tone analyser only returns analysis for 1 sentence

When using tone analyser, I am only able to retrieve 1 result. For example, if I use the following input text.
string m_StringToAnalyse = "The World Rocks ! I Love Everything !! Bananas are awesome! Old King Cole was a merry old soul!";
The results only return the analysis for document level and sentence_id = 0, ie. "The World Rocks !". The analysis for the next 3 sentences are not returned.
Any idea what I am doing wrong or am I missing out anything? This is the case when running the provided sample code as well.
string m_StringToAnalyse = "This service enables people to discover and understand, and revise the impact of tone in their content. It uses linguistic analysis to detect and interpret emotional, social, and language cues found in text.";
Running Tone analysis using the sample code on the sample sentence provided above also return results for the document and the first sentence only.
I have tried with versions "2016-02-19" as well as "2017-03-15" with same results.
I believe that if you want sentence by sentence analysis you need to send every separate sentence as a JSON object. It will then return analysis in an array where id=SENTENCE_NUM.
Here is an example of one I did using multiple YouTube comments (using Python):
def get_comments(video):
#Get the comments from the Youtube API using requests
url = 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=100&videoId='+ video +'&key=' + youtube_credentials['api_key']
r = requests.get(url)
comment_dict = list()
# for item in comments, add an object to the list with the text of the comment
for item in r.json()['items']:
the_comment = {"text": item['snippet']['topLevelComment']['snippet']['textOriginal']}
comment_dict.append(the_comment)
# return the list as JSON to the sentiment_analysis function
return json.dumps(comment_dict)
def sentiment_analysis(words):
# Load Watson Credentials using Python SDK
tone_analyzer = ToneAnalyzerV3(
username=watson_credentials['username'], password=watson_credentials['password'], version='2016-02-11')
# Get the tone, based on the JSON object that is passed to sentiment_analysis
return_sentiment = json.dumps(tone_analyzer.tone(text=words), indent=2)
return_sentiment = json.loads(return_sentiment)
Afterwards you can do whatever you want with the JSON object. I would also like to note for anyone else looking at this if you want to do an analysis of many objects, you can add sentences=False in the tone_analyzer.tone function.

Why does this get method stop returning correctly?

I am trying to write an app engine application for my university. What I am trying to achieve right now, is to create a method which takes in a Course name, and returns a list of all the CourseYears (think of that as being like a link table e.g. if Maths is the course, and it has Year 1, year 2 and Year 3; MathsYear1, MathsYear2 and MathsYear3 would be the names of the CourseYears).
This is the code for the module (WARING: super dirty code below!):
#ApiMethod(name = "courseYears")
public ArrayList<CourseYear> courseYears(#Named("name") String name){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query.Filter keyFilter = new Query.FilterPredicate("name", Query.FilterOperator.EQUAL, name);
Query query = new Query("Course").setFilter(keyFilter);
PreparedQuery preparedQuery = datastore.prepare(query);
List<Entity> resultList = preparedQuery.asList(FetchOptions.Builder.withLimit(1));
Course course = ofy().load().type(Course.class).id(resultList.get(0).getKey().getId()).now();
ArrayList<String> courseYearNames = course.getAllCourseYearNames();
System.out.println(course.getName());
ArrayList<CourseYear> courseYears = new ArrayList<CourseYear>();
for(String courseYearName: courseYearNames){
Query.Filter courseNameFilter = new Query.FilterPredicate("name", Query.FilterOperator.EQUAL, courseYearName);
Query query2 = new Query("CourseYear").setFilter(courseNameFilter);
List<Entity> resL = preparedQuery.asList(FetchOptions.Builder.withLimit(1));
System.out.println("test");
CourseYear courseYear = ofy().load().type(CourseYear.class).id(resL.get(0).getKey().getId()).now();
courseYears.add(courseYear);
}
return courseYears;
}
It basically takes a Course name in, applies a filter on all courses to get the corresponding Course object, and then calls getAllCourseYearNames() on the course to get an array list containing all its CourseYears' names. (I would have loved to do this using Keys, but parameterised Objectify keys don't seem to be supported in this version of App Engine).
I then try and get the CourseYears by looping through the arraylist of names and applying the filter for each name. I print "test" each time to see how many times it is looping. Like I said, a super dirty way of doing it.
When I try passing a few course names as a parameters, it loops the correct number of times only once or twice, and after that does not loop at all (doesn't print "test"). I could understand if it never looped, but not doing it correctly once or twice and then never again. It doesn't successfully return a list of CourseYears when it does work, but rather the relevant number of NULLs - I don't know if this is relevant. I believe it successfully retrieves the course every time, as I print the name of the course after loading and it never fails to do this.
If anyone has ANY suggestions for why this may be happening, I would be incredibly grateful to hear them!
Thanks
query2 is never used in your code. You reuse preparedQuery from your previous query, which runs on a different entity kind.

RIA Services - Silverlight 4.0 - Accessing entities from code

I have strange situation I have simple project to test RIA functionality in Silverlight 4.0.
When I use data source for Domain Service it works great but when I want to access Context from code and execute simple query I returns 0 rows.
//test One with query provided to DataSource
var q = ctx.GetDoctorsWithPatientsAndHospitalQuery();
var result = ctx.Load(q);
//test Two using EntityQuery
EntityQuery<Doctor> query =
from c in ctx.GetDoctorsWithPatientsAndHospitalQuery()
select c;
LoadOperation<Doctor> loadOp = this.ctx.Load(query);
var result2 = loadOp.Entities;
//test Three using only entity and Linq
var result3 = ctx.Doctors.ToList();
Strange is also that when I want to add new entity instance from code it works great.
Doctor newDoctor = new Doctor()
{
FirstName = firstNameTextBoxNew.Text,
LastName = lastNameTextBoxNew.Text,
Hospital_Id = tmp,
Hospital = tmpH
};
ctx.Doctors.Add(newDoctor);
ctx.SubmitChanges();
Can anyone could point me what I have done wrong to execute select from code?
Regards,
Daniel SkowroĊ„ski
Calling "LoadOperation loadOp = this.ctx.Load(query);" from code is an async operation so you are basically checking the result before it completes.
If you want to see the results, you need to provide a callback, to the Load() method, that will execute after the data is loaded.
Data sources for domain services handle async updates, so keep propagating changes as and when load operations complete.
Your "save" works as it does not wait around for the result. You are manually checking the database afterwards. Not checking it in code.
Hope this helps.
As a quick check, try this (breakpoint on the "result2 =" line). Your loadOp is redundant in this example, but I did not want to change your code too much:
LoadOperation<Doctor> loadOp = this.ctx.Load(query, loadOperation =>
{
var result2 = loadOp.Entities;
}, null);
**Note: for those that want to edit this code... Please don't. I wanted to retain the flavour of the asker's code. loadOp and loadOperation point to the same object and result2 was the asker's choice of variable name.*

Resources