Linq2Twitter not returning results - linq-to-twitter

having some trouble with Linq2Twitter v3.0.2. After the line where I call SingleOrDefault it hangs indefinitely. If you need more information let me know. Thanks in advance for your help.
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore()
{
ConsumerKey = MyConsumerKey,
ConsumerSecret = MyConsumerSecret,
AccessToken = MyAccessToken,
AccessTokenSecret = MyAccessTokenSecret
}
};
var twtrContext = new TwitterContext(auth);
var results =
from search in twtrContext.Search
where search.Type == SearchType.Search &&
search.Query == "Obama" &&
search.Count == 10
select search.Statuses;
var tweets = results.SingleOrDefault();

LINQ to Twitter v3.0 is async. You should change your query like this:
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore()
{
ConsumerKey = MyConsumerKey,
ConsumerSecret = MyConsumerSecret,
AccessToken = MyAccessToken,
AccessTokenSecret = MyAccessTokenSecret
}
};
var twtrContext = new TwitterContext(auth);
var searchResponse =
await
(from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == "Obama" &&
search.Count == 10
select search)
.SingleOrDefaultAsync();

Related

Correct order in for loop using Parse

I want to create a array containing objects, and I'm using Parse to query all the data.
However, the for loop which loops over the results doesn't does that in the correct order but randomly loops over the data. If I log i each iteration, the logs show different results every time.
Here is my code:
for (var i = 0; i < results.length; i++)
{
Parse.Cloud.useMasterKey();
// retrieve params
var objectid = results[i];
var self = request.params.userid;
// start query
var Payment = Parse.Object.extend("Payments");
var query = new Parse.Query(Payment);
query.get(objectid, {
success: function (payment) {
// get all the correct variables
var from_user_id = payment.get("from_user_id");
var to_user_id = payment.get("to_user_id");
var amount = payment.get("amount");
var createdAt = payment.updatedAt;
var note = payment.get("note");
var img = payment.get("photo");
var location = payment.get("location");
var status = payment.get("status");
var fromquery = new Parse.Query(Parse.User);
fromquery.get(from_user_id, {
success: function(userObject) {
var fromusername = userObject.get("name");
var currency = userObject.get("currency");
var toquery = new Parse.Query(Parse.User);
toquery.get(to_user_id, {
success: function(touser)
{
var tousername = touser.get("name");
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
},
error: function(touser, error)
{
var tousername = to_user_id;
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
}
});
function sendArray(tousername) {
var array = new Array();
// create the time and date
var day = createdAt.getDate();
var year = createdAt.getFullYear();
var month = createdAt.getMonth();
var hour = createdAt.getHours();
var minutes = createdAt.getMinutes();
// create the timestamp
var time = "" + hour + ":" + minutes;
var date = "" + day + " " + month + " " + year;
var associativeArray = {};
if(self == from_user_id)
{
fromusername = "self";
}
if(self == to_user_id)
{
tousername = "self";
}
associativeArray["from"] = fromusername;
associativeArray["to"] = tousername;
associativeArray["amount"] = amount;
associativeArray["currency"] = currency;
associativeArray["date"] = date;
associativeArray["time"] = time;
associativeArray["status"] = status;
if(note == "" || note == null)
{
associativeArray["note"] = null;
}
else
{
associativeArray["note"] = note;
}
if(img == "" || img == null)
{
associativeArray["img"] = null;
}
else
{
associativeArray["img"] = img;
}
if(location == "" || location == null)
{
associativeArray["location"] = null;
}
else
{
associativeArray["location"] = location;
}
array[i] = associativeArray;
if((i + 1) == results.length)
{
response.success(array);
}
},
error: function(userObject, error)
{
response.error(106);
}
});
},
error: function(payment, error) {
response.error(125);
}
});
}
But the i var is always set to seven, so the associative arrays are appended at array[7] instead of the correct i (like 1,2,3,4,5)
The reason that this is so important is because I want to order the payment chronologically (which I have done in the query providing the results).
What can I do to solve this issue?
Success is a callback that happens at a later point in time. So what happens is, the for loop runs 7 times and calls parse 7 times. Then after it has run each of parse success calls will be executed, they look at i which is now at 7.
A simple way to fix this is to wrap the whole thing in an immediate function and create a new closure for i. Something like this
for(var i = 0; i < results.length; i++){
function(iClosure) {
//rest of code goes here, replace i's with iClosure
}(i);
}
Now what will happen is that each success function will have access to it's own iClosure variable and they will be set to the value of i at the point they were created in the loop.

How can I Make Use of Only One Function with My Weather App

In my weather app, I need to get the user location, which I'm getting from ipinfo.io, so that's one http request, and then I make another http request to another api on openweathermap.org. My question is how can I improve my code. Is it possible to make only one http request function and use it for calling both api by passing different parameters. Notice that I do set a number of variables inside each function which are particular to that function. I don't think it is possible to use these variables outside the scope of the function.
Here's my index.js
/*
Weather App Javascript code
author: George Louis
date: 3/11/2018
purpose: get local weather
*/
window.onload = function() {
//variables
var ipUrl = "https://ipinfo.io/json";
var appid = "appid=8e1880f460a20463565be25bc573bdc6";
var location = document.getElementById("location");
var currentDate = new Date();
var dayNight = "day";
//setting the date
var dateElem = document.getElementById("date");
var strDate = currentDate.toString();
dateElem.innerHTML = strDate.substring(0, strDate.length-18)
//calling ipinfo.io/json function
httpReqIpAsync(ipUrl);
//request to ipinfo.io/json
function httpReqIpAsync(url, callback) {
var httpReqIp = new XMLHttpRequest();
httpReqIp.open("GET", url, true)
httpReqIp.onreadystatechange = function() {
if(httpReqIp.readyState == 4 && httpReqIp.status == 200) {
var jsonIp = JSON.parse(httpReqIp.responseText)
var ip = jsonIp.ip;
var city = jsonIp.city;
var country = jsonIp.country;
location.innerHTML = `${city}, ${country}`;
var lat = jsonIp.loc.split(",")[0];
var lon = jsonIp.loc.split(",")[1];
console.log(lat+" "+lon)
var weatherApi = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&${appid}`;
//calling openweathermap api function
httpReqWeatherAsync(weatherApi);
}
}
httpReqIp.send();
}
//request to openweathermap.com json
function httpReqWeatherAsync(url, callback) {
var httpReqWeather = new XMLHttpRequest();
httpReqWeather.open("GET", url, true);
httpReqWeather.onreadystatechange = function() {
if(httpReqWeather.readyState == 4 && httpReqWeather.status == 200) {
var jsonWeather = JSON.parse(httpReqWeather.responseText);
console.log(jsonWeather)
var weatherDesc = jsonWeather.weather[0].description;
var id = jsonWeather.weather[0].id;
var icon = `<i class="wi wi-owm-${id}"></i>`
var temperature = jsonWeather.main.temp;
var tempFaren = Math.round(1.8 * (temperature - 273) + 32)
// console.log(tempFaren)
var humidity = jsonWeather.main.humidity;
var windSpeed = jsonWeather.wind.speed;
//converting visibility to miles
var visibility = Math.round(jsonWeather.visibility / 1000);
// console.log(visibility)
//find whether is day or night
var sunSet = jsonWeather.sys.sunset;
//sunset is 10 digits and currentDate 13 so div by 1000
var timeNow = Math.round(currentDate / 1000);
console.log(timeNow + "<" + sunSet +" = "+(timeNow < sunSet))
dayNight = (timeNow < sunSet) ? "day" : "night";
//insert into html page
var description = document.getElementById("description");
description.innerHTML = `<i id="icon-desc" class="wi wi-owm-${dayNight}-${id}"></i><p>${weatherDesc}</p>`;
var tempElement = document.getElementById("temperature");
tempElement.innerHTML = `${tempFaren}<i id="icon-thermometer" class="wi wi-thermometer"></i>` ;
var humidityElem = document.getElementById("humidity");
humidityElem.innerHTML = `${humidity}%`;
var windElem = document.getElementById("wind");
windElem.innerHTML = `${windSpeed}m/h`;
var visibilityElem = document.getElementById("visibility");
visibilityElem.innerHTML = `${visibility} miles`;
}
}
httpReqWeather.send();
}
}
You can use the modern way to request with fetch instead, if you like. You can also take advantage of destructuring. This is what I would do:
function httpReqIpAsync(url, callback) {
fetch(url)
.then(response => response.json())
.then(jsonIp => {
const { ip, city, country } = jsonIp;
location.textContent = `${city}, ${country}`;
const [lat, lon] = jsonIp.loc.split(",");
const weatherApi = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&${appid}`;
return [weatherApi, callback];
})
.then(httpReqWeatherAsync)
}
//request to openweathermap.com json
function httpReqWeatherAsync([url, callback]) {
// ...
Since each request is separate, I think it makes much more sense for them to be in separate functions, rather than consolidating them together.

Shedulig service invokation in nifi

I have one GenerateFlowFile processor where I have 2 attributes userId(equals=1) and parameter (equals=5) , I have service which should give me repsonse for each userId from(1 to 5) so i need to call it 5 times ,what i want is to genreate 5 flowfile in execute script to invoke service 5 times with related id I have tried this code below but it doesn't work for me could you give me any advice what should i do ?
var OutputStreamCallback = Java.type("org.apache.nifi.processor.io.OutputStreamCallback");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
Date.prototype.isValid = function ()
{
return (Object.prototype.toString.call(this) === "[object Date]") && !isNaN(this.getTime());
};
var flowFile = session.get();
if (flowFile != null)
var userId= flowFile.getAttribute('userId') //equals 1
var parameter=flowFile.getAttribute('parameter')//equals5
var i=0;
while(parameter<i) {
var flowFile = session.get();
if (flowFile != null)
flowFile = session.putAttribute(flowFile, 'filename', userId + '_' + parameter);
flowFile = session.write(flowFile,
new OutputStreamCallback(function (outputStream) {
outputStream.write(0)
}));
session.transfer(flowFile, REL_SUCCESS)
userId++;
parameter--;
i++;
}
var OutputStreamCallback = Java.type("org.apache.nifi.processor.io.OutputStreamCallback");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
Date.prototype.isValid = function ()
{
return (Object.prototype.toString.call(this) === "[object Date]") && !isNaN(this.getTime());
};
var flowFile=session.get()
if (flowFile != null) {
var userId = flowFile.getAttribute('userId')
var parameter = flowFile.getAttribute('parameter')
var i = 0;
for(i=0;i<=parameter;i++) {
var flowfile1=session.create();
userId++;
flowfile1 = session.putAttribute(flowfile1, 'filename', userId);
flowfile1 = session.write(flowfile1,
new OutputStreamCallback(function (outputStream) {
outputStream.write(0)
}));
session.transfer(flowfile1, REL_SUCCESS)
parameter--;
}
session.remove(flowFile)
}

Trello API - connect cards with boards to get board name based on the board id

So I got all the cards from all the lists, inside all my boards:
var url3 = "https://api.trello.com/1/lists/"+listId+"/cards?key="+key+"&token="+token;
Now I need to join somehow with the boards list and get the board name of each card, based on the board ids, and I don't know how...
This is my entire function, trying to get all the cards with a due date, but I also want to get the name of the board each card is in...
function getDues(listId){
var xmlhttp3 = new XMLHttpRequest();
var url3 = "https://api.trello.com/1/lists/"+listId+"/cards?key="+key+"&token="+token;
xmlhttp3.onreadystatechange = function() {
if(xmlhttp3.readyState == 4 && xmlhttp3.status == 200) {
var arrCards = JSON.parse(xmlhttp3.responseText);
var dueName = "";
var dueDate = "";
var board = "";
for(c = 0; c < arrCards.length; c++){
if(arrCards[c].due !== null){
var dueName = arrCards[c].name;
var dueDate = arrCards[c].due;
var boardNo = arrCards[c].idBoard;
var date = new Date(dueDate);
var deadline = "";
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var now = new Date();
var result = "https://api.trello.com/1/organizations/"+orgId+"/boards?key="+key+"&token="+token;
for (card in arrCards) {
if (!arrCards.hasOwnProperty(card)) { continue; }
var name = result.name;
card.boardName = name
console.log(card.boardName);
}
}
}
}
}
xmlhttp3.open("GET", url3, true);
xmlhttp3.send();
}
All I get in for board name is "undefined".
Update
Changed the way I got the cards, and like this it works:
function getDues(boardId) {
var xmlhttp3 = new XMLHttpRequest();
var url3 = "https://api.trello.com/1/boards/"+boardId+"/cards?key="+key+"&token="+token;
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState === 4 && xmlhttp3.status === 200) {
var arrCards = JSON.parse(xmlhttp3.responseText);
var dueName = "";
var dueDate = "";
var board = "";
for (var c = 0; c < arrCards.length; c++) {
if (arrCards[c].due !== null) {
var dueName = arrCards[c].name; // due card name
var dueDate = arrCards[c].due; // due date
var boardNo = arrCards[c].idBoard; // board id
var date = new Date(dueDate);
var deadline = "";
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var now = new Date();
var xmlhttpBoardName = new XMLHttpRequest();
var boardNameUrl = "https://api.trello.com/1/boards/" + boardNo + "/?key=" + key + "&token=" + token;
xmlhttpBoardName.onreadystatechange = function() {
if (xmlhttpBoardName.readyState === 4 && xmlhttpBoardName.status === 200) {
var board = JSON.parse(xmlhttpBoardName.responseText);
var boardName = board.name; // board name
}
}
xmlhttpBoardName.open("GET", boardNameUrl, true);
xmlhttpBoardName.send();
}
}
}
}
xmlhttp3.open("GET", url3, true);
xmlhttp3.send();
}
Basing on your code, something like this should work:
function getDues(listId) {
var xmlhttp3 = new XMLHttpRequest();
var url3 = "https://api.trello.com/1/lists/"+listId+"/cards?key="+key+"&token="+token;
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState === 4 && xmlhttp3.status === 200) {
var arrCards = JSON.parse(xmlhttp3.responseText);
var dueName = "";
var dueDate = "";
var board = "";
for (var c = 0; c < arrCards.length; c++) {
if (arrCards[c].due !== null) {
var dueName = arrCards[c].name;
var dueDate = arrCards[c].due;
var boardNo = arrCards[c].idBoard;
var date = new Date(dueDate);
var deadline = "";
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var now = new Date();
var xmlhttpBoardName = new XMLHttpRequest();
var boardNameUrl = "https://api.trello.com/1/boards/" + boardNo + "/?key=" + key + "&token=" + token;
xmlhttpBoardName.onreadystatechange = function() {
if (xmlhttpBoardName.readyState === 4 && xmlhttpBoardName.status === 200) {
var board = JSON.parse(xmlhttpBoardName.responseText);
var boardName = board.name; // HERE YOU HAVE YOUR BOARD NAME
console.log(boardName);
}
}
xmlhttpBoardName.open("GET", boardNameUrl, true);
xmlhttpBoardName.send();
}
}
}
}
xmlhttp3.open("GET", url3, true);
xmlhttp3.send();
}
Anyway, I suggest you to use the official library, you do not have to take care of all the http requests.

