loop axois get in react - java

I am trying an api and I am trying to collect multiple questions with equal distribution.
here is what I have tried so far:
import React from "react"
import axios from "axios";
export default function App() {
const numberOfQuestions = 15;
const typesOfQuestions = [{id:12}, {id:13}, {id:14}, {id:17}];
const divide = numberOfQuestions / typesOfQuestions.length;
let remaining = numberOfQuestions % typesOfQuestions.length;
let newArr = [];
newArr = typesOfQuestions.map(async category => {
await axios.get(`https://opentdb.com/api.php?amount=${(divide + remaining)}&type=multiple&category=${category.id}`)
.then(res => {
return (newArr.push(res.data.results));
})
remaining = 0;
})
console.log(newArr);
}
an example of a working api
https://opentdb.com/api.php?amount=2&type=multiple&category=12
output:
{"response_code":0,"results":[{"category":"Entertainment: Music","type":"multiple","difficulty":"easy","question":"Who is the frontman of the band 30 Seconds to Mars?","correct_answer":"Jared Leto","incorrect_answers":["Gerard Way","Matthew Bellamy","Mike Shinoda"]},{"category":"Entertainment: Music","type":"multiple","difficulty":"easy","question":"Which 80s band is fronted by singer\/guitarist Robert Smith?","correct_answer":"The Cure","incorrect_answers":["The Smiths","Echo & the Bunnymen","New Order"]}]}

Related

calling rest API(locally running) from nodejs failed

We created a rest API on python and it is locally running. And the 'http://127.0.0.1:5002/business' API is showing contents {"business name": "something"} if I open it on google chrome. However, when we call this API in nodejs, it always gives me the error. But if I use another API(exactly same code but different api in nodejs), it is working.
async function get_recommend_initial(){
//https://ViolaS.api.stdlib.com/InitialRecommendation#dev/
// // agent.add('providing recommendations...');
const options = {
method: 'GET'
,uri: 'http://127.0.0.1:5002/business'
// ,uri:'https://ViolaS.api.stdlib.com/InitialRecommendation#dev/'
// ,json: true
};
// return request(options).then(response => {
// console.log(response)
// return (response)
// }).catch(function (err) {
// console.log('No recommend data');
// console.log(err);
// });
return requestAPI(options).then(function(data)
{
let initial_recommendation = JSON.parse(data);
console.log(initial_recommendation);
//return initial_recommendation.information[0].name;
}).catch(function (err) {
console.log('No recommend data');
console.log(err);
});
}
1
The API that is created by python file which is running locally. You can see the API code figure by moving your mouth above 1. Thanks!!!
The python code is as follows:
app = Flask(__name__)
#Add resources to be much cleaner
api = Api(app)
features = {}
class Business(Resource):
def get(self):
return {'business name': 'something'} # Fetches first column that is Employee ID
def post(self):
some_json = request.get_json()
print(some_json)
countNumber = features.get('count',0) + 1
features['count'] = countNumber
return {'You sent': some_json,
'Count:':countNumber}, 201
def put(self):
some_json = request.get_json()
print(some_json)
#record the count number
countNumber = features.get('count',0) + 1
features['count'] = countNumber
features['ok'] = 'yes'
return {'You sent': some_json,
'Count:':countNumber,
'Ok:': features['ok']}, 201
api.add_resource(Business, '/business') # Route_1
if __name__ == '__main__':
app.run(port='5002')
The error is as following:
dialogflowFirebaseFulfillment
Error: Unknown response type: "undefined" at WebhookClient.addResponse_ (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:277:13) at WebhookClient.add (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:245:12) at Sys_Recommend (/srv/index.js:31:11) at <anonymous>
And the log is:
No recommend data

Looking for a Play Framework pagination example

