Category Archives: dev

How to create a MEAN+ stack application (MongoDB, Express, Angular, Node + Bootstrap, Jade)

Steps

      Create a Node.js with Express.js App
      Create a Git repository and clone to localhost
      Add Angular.js
      Add Bootstrap
      Add MongoDb
      Add Jade
      Add an API for GET /people
      Connect to MongoDb
      Create a sortable table with Angular

Create a Node.js with Express.js App

I will be using Bluemix to host, build and deploy my Node.js application and the MongoDb service. I am developing on my localhost for unit testing before I upload my application to Bluemix, but you can also use the online editor and online Git instead.

1. If you do not have a Bluemix account yet, sign up for a free account at http://ibm.biz/bluemixnyc,
2. Once you have an account, go to your Bluemix console at https://console.ng.bluemix.net/,
3. Go to your Dashboard,
4. In the ‘Cloud Foundry Apps’ box, click ‘CREATE APP’,

5. Choose ‘WEB’

Continue reading

Print Friendly, PDF & Email

Calling a Watson service in Java

Overview

Note: this API needs to be updated to v2. Identify is now a resource on the Language Translation API.
http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/language-translation/api/v2/

Making an HTTP REST API POST request in Java is in principle as simple this:
Request request = Request.Post(serviceURI)
.addHeader("Authorization", basicAuthorization)
.bodyString(body, ContentType.APPLICATION_FORM_URLENCODED);
Executor executor = Executor.newInstance();
String response = executor.execute(request).returnContent().asString();

This code, uses the Apache Fluent API, which exposes only the essentials of the Apache HTTPClient.

The Authorization header is required for authentication by the Watson API, and is a base64 encoded string.
String auth = username + ":" + password;
String basicAuthorization = "Basic "+ Base64.encodeBase64String(auth.getBytes());

The POST request is “x-www-form-urlencoded” and in Java consists of a List<NameValuePair>:
List<NameValuePair> params = new ArrayList<NameValuePair>();

Continue reading

Print Friendly, PDF & Email

Call IBM Watson APIs to add Machine Learning to your App

You can easily add very cool IBM Watson APIs to your application. You need to sign up for Bluemix, create an application and bind APIs or services to the app. This will create credentials (username and password) for each API or service.

Create a Bluemix acccount

First if you have not signed up for a Bluemix account yet, go to http://ibm.biz/bluemixnyc and Sign Up.

Create an App

Once you have confirmed your account, go to the Catalog and choose any Runtime. We will only use the runtime to bind services to, which will give us API credentials. For example, name the app ‘my-app1’.

Add a Service

Now, to add Services either go to Catalog > Services, and add a service to your app, or go to your app’s admin page. Bluemix is based on Cloud Foundry, so apps in Bluemix are listed under ‘CF Apps.’ Go to Dashboard > CF Apps > ‘my-app1’, and click the ‘Add a Service or API.’ I will add Personality Insights to my app in this example. Edit the required fields and click the Create button. Bluemix might ask you to restage your app. Now we’re ready to call the Personality Insights API.

Call the Watson API

To make a REST call to a Watson API, you must add an Authorization header with a Base64 encoded “Basic :” string. To generate the Basic Authorization header, use the colon as a separator for username and password and Base64 encode the Authorization string.

String username = "username from your service credentials";
String password = "password from your service credentials";
String s = username + ":" + password;
byte[] b = s.getBytes();
String enc = Base64.encodeBase64String(b);
String authorization = "Basic "+enc;

To call the API with the above credentials use the following curl statement from command line.

curl -X POST -H "Authorization: Basic BzAvEATz4UYqKfU5JA66GSIwKNgdATGiADR8YiWaOSH2Purd6tedhKUJaPa3KLshLq==" -H "Content-Type: text/plain" -H "Accept: application/json" -H "Accept-Language: en" -H "headers: true" -d 'put your text here' https://gateway.watsonplatform.net/personality-insights/api/v2/profile

For the API reference details go here
http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/#!/personality-insights/profile

This curl command will return a response object that you can visualize with the Visualize Personality Insights API.
http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/#!/personality-insights/visualize

Print Friendly, PDF & Email

Send a multipart/form-data request in PHP

GET

To List your current indexes with ‘standard’ flavor use a GET request to the List Indexes API.


$url_listindexes = 'https://api.idolondemand.com/1/api/sync/listindexes/v1';
$params1 = 'flavor=standard&apikey='.$apikey;
$response = file_get_contents($url_listindexes .'?'.$params1);
if($response) { $json = json_decode($response); if($json){ $indexes = $json->index; } return $indexes; }

POST

POST multipart/form-data with native PHP


