Successful consumption of a Azure Machine Learning API? - ruby-on-rails

Does anyone have good documentation of a successful implementation of the Azure ML studio API in a web app that's not ASP.net? I'd like to run on it with ruby on rails, but I guess I have to figure it out on my own.

It is simply a rest API call. Look at this...
data = {
"Inputs": {
"input1":
{
"ColumnNames": ["YearBuild", "City", "State", "HomeType", "TaxAssesmentYear", "LotSize", "HomeSize", "NumBedrooms"],
"Values": [ [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], ]
}, },
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/45aeb4d8283d4be6ae211592f5366af5/services/07ffeeb6fcb84f16bc62cdcf67fd95b3/execute?api-version=2.0&details=true'
api_key = 'abc123' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
Give a shot at trying with the postman app in chrome first. Setting your headers, just as above, your data goes in the post payload in the json format.

Here you'll find Ruby code (not python)
data = {
'Inputs' => {
'input1' => [
{
'weekday' => 1,
'hour' => 2,
'events' => 0
}
]
},
'GlobalParameters' => {}
}
body = data.to_json
url = 'https://asiasoutheast.services.azureml.net/subscriptions/[tour stuff...]execute?api-version=2.0&format=swagger'
api_key = '[your api key]'
headers = {'Content-Type': 'application/json', 'Authorization': ('Bearer '+ api_key)}
RestClient::Request.execute(method: :post, url: url, payload: body, headers: headers)

Related

POST with more than one "body"

This is my code to make the call, a POST. Until now I only needed to send one product in each post.
But, I wanted to start sending my list of products in just one POST.
Future DadosPagamento() async {
await Future.delayed(const Duration(milliseconds: 200));
var headers = {'Authorization': 'Bearer Gns2DfakHnjd9id', 'Content-Type': 'application/json'};
var request = http.Request(
'POST', Uri.parse('http://appdnz.ddns/APP1/Products'));
request.body = json.encode(
[
{
"OrderState": "",
"LineID": "1",
"ClientID": idCliente,
"ProductReference": ref,
"Color": color,
"Size": size,
"Quantity": quantity,
"UnitPriceWithoutTax": precoSemTax,
"ShippingAmount": envioPreco,
"OrderReference": "",
"CarrierID": idTrans,
"Comments": comentario,
"ProductDescription": descricaoProd,
"ShippingName": envioNome,
},
],
);
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}
example of what i want to send
request.body = json.encode(
[
{
"Lineid" = "1",
"Reference"= "xpto",
"Quantity"= "1"
....
}
,
{
"Lineid" = "2",
"Reference" = "xpto2",
"Quantity" = "5"
...
}
,
{
"Lineid" = "3",
"Reference" = "xpto3",
"Quantity" = "6"
...
}
]
)
In the research I did, I realized that it might work if I create a list and put it in json.encode(list), I don't know if it's the best way or if there aren't any more ways.
Thanks

I am trying to add forwarding rule to the user's mailbox but it is not working asexpected

I am using graph API to add message rule which is forward a mail from user's inbox. Rule is getting added but mails are not forwarding to specified id.
Here are some details:
var data = {
"displayName": "From partner",
"sequence": 1,
"isEnabled": true,
"conditions": {
"isAutomaticForward": true
},
"actions": {
"forwardTo": [
{
"emailAddress": {
"name": "recipient name ",
"address": "email address"
}
}
],
"stopProcessingRules": true
}
}
axios.post("https://graph.microsoft.com/v1.0/users/{userId}/mailFolders/inbox/messageRules", data,
{
headers: {
"Authorization": "Bearer " + access_token
}
}
)
.then(response => {
console.log(response.data)
})
.catch(err => {
console.log(err.response)
})
Response is as expected but mails are not forwarding.
I tried the above payload, steps and it works for me!!
(1) Create a new rule using Graph API
POST https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messageRules
Content-type: application/json
{
"displayName": "From partner",
"sequence": 2,
"isAutomaticForward": true,
"actions": {
"forwardTo": [
{
"emailAddress": {
"name": "Alex Wilbur",
"address": "AlexW#contoso.onmicrosoft.com"
}
}
],
"stopProcessingRules": true
}
}
(2) Test whether the rule is working or not.
Result: It's working as expected
(3) Check that the above rule shows or not (as part of Outlook.office.com or Outlook UI's rule section)
Adding a snapshot that i captured from Outlook.office.com, mailbox settings!!

Telegram (simplest) inline bot send photo 2 times on iOS

I have an inline bot similar to #pic and it works ok, when I type query word I can see pictures appear so I can choose one and send to a chat. The problem is when I do - 2 copies of same result are sent. This happens only on iOS client. On Android, PC and other platforms only one picture is being sent. I have checked all logs (the bot is done in Node.js) and for every request I have a single response. It seems to be a iOS client bug, although #pic bot works fine. Has someone encountered this bug or have an idea of what can cause it?
Example of answerInlineQuery response object
{
"inline_query_id": "817150058382989968",
"results": [
{
"type": "photo",
"id": "se090",
"photo_url": "http://www.shadowera.com/secardbot361/se090.jpg",
"thumb_url": "http://www.shadowera.com/secardbot361/se090.jpg",
"photo_width": 344,
"photo_height": 480,
"title": "Tracking Gear",
"description": "You can view the hands of opposing players.",
"caption": "king"
},
{...
UPDATE:
So I have created a simplest possible inline bot in node.js #iosinlinebot (you can try it) AND you have the same exact behaviour: only on iOS devices you will send 2 images to the chat once tapped on the result.
Here is the code:
exports.handler = function(event, context) {
console.log(event);
const https = require("https");
let answer = {
inline_query_id: event.inline_query.id,
results: [{
type: "photo",
id: "abcd",
photo_url: "https://lh3.googleusercontent.com/jVXglyWWL5J2y1vRN-7Jy3_ozvvZc4w5486IAkbAIrWcNN_vn7YuIvhc1JDtGq43BqGl=s180",
thumb_url: "https://lh3.googleusercontent.com/jVXglyWWL5J2y1vRN-7Jy3_ozvvZc4w5486IAkbAIrWcNN_vn7YuIvhc1JDtGq43BqGl=s180",
photo_width: 180,
photo_height: 180,
title: "title",
description: "description",
caption: "test"
}],
cache_time:1
};
let postBody = JSON.stringify(answer);
let options = {
hostname: "api.telegram.org",
port: 443,
path: "/bot" + process.env.TOKEN + "/answerInlineQuery",
method: "POST",
headers: {
'Content-Type': 'application/json',
'Content-Length': postBody.length
}
};
let postreq = https.request(options, (res) => {
res.setEncoding('utf8');
const body = [];
res.on('data', (chunk) => body.push(chunk));
res.on('end', () => {
let j = body.join('');
console.log(j);
//context.done(JSON.parse(j));
});
});
postreq.write(postBody);
postreq.end();
};
this is an event object (coming from telegram):
{
"update_id": 12345678,
"inline_query": {
"id": "123456789123456789",
"from": {
"id": 123456789,
"is_bot": false,
"first_name": "Firstname",
"username": "username",
"language_code": "it-IT"
},
"query": "test",
"offset": ""
}
}
UPDATE:
Thanks to Sedric Heidarizarei we were able to find the problem. It is a telegram iOS client bug. If InlineQueryResultPhoto object contains caption field, you user will post 2 images to the chat.
It is very important to close the Begin and the End of your regex with ^ and $.
For example a user with this regex /^[/]start/ can use start and start a and start b as Bot command And will allow Them to receive your photo, But with /^[/]start$/, The user must enter the exact /start Command.
1: Use This Module: node-telegram-bot-api
2: And Send Your Photo:
bot.onText(/^[/]start$/, (msg) => {
const opts = {
parse_mode: 'Markdown',
reply_markup: {
inline_keyboard: [[{
text: '🔙',
callback_data: 'back'
}]]
}
};
bot.sendPhoto(msg.chat.id, 'AgADBAADn64xBoABCx8L8trMV9eMqgDAAEC', opts); // Your Photo id
});
Notice:
Open an empty project and just use and check your InlineQueryResultPhoto.
update:
That is a Telegram bug for For temporary use, remove caption from your let answer ={}

proper syntax for generating JSON body in API call

With the following long controller action code
#available = Available.find(694)
#tareservation_id = 8943
#request_date_time = Time.now.utc.iso8601
#request_id = Time.now.to_i
#in_date = (Date.today + 24.days).strftime("%Y-%m-%d").to_s
#book = %Q|{
"booking": {
"currencyCode": "USD",
"languageCode": "es",
"paxNationality": "ES",
"clientRef": {
"value": \"#{#tareservation_id}\",
"mustBeUnique": true
},
"items": [
{
"itemNumber": 1,
"immediateConfirmationRequired": true,
"productCode": \"#{#available.product_code}\",
"leadPaxName":
{ "firstName": "Guy",
"lastName": "Test"
},
"product":
{
"period":
{
"start": "2018-08-27",
"quantity": 2
}
}
} ]
},
"requestAuditInfo":
{ "agentCode": "001",
"requestPassword": "pass",
"requestDateTime": \"#{#requestDateTime}\",
"requestID": #{#request_id} },
"versionNumber": "2.0"
}|
This then must be shipped off to the API as JSON in the body call
#result = HTTParty.post(
'https://test.com/search',
:body => JSON.parse(#book).to_json,
headers: {
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Connection' => 'Keep-Alive'
}
)
If the following block is removed:
,
"product":
{
"period":
{
"start": "2018-08-27",
"quantity": 2
}
}
in console JSON.parse(#start), parses properly. With the block JSON::ParserError: 784: unexpected token. Yet I fail to see what is incorrect here?
Is Rails handling of string for future JSON conversion really strict on syntax, particularly since there is interpretation of instance variables - both as strings and integers - and har returns involved? What would it be then? Or is there a safer solution to get out of what quickly becomes quicksand?
It turns out that pasting too many lines into the console (iTerm2, in this case) does something to the memory. 25 lines of code pasted in a single time is the maximum observered where behaviour is as expected.

Docusign integration with rails 4

I am using the docusign_rest gem for DocuSign REST API, and following are my DocuSign configuration.
# config/initializers/docusign_rest.rb
require 'docusign_rest'
DocusignRest.configure do |config|
config.username = 'myemail#email.com'
config.password = 'MyPassword'
config.integrator_key = 'My-key'
config.account_id = 'account_id'
config.endpoint = 'https://www.docusign.net/restapi'
config.api_version = 'v1'
end
When I try to connect and get account_id, I get nil as a response.
client = DocusignRest::Client.new
puts client.get_account_id # Returns nil.
I am using rails-4.1.4 and ruby-2.2.2
What did I miss? Please suggest.
Not sure if you figured this out or not quite yet. Here is another solution that wasn't too difficult using httparty. If you're trying to create a document for a template for example, your request might look like so:
baseUrl = "https://demo.docusign.net/restapi/v2/accounts/acct_number/envelopes"
#lease = Lease.find(lease.id)
#unit = #lease.unit
#application = #lease.application
#manager = #lease.property_manager
#application.applicants.each do |renter|
req = HTTParty.post(baseUrl,
body: {
"emailSubject": "DocuSign API call - Request Signature - Boom",
"templateId": "id of your template",
"templateRoles": [{
"name": "#{renter.background.legal_name}",
"email": "#{renter.email}",
"recipientId": "1",
"roleName": "Lessee",
"tabs": {
"texttabs": [{
"tablabel": "Rent",
"value": "#{#lease.rent}"
},{
"tablabel": "Address",
"value": "987 apple lane"
}]
}
},{
"email": "#{#manager.email}",
"name": "#{#manager.name}",
"roleName": "Lessor",
"tabs": {
"texttabs": [{
"tablabel": "Any",
"value": "#{#lease.labels}"
},{
"tablabel": "Address",
"value": "987 hoser lane"
}]
}
}],
"status": "sent"
}.to_json,
headers: {
"Content-Type" => "application/json",
'Accept' => 'application/json',
'X-DocuSign-Authentication' => '{
"Username" : "place your",
"Password" : "credentials",
"IntegratorKey" : "here"
}'
}, :debug_output => $stdout )
debug output on the final line is to allow you to debug the api request, it can be removed at any time.
This was a bug in docusign_rest 0.1.1; that method always returned nil. That bug has been fixed and the latest gem version includes that fix.

Resources