PostMan - Generate random number range and random future date - api

there are certain discussions on generating random stuff within a range on stack but none of them answer the actual question.
So task is the following
Need to generate a random number within a range, let's say from 1 to 13010, and put this number into the body. example
{
"userid": {{randomNumberFromRange}},
"date": "{{RandomDateInFuture}}"
}
the main requirement - this should work in POST request body. Any ideas?

In Pre-request:
pm.variables.set("randomNumberFromRange", _.random(1, 13010));
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
}
pm.variables.set("RandomDateInFuture", randomDate(new Date(), new Date(2030, 0, 1)));
Result:
{
"userid": 3538,
"date": "2023-07-19T22:17:13.379Z"
}
Reference: https://gist.github.com/miguelmota/5b67e03845d840c949c4

Related

Date format messed up while copying data from one spreadsheet to another using Google Sheets API batchUpdate

I am copying a dataset from one spreadsheet to another and all is fine except the dates.
In the source file the dates are like "2020-07-27", but after I run the script, the dates in the destination file are in completely different format like "Sun Jul 26 18:00:00 GMT-04:00 2020".
What should I do in order to copy the date as it is - YYYY-MM-DD?
My code:
function myFunction() {
var sheet_source_values = SpreadsheetApp.openById("1JfjXPPFj08p6cxjdsdcBhTMkl6yXLJkhASG0dv4").getSheetByName(Utilities.formatDate(now,"GMT+1", "dd.MM")).getRange('A:AD').getValues()
var sheet_destination = SpreadsheetApp.openById("GTjEfvjoTJ7U7ZXwYUEnSkKtfudXZuCP0dyq").getSheetByName("Updated_sheet")
var request = {
'responseValueRenderOption' : 'UNFORMATTED_VALUE',
'valueInputOption': 'RAW',
'responseDateTimeRenderOption' : 'SERIAL_NUMBER',
'data': [
{
'range': "'Updated_sheet'!" + sheet_destination.getRange(2,1,sheet_source_values.length,sheet_source_values[0].length).getA1Notation(),
'majorDimension': 'ROWS',
'values': sheet_source_values
}
]
};
Sheets.Spreadsheets.Values.batchUpdate(request, "GTjEfvjoTJ7U7ZXwYUEnSkKtfudXZuCP0dyq");
}
I tried changing "responseValueRenderOption" and "responseDateTimeRenderOption" but could find solution :(
The problem here is not with the Sheets API, but with the way you are retrieving the values from the source spreadsheet.
According to the getValues method documentation:
getValues - Returns a two-dimensional array of values, indexed by row, then by column. The values may be of type Number, Boolean, Date, or String, depending on the value of the cell.
In this way, the values will be retrieved as a Date type, but this type is the Google default one, hence the results you are getting on the destination sheet.
In order to fix this, I suggest you use getDisplayValues instead as this will return the displayed values from the source sheet. As for the Sheets API request, you can simply keep the 'valueInputOption': 'RAW' option only.
Modified sheet_source_values
var sheet_source_values = SpreadsheetApp.openById("1bGCXCUe6cgyLQRUQrOIAT2BruBH95ybAX7iG_pyk4Q0").getSheetByName("Sheet1").getRange('A1:A4').getDisplayValues();
Modified Sheets API request
var request = {
'valueInputOption': 'RAW',
'data': [{
'range': "'Updated_sheet'!" + sheet_destination.getRange(2, 1, sheet_source_values.length, sheet_source_values[0].length).getA1Notation(),
'majorDimension': 'ROWS',
'values': sheet_source_values
}]
};
Reference
Google Apps Script Range Class - getDisplayValues();
Google Apps Script Range Class - getValues().

DataTables convert incoming epoch date to dd/mm/yyyy

I am using an AJAX call with datatables to populate a table. The format of the incoming data is:
{
"name": "John Doe",
"date":1244231200500
}
I can see that date formatting is discussed here: https://datatables.net/blog/2014-12-18 but there's no clear instructions for epoch data conversion.
What I want to do is put something (like within the example at the datatables site) like:
$.fn.dataTable.moment('epoch');
...but I don't see an option. What's the best approach here?
If you include moment.js you can sort this out quite easily using moment within a render function of your columns option array. Something like this should work:
{
"data":"date",
"render": function(data){
return moment.unix(data).format("DD/MM/YYYY")
}
}
Hope that helps.
You could create your own formatting function:
function ISODateString(d) {
function pad(n) { return n < 10 ? '0' + n : n }
return pad(d.getDate()) + '/' + pad(d.getMonth() + 1) + '/' + d.getFullYear();
}
And call it in datatables render:
"render": function(data){
var d = new Date(parseInt(data.substr(6), 0));
return ISODateString(d);
}

Filtering posts by timestamp and userId

I have the following object in Couchbase:
{
"postReplyId": "Reply_9AE1F47E585522FD1D2EFFEA7671C0855BBFDA991698B23886E37D1C65DAC8AF_1375468399745",
"userId": "User_9AE1F47E585522FD1D2EFFEA7671C0855BBFDA991698B23886E37D1C65DAC8AF",
"postId": "Message_9AE1F47E585522FD1D2EFFEA7671C0855BBFDA991698B23886E37D1C65DAC8AF_1375457606125",
"post_reply_message": "Testing",
"attachments": {
"images": [
],
"audio": [
],
"videos": [
]
},
"upVoters": [
],
"downVoters": [
],
"upVotes": 0,
"report": 0,
"reporters": [
],
"timestamp": 1375468399745,
"mtype": "reply"
}
I would like to have a view and return all the posts created during the last 30 minutes by the user x
I did:
function (doc, meta) {
if(doc.mtype == "reply") {
var dt = new Date();
if((dt.getTime() - doc.timestamp) < 1800000 )
emit(doc.userId, doc);
}
}
and i pass the userIds as multiple keys in the URL, but I get old results
Can someone suggest a solution?
A view runs as documents are added/modified, and only upon request or when automatically updated. It doesn't rerun constantly, and more importantly, it does not re-run for already added documents. So, as written your view would only contain old results.
You need to emit all documents and include the timestamp as part of the emit, so that you can use that as part of the query to the view (a time range).
So, in your emit function, you might instead (untested code):
function (doc, meta) {
if (doc.mtype === "reply") {
// dt will be when the document is processed by the view, which may
// not when the document was added.
var dt = new Date();
var year = dt.getFullYear();
var month = dt.getMonth() + 1; // make month 1-12
var day = dt.getDate();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
// emit the full key, including the user id and the date of the document.
emit([doc.userId, year, month, day, hours, minutes, seconds], doc._id);
}
}
Then your query might be like this range (broken into several lines for readability):
/salamis_db/_design/docs/_view/by_user_date?
startkey=["the-userId", 2013, 8, 7, 10, 30, 0]
&endkey=["the-userId", 2013, 8, 7, 11, 00, 00]
Although endkey wouldn't strictly be necessary, I've left it in for clarity.
Because of the way Couchbase views work, a view may not always contain all data though (from here):
Irrespective of the stale parameter, documents can only be indexed by
the system once the document has been persisted to disk. If the
document has not been persisted to disk, use of the stale will not
force this process. You can use the observe operation to monitor when
documents are persisted to disk and/or updated in the index.
Also, note that documents are not immediately added to the view by default. Read this for more information.

Adding x axis labels when using dojox.charting.DataSeries

I'm creating a Dojo line chart from a dojo.data.ItemFileReadStore using a dojox.charting.DataSeries. I'm using the third parameter (value) of the constructor of DataSeries to specify a method which will generate the points on the chart. e.g.
function formatLineGraphItem(store,item)
{
var o = {
x: graphIndex++,
y: store.getValue(item, "fileSize"),
};
return o;
}
The graphIndex is an integer which is incremented for every fileSize value. This gives me a line chart with the fileSize shown against a numeric count. This works fine.
What I'd like is to be able to specify the x axis label to use instead of the value of graphIndex i.e. the under lying data will still be 1,2,3,4 but the label will show text (in this case the time at which the file size was captured).
I can do this by passing in an array of labels into the x asis when I call chart.addAxis() but this requires me to know the the values before I iterate through the data. e.g.
var dataSeriesConfig = {query: {id: "*"}};
var xAxisLabels = [{text:"2011-11-20",value:1},{text:"2011-11-21",value:2},{text:"2011-11-22",value:3}];
var chart1 = new dojox.charting.Chart("chart1");
chart1.addPlot("default", {type: "Lines", tension: "4"});
chart1.addAxis("x", {labels: xAxisLabels});
chart1.addAxis("y", {vertical: true});
chart1.addSeries("Values", new dojox.charting.DataSeries(dataStore, dataSeriesConfig, formatLineGraphItem));
chart1.render();
The xAxisLabels array can be created by preparsing the dataSeries but it's not a very nice work around.
Does anyone have any ideas how the formatLineGraphItem method could be extended to provide the x axis labels. Or does anyone have any documentation on what values the object o can contain?
Thanks in advance!
This will take a unix timestamp, multiply the value by 1000 (so that it has microseconds for JavaScript, and then pass the value to dojo date to format it).
You shouldn't have any problems editing this to the format you need.
You provided examples that your dates are like "1", "2", "3", which is clearly wrong. Those aren't dates.. so this is the best you can do unless you edit your question.
chart1.addAxis("x",{
labelFunc: function(n){
if(isNaN(dojo.number.parse(n)) || dojo.number.parse(n) % 1 != 0){
return " ";
}
else {
// I am assuming that your timestamp needs to be multiplied by 1000.
var date = new Date(dojo.number.parse(n) * 1000);
return dojo.date.locale.format(date, {
selector: "date",
datePattern: "dd MMMM",
locale: "en"
});
}
},
maxLabelSize: 100
}

Couchdb views and many (thousands) document types

I'm studing CouchDB and I'm picturing a worst case scenario:
for each document type I need 3 view and this application can generate 10 thousands of document types.
With "document type" I mean the structure of the document.
After insertion of a new document, couchdb make 3*10K calls to view functions searching for right document type.
Is this true?
Is there a smart solution than make a database for each doc type?
Document example (assume that none documents have the same structure, in this example data is under different keys):
[
{
"_id":"1251888780.0",
"_rev":"1-582726400f3c9437259adef7888cbac0"
"type":'sensorX',
"value":{"ValueA":"123"}
},
{
"_id":"1251888780.0",
"_rev":"1-37259adef7888cbac06400f3c9458272"
"type":'sensorY',
"value":{"valueB":"456"}
},
{
"_id":"1251888780.0",
"_rev":"1-6400f3c945827237259adef7888cbac0"
"type":'sensorZ',
"value":{"valueC":"789"}
},
]
Views example (in this example only one per doc type)
"views":
{
"sensorX": {
"map": "function(doc) { if (doc.type == 'sensorX') emit(null, doc.valueA) }"
},
"sensorY": {
"map": "function(doc) { if (doc.type == 'sensorY') emit(null, doc.valueB) }"
},
"sensorZ": {
"map": "function(doc) { if (doc.type == 'sensorZ') emit(null, doc.valueC) }"
},
}
The results of the map() function in CouchDB is cached the first time you request the view for each new document. Let me explain with a quick illustration.
You insert 100 documents to CouchDB
You request the view. Now the 100 documents have the map() function run against them and the results cached.
You request the view again. The data is read from the indexed view data, no documents have to be re-mapped.
You insert 50 more documents
You request the view. The 50 new documents are mapped and merged into the index with the old 100 documents.
You request the view again. The data is read from the indexed view data, no documents have to be re-mapped.
I hope that makes sense. If you're concerned about a big load being generated when a user requests a view and lots of new documents have been added you could look at having your import process call the view (to re-map the new documents) and have the user request for the view include stale=ok.
The CouchDB book is a really good resource for information on CouchDB.
James has a great answer.
It looks like you are asking the question "what are the values of documents of type X?"
I think you can do that with one view:
function(doc) {
// _view/sensor_value
var val_names = { "sensorX": "valueA"
, "sensorY": "valueB"
, "sensorZ": "valueC"
};
var value_name = val_names[doc.type];
if(value_name) {
// e.g. "sensorX" -> "123"
// or "sensorZ" -> "789"
emit(doc.type, doc.value[value_name]);
}
}
Now, to get all values for sensorY, you query /db/_design/app/_view/sensor_value with a parameter ?key="sensorX". CouchDB will show all values for sensorX, which come from the document's value.valueA field. (For sensorY, it comes from value.valueB, etc.)
Future-proofing
If you might have new document types in the future, something more general might be better:
function(doc) {
if(doc.type && doc.value) {
emit(doc.type, doc.value);
}
}
That is very simple, and any document will work if it has a type and value field. Next, to get the valueA, valueB, etc. from the view, just do that on the client side.
If using the client is impossible, use a _list function.
function(head, req) {
// _list/sensor_val
//
start({'headers':{'Content-Type':'application/json'}});
// Updating this will *not* cause the map/reduce view to re-build.
var val_names = { "sensorX": "valueA"
, "sensorY": "valueB"
, "sensorZ": "valueC"
};
var row;
var doc_type, val_name, doc_val;
while(row = getRow()) {
doc_type = row.key;
val_name = val_names[doc_type];
doc_val = row.value[val_name];
send("Doc " + row.id + " is type " + doc_type + " and value " + doc_val);
}
}
Obviously use send() to send whichever format you prefer for the client (such as JSON).