Uploading multiple images with timestamp as their name [duplicate] - javascript

I need a unique number to be generated to be used in my code.I use
var id = new Date().valueOf()
I know the above returns the number of milliseconds.
But the values are not unique.For example :1385035174752.This number is generated twice or more than that.
My question is Why is it not unique? and how do i get unique number from current date/time?

If you need uniqueness, use Math.random(), and not any of the Date() APIs.
Math.random returns an integer between and including 0 and 1. If you really want an semi-unique number based on the current time, you can combine the Date API with Math.random. For example:
var id = new Date().getTime() + Math.random();
In modern browsers, you can also use performance.now(). This API guarantees that every new call's return value is unique.

On Windows the resolution of the timer is about 10.5 ms. So you have chances of getting the same value even few milliseconds later. There are better timers of course, but AFAIK they are not available to JavaScript.

example.Even performance.now() sometimes don't give unique numbers. You have to make your own system to generate it. Something like make a counter and increase it by 1 each time when it is accessed.

Related

Get changes based on uploaded time from firebase

I have initialized a real time database using firebase, I am detecting live changes to the databse using
const ref = firebase.database().ref("test");
ref.on('value', function(dataSnapshot){
console.log(dataSnapshot.val())
});
But this returns me value in ascending order. Whereas I want it to return based on time. I tried using time in: 00:00 (IST) format but if a data is marked 11:59 (am) and another 01:02 (pm) this will return me the second message first.
What will be the best way to fix this?
example data is =>
in my databse =>
It is not clear what you mean by time in ascending order
None of your example data mention time. They are just usernames and text.
If you want to order times correctly, best to use ISO date format
This stores 1:02 pm as 13:02, which will sort after 11:59. Its sorting characteristics are ideal.
Use an international time standard to store your times
An international time standard, UTC, has great advantages over national times. It is not subject to change with location, political decisions, or season. You can always interconvert with the user's local time, at the time of entry or display.
Example
const dateString = (new Date()).toISOString();
console.log(dateString)
// Result:
// 2021-06-22T14:40:37.985Z
// If you want to use them as Firebase keys, they must not contain a ".", so you might clean it up like this:
const cleanDateString = (new Date()).toISOString().replace(".","-")
console.log(cleanDateString)
// Result:
// 2021-06-22T14:47:44-445Z
Even better, use a Firebase PushID
The above date-and-time system will work if you are using it to sort the remarks made by a single person, but will not be good as a message identifier if a single space is shared by all people, since 2 people will eventually make a message at the same millisecond, and will get the same message ID.
To deal with that it is better practice to use a Firebase Push ID.
An explanation is given here: In Firebase when using push() How do I get the unique ID and store in my database
Or from Firebase itself, here:
https://firebase.google.com/docs/database/admin/save-data

How to stop a function from executing more than x times per day?

In Google Sheets Script, how do I stop a function from executing more than x e.g. 5 times a day?
For instance, I have a trigger that executes a function every 20 minutes that sends an email based on a condition in the function, however I only want it to send this email a maximum of 5 times a day. How would I do this?
As other users recommended, you can store a value in the Project Properties, and use it to count how many times the script has been executed. I recommend you to use a condition to compare the new property with 5.
Remind to convert the property returned result type to Integer, as it is an
String by default, otherwise you won't be able to add 1 in each
execution.
As an example we can use the setProperty to modify the already saved value, for example:
var userProperties = PropertiesService.getUserProperties();
var newValue = +userProperties.getProperty('Execution_times') + 1;
userProperties.setProperty('Execution_times', newValue); // Updates stored value.

How can I set the Unix epoch of a moment js object?

I have a moment.js object whose Unix epoch value I'd like to change.
Normally I'd use myMoment = moment(someEpoch);, but because of design constraints I'm having to pass the object by reference, so I must mutate the value rather than replacing it altogether.
What is the neatest and (ideally) most performant way to do this in v2.15+?
Assuming m is a moment object, and t is the timestamp to set (in ms), probably the easiest way is:
m.add(t-m);
Or if you prefer to be more verbose:
m.add(t - m.valueOf(), 'ms');
Note that the default units are milliseconds when not specified and the input is numeric. If your input timestamp is in whole seconds, you'd have to multiply it by 1000 in either of the above formulas before subtracting the value of m.
However, if you're really after the most efficient code in terms of minimizing total operations performed internally, you could modify moment internals directly. Doing so is dangerous in that there's no guarantee the internals won't change between versions. Only the public API compatibility is guaranteed, following SemVer rules. So only do this if you are optimizing for perf and are willing to deal with potentially breaking changes in the future:
m._d.setTime(t + ((m._offset || 0) * 60000));
This is essentially an inversion of moment's valueOf function, and is probably what the implementation would look like if it were built in to moment.
Of course, if you are only working with moments in UTC mode, you can just do:
m._d.setTime(t);
One last thing, with regard to terminology, you can't actually set "the Unix epoch value", because the epoch is a fixed value. In this context, "epoch" means the timestamp that is zero, which is associated with 1970-01-01T00:00:00.000Z. It cannot be changed. You are simply using a "Unix Timestamp in milliseconds", or perhaps an "epoch-based timestamp". But it is a misnomer for your variable to be named someEpoch.
moment.js has a method to do that:
moment.unix(Number)
http://momentjs.com/docs/#/parsing/unix-timestamp/