function send_multipart_post_message($sync_or_async, $json1){
$url = "https://api.idolondemand.com/1/api/".$sync_or_async."/addtotextindex/v1";
// using WordPress custom functions to retrieve index and apikey
$index1 = wp_idolondemand_get_setting('index');
$apikey = wp_idolondemand_get_setting('apikey');
$eol = "\r\n";
$data = '';
$mime_boundary=md5(time());
//
$data .= '--' . $mime_boundary . $eol;
$data .= 'Content-Disposition: form-data; name="apikey"' . $eol . $eol;
$data .= $apikey . $eol;
$data .= '--' . $mime_boundary . $eol;
$data .= 'Content-Disposition: form-data; name="index"' . $eol . $eol;
$data .= $index1 . $eol;
$data .= '--' . $mime_boundary . $eol;
$data .= 'Content-Disposition: form-data; name="json"; filename="allposts.json"' . $eol;
$data .= 'Content-Type: application/json' . $eol;
$data .= 'Content-Transfer-Encoding: base64' . $eol . $eol;
$data .= base64_encode($json1) . $eol;
// alternatively use 8bit encoding
//$data .= 'Content-Transfer-Encoding: 8bit' . $eol . $eol;
//$data .= $json1 . $eol;
$data .= "--" . $mime_boundary . "--" . $eol . $eol;
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: multipart/form-data; boundary=' . $mime_boundary,
'content' => $data
//'proxy' => 'tcp://localhost:8888' //use with Charles to catch http traffic
));
$ctx = stream_context_create($params);
$response = file_get_contents($url, FILE_TEXT, $ctx);
return $response;
}

Continue reading

Print Friendly, PDF & Email

[JavaScript] Find Related Concepts as D3js Bubble Chart

The Find Related Concepts API from IDOL OnDemand returns the most relevant terms and concepts from related documents. Here’s represented as a D3 Bubble Chart. Thanks to incredibly good work by Mike Bostock. For a description of the API go here https://www.idolondemand.com/developer/apis/findrelatedconcepts#overview
For D3 Data-Driven Documents go here: http://d3js.org

Print Friendly, PDF & Email

[JavaScript] POST upload file with XHR FormData

This example uses the Optical Character Recognition (OCR) API from IDOL OnDemand. For details see here: https://www.idolondemand.com/developer/apis/ocrdocument#overview

Print Friendly, PDF & Email

HTML5 and JavaScript: Flip an Image using HTML5 Canvas

See the working code example on jsfiddle.


<!DOCTYPE html>
<html>
<head>
<title>Flipping an Image Horizontally and Vertically</title>
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
var imageurl = null;
//
$(document).ready( function() {
$('#loadimage').click(function() {
urlProvided();
});
$('#mirrorh').click(function() {
mirror(1,0);
});
$('#mirrorv').click(function() {
mirror(0,1);
});
});
//
function urlProvided() {
var userinput = document.getElementById('imageurl');
imageurl = userinput.value;
loadImage();
}
function loadImage(){
//
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//
var img = new Image();
img.src = imageurl;
img.onload = function(){
ctx.drawImage(img,0,0);
};
//
var w = img.width;
var h = img.height;
canvas.width = w;
canvas.height = h;
}
//
function mirror(mirrorh,mirrorv){
//
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
//
var img = new Image();
img.src = imageurl;
//
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
//
var w = img.width;
var h = img.height;
if(mirrorh){
ctx.scale(1, -1);
ctx.translate(0, -h);
}
if(mirrorv){
ctx.scale(-1, 1);
ctx.translate(-w,0);
}
ctx.drawImage(img,0,0,img.width,img.height,null,null,w,h);
ctx.save();
}
</script>
</head>
<body>
<div>
Your image URL: <input type="text" id="imageurl"></input><button id="loadimage">load image</button>
</div>
<div>
<button id="mirrorh">mirrorh</button>
<button id="mirrorv">mirrorv</button>
</div>
<div>
<canvas id="canvas"></canvas>
</div>
</body>
</html>

Print Friendly, PDF & Email

CSharp: POST Request to Query API and JSON Parsing

Use the System.Net.WebClient object to make a POST request in C#. For parsing JSON, you can use Json.NET by James Newton-King. Install both packages using the NuGet Package Manager. This code example posts a search for the text ‘Dog’ to the Query API. This example uses the text parameter, if you want to use the file parameter to upload a document as a search parameter you will need to use multipart/form content type, with for instance RestSharp client for .NET.


string apiKey = "your-apikey";
string iodURL = "https://api.idolondemand.com/1/api/sync/query/v1";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["apikey"] = apiKey;
formData["text"] = "Dog";
byte[] responseBytes = webClient.UploadValues(iodURL, "POST", formData);
webClient.Dispose();
UTF8Encoding enc = new UTF8Encoding();
string json = enc.GetString(responseBytes);
//Debug.WriteLine(json);

The JSON response is serialized using Json.NET into .NET Objects representing the JSON response as a DocumentList of Document type.