I'm looking for a Play Framework pagination example. Please help me with a good reference link.
I searched for it and don't have java code.
I'll provide a Scala solution and you can adjust your code.
You could create a utility class called Paginator:
package util
case class Paginator[A](items: Seq[A], page: Int, offset: Long, total: Long) {
lazy private val pageSize: Int = 20 // you can adjust to your preference
lazy val prevPage: Option[Int] = Option(page - 1).filter(_ >= 0)
lazy val nextPage: Option[Int] = Option(page + 1).filter(_ => (offset + items.size) < total)
lazy val numberOfPages: Float = if (total % pageSize > 0) { total / pageSize + 1 }
else { total / pageSize }
}
In your controller you will do something like:
def list(currentPage: Int) = Action.async { implicit request =>
val offset: Int = currentPage * resultsPerPage
// Put your logic here to get the `listOfItems` you want to display
// and the number of `totalItems`
// and then return Ok and call your view
Ok(views.html.list(Paginator(listOfItems, currentPage, offset, totalItems)))
}
and finally in your view you will have something like:
#import util.Paginator
#(paginatedList: Paginator[Item])(implicit msg: play.api.i18n.MessagesProvider)
#main(msg.messages("label.list_of_items")) {
<h1>#msg.messages("label.paginated_list")</h1>
#* populate your list here *#
#* and this is your paginator *#
<div class="pagination">
#paginatedList.prevPage.map { page =>
<a href="#link(page)">#msg.messages("label.previous")<a>
}.get
#for(pageNumber <- 1 to paginatedList.numberOfPages.toInt) {
#pageNumber
}
#paginatedList.nextPage.map { page =>
#msg.messages("label.next")
}.get
</div>
}
I got the original idea from this project and I've expanded on it. You can also improve the paginator by using getOrElse to provide alternative/disabled links when being on the first/last page, or to disable the current page number etc.
I hope this helps.

youtube.subscriptions.list (api v3) - nextPageToken isn't available

