How to Express 'Infinite Time'

Is there a way to express 'infinite time'?

It's possible using DateTime::Infinity class:

future = DateTime.now..DateTime::Infinity.new
future.include?(1_000_000.years.from_now) #=> true

Problems with infinite time range in Rails

You cannot store Infinity as part of a time range in Rails. I believe this is because Infinity is going to be inserted as a string value and interpreted as a float when pulled out of the native PSQL oid. So, any date range from Date -> Float will not be viable. But you can manage to create your own range with pseudo (1 million years from now) dates or you can just use two separate date fields and interpret them appropriately in the model. Begin date, end date.

In Rails 4.2+, you can store a Float::INFINITY value inside your datetime type. Example.

User.first.update(begin_date: DateTime.now, end_date: 'infinity')
User.first.end_date # => Infinity

However, end_date will not be a valid date. You're just storing the string in the database and you're pulling out a float when your call it.

Here's the actual (Rails 4.2) code that handles that:

module ActiveRecord
module ConnectionAdapters
module PostgreSQL
module OID # :nodoc:
class DateTime < Type::DateTime # :nodoc:
include Infinity

def type_cast_for_database(value)
if has_precision? && value.acts_like?(:time) && value.year <= 0
bce_year = format("%04d", -value.year + 1)
super.sub(/^-?\d+/, bce_year) + " BC"
else
super
end
end

def cast_value(value)
if value.is_a?(::String)
case value
when 'infinity' then ::Float::INFINITY
when '-infinity' then -::Float::INFINITY
when / BC$/
astronomical_year = format("%04d", -value[/^\d+/].to_i + 1)
super(value.sub(/ BC$/, "").sub(/^\d+/, astronomical_year))
else
super
end
else
value
end
end
end
end
end
end
end

Again, you will not be able to do date time comparisons with a float. But, it's probably simple enough to have a special case for these two values -::Float::INFINITY and ::Float::INFINITY

Is there a way to ask time.After() for an infinite amount of time?

There is no "forever" duration, but there is max duration:

const maxDuration time.Duration = 1<<63 - 1

maxDuration is about 292 years. It should be enough for the lifetime of a single app. But instead I propose the below solution which doesn't use it:

Note that if "forever" is the intended max wait time, it's simpler and more efficient to omit time.After() and use a simple receive:

func service(timeout *time.Duration) SomeType {
if timeout == nil {
return <-some_channel
}

select {
case value := <-some_channel:
return value
case <-time.After(*timeout):
return nil
}
}

You indicated that your actual code is much more complex and contains more cases.

In that case, I'd move the timeout channel creation outside of the select statement, and initialize accordingly. When timeout is nil, just leave the channel nil (its zero value), which will never deliver any value, so receiving from a nil channel literally takes "forever":

func service(timeout *time.Duration) SomeType {
var timeoutCh <-chan time.Time
if timeout != nil {
timeoutCh = time.After(*timeout)
}

select {
case value := <-some_channel:
return value
case <-timeoutCh:
return nil
}
}

Breaking an infinite loop in Node.js/Express.Js

This will never work like you would expect, you're firing async requests inside a sync while loop. So at the time the first request is trying to get the data, you're firing the same request again, so your first request gets canceled. This goes like forever. You should fire the next request inside the success callback of the previous request, so it gets fired after the previous one resolves.

Something like that:

app.post("/api/example", function(req, res) {
var username = username;
var password = password;
var container = [];
var maxPages = 5;
var makeRequest = function(page) {
console.log("I'm making a request");
var URL = "https://fakeapiurl.com/&page=" + page;
request.get(URL, {
'auth': {
'user': username,
'pass': password,
'sendImmediately': true
},
'content-type': 'application/json'
}, function(error, response, data) {
var results = JSON.parse(data);
var examples = results.examples || [];
var numOfExamples = results.numResults;
var lastPageReached = (numOfExamples === 0 || numOfExamples === jobsContainer.length - 1);
lastPageReached = lastPageReached && page < maxPages;

if (lastPageReached) {
container.sort(function(a, b) {
etc.
});
res.send(container);
} else {
container = container.concat(...examples);
makeRequest(page + 1);
}
});
};
makeRequest(0);
});

How to create an infinite loop in NodeJS

Why do you want a while loop at all? Either use setInterval, or (better) create a function that calls itself again after a timeout:

function logEvery2Seconds(i) {    setTimeout(() => {        console.log('Infinite Loop Test n:', i);        logEvery2Seconds(++i);    }, 2000)}
logEvery2Seconds(0);
let i = 0;setInterval(() => { console.log('Infinite Loop Test interval n:', i++);}, 2000)

Implement infinite long running service in NodeJS

You can use something very simple like setInterval() to have your task repeat x amount of times.

var testUrls = function(){
//do your magic of connecting to the DB and checking urls.
}

setInterval(testUrls, 60000);

The above code snippet will call your function testUrls every minute.

Or if you need more control over the scheduling you can use a npm package like cron.

JQuery onChange event triggering an infinite amount of times

Try the following script -

<script >
$('#curtainForm').find('select, input').on('change', function(event) {
event.preventDefault();
var $wrapper = $('#curtainForm'),
model_id = $wrapper.find('#model_id').val(),
cover_id = $wrapper.find('#cover_id').val(),
width = $wrapper.find('#width').val(),
height = $wrapper.find('#height').val(),
_token = $('input[name="_token"]').val();

console.log('Model: ' + model_id);
console.log('Cover: ' + cover_id);
console.log('Width: ' + width);
console.log('Height: ' + height);
});
</script>

Infinite loop in Nodejs

You can loop over and test for values in your database using async/await. What we do is convert your function to an async function, then create a new function that will return a promise which will resolve true/false.

Next we call that function in the while loop and await for a result which will contain true/false we then set that to the variable cond and continue the loop.

It would look something like this:

async function makeShort(length) {
let cond = true;

while (cond) {
let short = (Math.random() * 1000).toString(32).replace(/\./g, '').substr(0, length);

let query = { short: short };
cond = await findOne(query);
}
return short;
}

function findOne(query) {
return new Promise(resolve => {
Link.findOne(query, (err, link) => {
if (err) resolve(false);
if (!link) {
return resolve(false);
}
return resolve(true);
});
})
}

We then can call it using let short = await makeShort() like this (we also have to the make (req, res) function async):

router.post('/', async (req, res) => {
let short = await makeShort();
const newLink = new Link({
url: req.body.url,
short: short
});

newLink.save().then(link => {
res.json(link);
});
});


Related Topics



Leave a reply



Submit