DocumentList documentList = JsonConvert.DeserializeObject(json);
List docs = documentList.Documents;
//
public class DocumentList
{
[JsonProperty("documents")]
public List Documents { get; set; }
}
public class Document
{
[JsonProperty("reference")]
public string Reference { get; set; }
[JsonProperty("weight")]
public double Weight { get; set; }
[JsonProperty("links")]
public List Links { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("content")]
public Object Content { get; set; }
}

The above code will parse the JSON response from IDOL OnDemand.


{
"documents" : [{
"content" : { },
"index" : "news_eng",
"links" : [ "DOG" ],
"reference" : "http://feeds.theguardian.com/c/34708/f/663840/s/3605393d/sc/38/l/0L0Stheguardian0N0Cchildrens0Ebooks0Esite0C20A140Cjan0C170Creview0Etom0Ewatson0Estick0Edog0Ewants0Ea0Ehot0Edog/story01.htm",
"title" : "Stick Dog Wants a Hot Dog by Tom Watson - review",
"weight" : 89.5
},{
"content" : { },
"index" : "news_eng",
"links" : [ "DOG" ],
"reference" : "http://feeds.theguardian.com/c/34708/f/663879/s/37621ce9/sc/38/l/0L0Stheguardian0N0Ccommentisfree0C20A140Cfeb0C210Cdog0Eattacks0Eon0Echildren0Etragic0Etriggers/story01.htm",
"title" : "Dog attacks on children are tragic – but we can try to understand the triggers | Deborah Orr",
"weight" : 88.010000000000005
}
]}

Access the properties as normal:


foreach (Document doc in docs)
{
Debug.WriteLine("doc.reference: " + doc.Reference);
}

To do a multipart/form-data POST request, the simplest way is to use a client like RestSharp, which you can install via NuGet:


string apiKey = @"your-apikey";
string iodURL = @"https://api.idolondemand.com/1/api/sync/query/v1";
string file = @"C:\Users\user1\Documents\iod\TheSecretSpiritualHistoryOfCalculus_ScientificAmerican.pdf";
var client = new RestClient(iodURL);
var request = new RestRequest("", Method.POST);
request.AddParameter("apikey", apiKey);
request.AddFile("file", file);
RestResponse response = (RestResponse) client.Execute(request);
string content = response.Content;
Debug.WriteLine("status: "+ response.StatusCode + ", content: " + content);

Brian Grinstead wrote a great article on a Multipart form post in C# implementation, for those who are interested.

Print Friendly, PDF & Email

Arduino: TMP36 temperature sensor

The TMP36 temperature sensor is an easy to use temperature sensor. With a few lines of code you can measure the temperature with reasonable accuracy.
tmp36

int sensorPin = A0;
float celsius;
float kelvin;
float fahrenheit;
void getTemperature()
{
float val = analogRead(sensorPin);
// analogRead returns a 0 to 5 volts measure on a scale from 0 to 1023,
// i.e. 2*10 bits or 1024 units
val = (val * 5.0) / 1024;
// convert Volts to milliVolts
// the TMP36's linear scale is 10 mV / degree Celsius
// i.e. (* 1000 / 10) = * 100
val = (val) * 100;
celsius = val;
kelvin = val + 273.15;
fahrenheit = ((val * 9)/5.0) + 32;
}

tmp36_temperature_sensor_with_arduino_uno_R3

Print Friendly, PDF & Email

Cordova: Install or Update Cordova on Windows with Visual Studio

To install Apache Cordova on Windows and to use it with Visual Studio 2010 Express for Windows Phone, follow these steps:

  1. Get the source code for the latest version from the Cordova project page or for older versions go to the Cordova distribution archive.
  2. Unzip the source archive cordova-3.4.0-src.zip.
    C:/>unzip cordova-3.4.0-src.zip
  3. Locate the file cordova-wp8.zip in the extracted directory, and unzip the archive.
    C:/>cd cordova-3.4.0
    C:/cordova-3.4.0>unzip cordova-wp8.zip
  4. Change directory to cordova-wp8 and run the createTemplates.bat script.
    C:/cordova-3.4.0>cd cordova-wp8
    C:/cordova-3.4.0/cordova-wp8>createTemplates.bat
  5. Copy the generated template files CordovaWP7_3_4_0.zip and CordovaWP8_3_4_0.zip to the Visual Studio Templates directory in the users My Documents folder ~/Document
    s\Visual Studio 2010\Templates\ProjectTemplates.
    C:\cordova-3.4.0\cordova-wp8>copy CordovaWP8_3_4_0.zip "C:\Users\user1\Document
    s\Visual Studio 2010\Templates\ProjectTemplates"

Now, start Visual Studio 2010 Express for Windows Phone, and in the File menu, select New Project…. In the Installed Templates select the Cordova template you just copied.

To add Cordova plugins on Windows with Visual Studio, go here.

Print Friendly, PDF & Email