Can't get values from Backendless table on javascript

I have the table "Products" with full fields. I try to find and get values with some condition. This is javascript file
var APPLICATION_ID = "id",
SECRET_KEY = "key",
VERSION = "v1";
Backendless.initApp(APPLICATION_ID, SECRET_KEY, VERSION);
function Products(args) {
args = args || {};
this.id_user = args.id_user || "";
this.cal = args.cal || null;
this.id_day = args.id_day || null;
this.id_product = args.id_product || null;
this.nameProduct = args.nameProduct || "";
}
var productStorage = Backendless.Persistence.of( Products );
var query = {
condition : "id_day = 33"
}
function get(){
try{
var product = productStorage.find(query).data;
}catch( e )
{
if( e.code != 1009 )
alert(e.message);
}
return [];
}
var array = get();
alert(array[0]);
in alert message i get just "undefined". And also there are no problems in catch block in the function "get()".
Right now you're always returning an empty array, even if your query finds a product - an empty array has nothing in index '0', therefore you get 'undefined'.
Try adding
return product;
to get(), right after you query for it.
Debugging will be easier with console.log instead of alert - you'll need to open your browser's javascript console to see it:
console.log(array)
If you do choose to use alert, converting the value to JSON can help:
alert(JSON.stringify(array));
Thanks to Backendless team, they helped me to solve this. So my code :
var APP_ID = "id",
SECRET_KEY = "key",
VERSION = "v1";
function Products(args) {
args = args || {};
this.id_user = args.id_user || "";
this.cal = args.cal || null;
this.id_day = args.id_day || null;
this.id_product = args.id_product || null;
this.nameProduct = args.nameProduct || "";
}
var dataQuery = {
condition: "id_day = 33"
};
function fetchingFirstPageAsync(){
var products = Backendless.Persistence.of(Products).find(dataQuery);
for(var i = 0; i < products.data.length; i++) {
console.log("Product name = " + products.data[i].nameProduct);
}
}
Backendless.initApp( APP_ID, SECRET_KEY, VERSION );
fetchingFirstPageAsync();

Resources