Dynamic Frequency Map from MongoDB Keys

I'm using MiniMongo through Meteor, and I'm trying to create a frequency table based off of a dynamic set of queries.
I have two main fields, localHour and localDay. I expect many overlaps, and I'd like to determine where the most overlaps occur. My current method of doing this is so.
if(TempStats.findOne({
localHour: hours,
localDay: day
})){//checks if there is already some entry on the same day/hour
TempStats.update({//if so, we just increment frequency
localHour: hours,
localDay: day
},{
$inc: {freq: 1}
})
} else {//if nothing exists yet, we put in a new entry
TempStats.insert({
localHour: hours,
localDay: day,
freq: 1
});
}
Essentially, this code runs every time I have new data I want to insert. It works fine at the moment, in that, after all data is inserted, I can sort by frequency to find what set of hours & days occurs the most often (TempStats.find({}, {sort: {freq: -1}}).fetch()).
However, I'm looking more for a way to search by frequency for any key. For instance, searching for the day which everything occurs on the most often as opposed to both the date and hour. With my current way of doing this, I would need to have multiple databases and different methods of inserting for each, which is a bit ridiculous. Is there a Mongo (specifically MiniMongo) solution to do frequency maps based on keys?
Thanks!
It looks like miniMongo does not in fact support aggregation, which makes this kind of operation difficult. One way to go about it would be aggregating yourself at the end of each day and inserting that aggregate record into your db (without the hour field or with it set to something like -1). Conversely as wastefully you could also update that record at the time of each insert. This would allow you to use the same collection for both and is fairly common in other dbs.
Also you should consider #nickmilon's first suggestion since the use of an upsert statement with the $inc operator would reduce your example to a single operation per data point.
a small note on your code: the part that comes as an else statement is not really required your update will do the complete job if you combine it with the option upsert=true it will insert a new document and $inc will set the freq field to 1 as desired see: here and here
for alternative ways to count your frequencies: assuming you store the date as a datetime object I would suggest to use an aggregation (I am not sure if they added support for aggregation yet in minimongo) but there are solutions then with aggregation you can use datetime operators as
$hour, $week, etc for filtering and $count to count the frequencies without you having to keep counts in the database.
This is basically a simple map-reduce problem.
First, don't separate the derived data into 2 fields. This violates DB best practices. If the data comes to you this way, use it to create a Date object. I assume you have a bunch of collections that are being subscribed to and then you aggregate all those into this temporary local collection. This is the mapping of the map-reduce pattern. At this point, since your query in unknown, it's a waste of CPU (even though it's your client) to aggregate. Map first, reduce second. What you should have is a collection full of datetimes. call it TempMapCollection if you wish. Now, use a forEach() and pass in your reduce function (by day, by hour, etc).
You can reduce into another local collection, or into a javascript object. I like using collections, but if the objects are complex, you'll get EJSON errors all up in there. Since your objects are nothing more than a datetime, let's use collections.
so you've got something like:
TempMapCollection.find().forEach(function(doc) {
var date = doc.dateTime.getDate();
TempReduceCollection.upsert({timequery: hours}, {$inc: {freq: 1}});
})
Now query your reduce collection. This has the added benefit that you won't have to re-map if you want to do 2 unique queries.

Javascript timestamp number is not unique

I need a unique number to be generated to be used in my code.I use
var id = new Date().valueOf()
I know the above returns the number of milliseconds.
But the values are not unique.For example :1385035174752.This number is generated twice or more than that.
My question is Why is it not unique? and how do i get unique number from current date/time?
If you need uniqueness, use Math.random(), and not any of the Date() APIs.
Math.random returns an integer between and including 0 and 1. If you really want an semi-unique number based on the current time, you can combine the Date API with Math.random. For example:
var id = new Date().getTime() + Math.random();
In modern browsers, you can also use performance.now(). This API guarantees that every new call's return value is unique.
On Windows the resolution of the timer is about 10.5 ms. So you have chances of getting the same value even few milliseconds later. There are better timers of course, but AFAIK they are not available to JavaScript.
example.Even performance.now() sometimes don't give unique numbers. You have to make your own system to generate it. Something like make a counter and increase it by 1 each time when it is accessed.

Categories

Resources