I'm trying to get all channels from my subscriptions. But the "nextPageToken" isn't available.
The response should containing "nextPageToken":
(from developers.google.com - YouTube (v3) - Subscriptions: list)
{
"kind": "youtube#subscriptionListResponse",
"etag": etag,
"nextPageToken": string,
"prevPageToken": string,
"pageInfo": {
"totalResults": integer,
"resultsPerPage": integer
},
"items": [
subscription Resource
]
}
This is my request:
GET https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&maxResults=10&mine=true&key={YOUR_API_KEY}
APIs Explorer - YouTube (v3) - Subscriptions.list:
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.subscriptions.list?part=snippet&maxResults=10&mine=true
My response:
{
"kind": "youtube#subscriptionListResponse",
"etag": "\"XXXXX/XXXXX\"",
"pageInfo": {
"totalResults": 115,
"resultsPerPage": 10
},
"items": [
...
Can you tell me why the nextPageToken is missing, please?
I have now a workaround for this.
Please tell me if that helps.
The tokens seems to be the same for each page of other API Youtube V3 API calls, so I can use it to fetch all pages of subscriptions I need.
tokens = ['CDIQAA','CGQQAA','CJYBEAA','CMgBEAA','CPoBEAA','CKwCEAA','CN4CEAA','CJADEAA','CMIDEAA','CPQDEAA','CKYEEAA', ...]
You can use ANOTHER Youtube API to get more page tokens if you need more. Just fetch 1 element a time and log the tokens to use in this API.
I just need to known when to stop... so I checked when API calls returned no channels!
#retry(stop_max_attempt_number=7)
def get_subscription_page(self, channel_id, pageToken):
print 'Retrieving subscription page using Youtube API (token: %s)' % pageToken
res = self.youtube_data_api.subscriptions().list(part="id,snippet,contentDetails",channelId=channel_id, maxResults=50, pageToken=pageToken).execute()
return res
def get_subscriptions(self, channel_id):
self.authorize(channel_id)
subs = []
# Tokens to deal with api bug...
# https://code.google.com/p/gdata-issues/issues/detail?id=7163
tokens = ['CDIQAA','CGQQAA','CJYBEAA','CMgBEAA','CPoBEAA','CKwCEAA','CN4CEAA','CJADEAA','CMIDEAA','CPQDEAA','CKYEEAA']
iPage = 0
pageToken = ''
while True:
res = self.get_subscription_page(channel_id, pageToken)
channelIds = []
for channel in res['items']: channelIds.append(channel.get('snippet').get('resourceId').get('channelId'))
pageToken = res.get('nextPageToken')
# If no next page token is returned... it might be caused by a bug.
# This workaroud will only have effect when the bug still lives.
if not pageToken:
if not channelIds:
# Workaroud for this: https://code.google.com/p/gdata-issues/issues/detail?id=7163
print ' (Workaround due to API bug) No channels returned in this API call! Finished!'
break
else:
pageToken = tokens[iPage]
# get channel info for each channel ID
channelsInfo = self.get_channel_info(channelIds)
subs += channelsInfo
print ' Itens already retrieved: %d ' % len(subs)
iPage += 1
if args.debug: break
if pageToken: continue
print 'No more pages to retrieve!'
break
return subs
Here is a JS snippet I came up with to generate pageTokens up to at least 1024, I cannot guarantee that it will produce anything valid beyond that as i could not find any service which will get me tokens for offsets > 450 to validate my guesses and assumptions.
var d0 = "AEIMQUYcgkosw048";
var d1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var d2 = d1;
var d1c = 0;
var d2c = 0;
var overflowSuffix = "Q";
var direction = "AA";
var d2OverflowCounter = 0;
var pageSize = 50;
for (i = 0; i < 1024; i++) {
if (i % pageSize == 0) console.log("C" + d1.charAt((d1c / d0.length) % d1.length) + d0.charAt(i % d0.length) + overflowSuffix + direction, ":", i);
if (++d1c % (1 << 8) == 0) d1c = 1 << 7;
if (++d2c % (1 << 7) == 0) overflowSuffix = d2.charAt(++d2OverflowCounter) + "E";
}
(check developer tools / console to see generated codes)
I have a script that runs each hour based on this Youtube API V3 and it stopped to work 4 hours ago. The nextPageToken is not available anymore. Before, it was available exactly like in the first code you posted.

How to run javascript function periodically when the Apache tomcat server is starts instead of java class using ScheduledExecutorService?

I need to run my javascript function periodically on server starts. i dont know how to write the equivalent Java code as my javaScript function contains multiple ajax call and mathematical equations.
below is my javascript code which i need to run periodically on server start.
<script type="text/javascript">
$(document).ready(function(){
var polyLat = new Array();
polyLat[0] = 10.194027;
polyLat[1] = 10.226975;
polyLat[2] = 10.059987;
polyLat[3] = 10.002248;
polyLat[4] = 9.854925;
polyLat[5] = 9.835443;
polyLat[6] = 9.899107;
polyLat[7] = 9.993088;
polyLat[8] = 10.081425;
polyLat[9] = 9.992266;
polyLat[10] = 10.194027;//First point repeated to close polygon
var polySides = (polyLat.length)-1;//number of points in polygon
//vertical Longitude coordinates of polygon
var polyLng = new Array();
polyLng[0] = 76.201205;
polyLng[1] = 76.375022;
polyLng[2] = 76.775730;
polyLng[3] = 76.778940;
polyLng[4] = 76.584336;
polyLng[5] = 76.411473;
polyLng[6] = 76.368070;
polyLng[7] = 76.397007;
polyLng[8] = 76.317492;
polyLng[9] = 76.267905;
polyLng[10] = 76.201205;//First point repeated to close polygon
//Coordinates for bounding box
var maxLat = Math.max.apply(null,polyLat);
var minLat = Math.min.apply(null,polyLat);
var maxLng = Math.max.apply(null,polyLng);
var minLng = Math.min.apply(null,polyLng);
$.post('outboundupd.jsp',
{
mx_lat:maxLat,
mn_lat:minLat,
mx_lng:maxLng,
mn_lng:minLng,
ply_sds:polySides
},
function(response,status,xhr)
{
// alert(response.trim());
plotdata(response);
});
function plotdata(response)
{
var x;
var y;
var mob;
var jsonArray=JSON.parse(response.trim());
var jalen= jsonArray.length;
for(i=0;i<jalen;i++)
{
var obj=jsonArray[i];
pcode= obj.Pcode;
nplate= obj.N_plate;
driver= obj.Driver;
mob= obj.MobileNu;
x= obj.Latitude;
y= obj.Longitude;
time= obj.Time;
}
var j = polySides-1 ;
oddNodes = 0;
for (i=0; i<polySides; i++) {
if (polyLng[i]<y && polyLng[j]>=y || polyLng[j]<y && polyLng[i]>=y) {
if (polyLat[i]+(y-polyLng[i])/(polyLng[j]-polyLng[i])*(polyLat[j]-polyLat[i])<x) {
oddNodes=!oddNodes;
}
}
j=i; }
if(oddNodes!=true)
{
// alert("ob mobile:"+mob);
$.post('obsouth.jsp',
{
pcd:pcode,
npt:nplate,
drv:driver,
mobl:mob,
lat:x,
lon:y,
tm:time
},
function(response,status,xhr)
{
alert(response.trim());
});
}
return oddNodes;
}
});
</script>
My question:-
Is there any technique to call a javascript function from a java class extended with runnables or directly implement the exact javascript in java class?
If answer for 1 is no, can you please guide me to convert my entire javascript to Java code?
Any piece of code is highly appreciated and thanks in advance.
Use node.js and execute your script using Runtime.exec(). you would run node on this or you can go for Rhino scripting engine to envoke methods in .js file from within a java class. Hope that helped.

Get remote data sorted with grand total in jQuery using Java

I am using jQuery for UI and my programming language is Java. Now I want to get remote data using an Ajax call to Java servlet and get the records from remote site in sorted order with also grand total. How can I do that?
I found many examples, but that was in PHP only. I want to implement it in Java, and I am not able to understand PHP.
Example which I found is as below.
JavaScript code
jQuery("#48remote2").jqGrid({
url:'server.php?q=2',
datatype: "json",
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:55, editable:true, sorttype:'int',summaryType:'count', summaryTpl : '({0}) total'},
{name:'invdate',index:'invdate', width:90, sorttype:'date', formatter:'date', datefmt:'d/m/Y'},
{name:'name',index:'name', width:100},
{name:'amount',index:'amount', width:80, align:"right", sorttype:'number',formatter:'number',summaryType:'sum'},
{name:'tax',index:'tax', width:80, align:"right",sorttype:'number',formatter:'number',summaryType:'sum'},
{name:'total',index:'total', width:80,align:"right",sorttype:'number',formatter:'number', summaryType:'sum'},
{name:'note',index:'note', width:150, sortable:false,editable:true}
],
rowNum:10,
rowList:[10,20,30],
height: 'auto',
pager: '#p48remote2',
sortname: 'invdate',
viewrecords: true,
sortorder: "desc",
caption:"Grouping with remote data",
grouping: true,
groupingView : {
groupField : ['name'],
groupColumnShow : [true],
groupText : ['<b>{0}</b>'],
groupCollapse : false,
groupOrder: ['asc'],
groupSummary : [true],
groupDataSorted : true
},
footerrow: true,
userDataOnFooter: true
});
jQuery("#48remote2").jqGrid('navGrid','#p48remote',{add:false,edit:false,del:false});
And PHP code is as below,
PHP MySQL code
examp = $_REQUEST["q"]; //Query number
$page = $_REQUEST['page']; // Get the requested page
$limit = $_REQUEST['rows']; // Get how many rows we want to have into the grid
$sidx = $_REQUEST['sidx']; // Get index row - i.e. user click to sort
$sord = $_REQUEST['sord']; // Get the direction
if(!$sidx) $sidx =1;
...
$result = mysql_query("SELECT COUNT(*) AS count FROM invheader a, clients b WHERE a.client_id=b.client_id".$wh);
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
}
else {
$total_pages = 0;
}
if ($page > $total_pages)
$page=$total_pages;
$start = $limit*$page - $limit; // Do not put $limit*($page - 1)
if ($start<0)
$start = 0;
$SQL = "SELECT a.id, a.invdate, b.name, a.amount,a.tax,a.total,a.note FROM invheader a, clients b WHERE a.client_id=b.client_id".$wh." ORDER BY ".$sidx." ".$sord. " LIMIT ".$start." , ".$limit;
$result = mysql_query( $SQL ) or die("Could not execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0; $amttot=0; $taxtot=0; $total=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$amttot += $row[amount];
$taxtot += $row[tax];
$total += $row[total];
$responce->rows[$i]['id']=$row[id];
$responce->rows[$i]['cell']=array($row[id],$row[invdate],$row[name],$row[amount],$row[tax],$row[total],$row[note]);
$i++;
}
$responce->userdata['amount'] = $amttot;
$responce->userdata['tax'] = $taxtot;
$responce->userdata['total'] = $total;
$responce->userdata['name'] = 'Totals:';
echo json_encode($responce);
But I am not able to understand the code in PHP. How can I do that?
If I understand you correct you need include summary line in the bottom of the grid. To do this you don't need the grouping part from the posted example. The only parameters which are important in your case are:
footerrow: true,
userDataOnFooter: true
If you use both from the jqGrid options you need just calculate the sum for the columns where you need it has and include "userdata" part in the JSON which produce the servlet. See here, here and here for more information.

Categories