Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Books

The Egg – Andy Weir

Awesome Andy Weir and his The egg. If you like this, you may like his The Martian which will be a movie in 2015. The Youtube adaptation:

You were on your way home when you died.

It was a car accident. Nothing particularly remarkable, but fatal nonetheless. You left behind a wife and two children. It was a painless death. The EMTs tried their best to save you, but to no avail. Your body was so utterly shattered you were better off, trust me.

And that’s when you met me.

“What… what happened?” You asked. “Where am I?”

“You died,” I said, matter-of-factly. No point in mincing words.

“There was a… a truck and it was skidding…”

“Yup,” I said.

“I… I died?”

“Yup. But don’t feel bad about it. Everyone dies,” I said.

You looked around. There was nothingness. Just you and me. “What is this place?” You asked. “Is this the afterlife?”

“More or less,” I said.

“Are you god?” You asked.

“Yup,” I replied. “I’m God.”

“My kids… my wife,” you said.

“What about them?”

“Will they be all right?”

“That’s what I like to see,” I said. “You just died and your main concern is for your family. That’s good stuff right there.”

You looked at me with fascination. To you, I didn’t look like God. I just looked like some man. Or possibly a woman. Some vague authority figure, maybe. More of a grammar school teacher than the almighty.

“Don’t worry,” I said. “They’ll be fine. Your kids will remember you as perfect in every way. They didn’t have time to grow contempt for you. Your wife will cry on the outside, but will be secretly relieved. To be fair, your marriage was falling apart. If it’s any consolation, she’ll feel very guilty for feeling relieved.”

“Oh,” you said. “So what happens now? Do I go to heaven or hell or something?”

“Neither,” I said. “You’ll be reincarnated.”

“Ah,” you said. “So the Hindus were right,”

“All religions are right in their own way,” I said. “Walk with me.”

You followed along as we strode through the void. “Where are we going?”

“Nowhere in particular,” I said. “It’s just nice to walk while we talk.”

“So what’s the point, then?” You asked. “When I get reborn, I’ll just be a blank slate, right? A baby. So all my experiences and everything I did in this life won’t matter.”

“Not so!” I said. “You have within you all the knowledge and experiences of all your past lives. You just don’t remember them right now.”

I stopped walking and took you by the shoulders. “Your soul is more magnificent, beautiful, and gigantic than you can possibly imagine. A human mind can only contain a tiny fraction of what you are. It’s like sticking your finger in a glass of water to see if it’s hot or cold. You put a tiny part of yourself into the vessel, and when you bring it back out, you’ve gained all the experiences it had.

“You’ve been in a human for the last 48 years, so you haven’t stretched out yet and felt the rest of your immense consciousness. If we hung out here for long enough, you’d start remembering everything. But there’s no point to doing that between each life.”

“How many times have I been reincarnated, then?”

“Oh lots. Lots and lots. An in to lots of different lives.” I said. “This time around, you’ll be a Chinese peasant girl in 540 AD.”

“Wait, what?” You stammered. “You’re sending me back in time?”

“Well, I guess technically. Time, as you know it, only exists in your universe. Things are different where I come from.”

“Where you come from?” You said.

“Oh sure,” I explained “I come from somewhere. Somewhere else. And there are others like me. I know you’ll want to know what it’s like there, but honestly you wouldn’t understand.”

“Oh,” you said, a little let down. “But wait. If I get reincarnated to other places in time, I could have interacted with myself at some point.”

“Sure. Happens all the time. And with both lives only aware of their own lifespan you don’t even know it’s happening.”

“So what’s the point of it all?”

“Seriously?” I asked. “Seriously? You’re asking me for the meaning of life? Isn’t that a little stereotypical?”

“Well it’s a reasonable question,” you persisted.

I looked you in the eye. “The meaning of life, the reason I made this whole universe, is for you to mature.”

“You mean mankind? You want us to mature?”

“No, just you. I made this whole universe for you. With each new life you grow and mature and become a larger and greater intellect.”

“Just me? What about everyone else?”

“There is no one else,” I said. “In this universe, there’s just you and me.”

You stared blankly at me. “But all the people on earth…”

“All you. Different incarnations of you.”

“Wait. I’m everyone!?”

“Now you’re getting it,” I said, with a congratulatory slap on the back.

“I’m every human being who ever lived?”

“Or who will ever live, yes.”

“I’m Abraham Lincoln?”

“And you’re John Wilkes Booth, too,” I added.

“I’m Hitler?” You said, appalled.

“And you’re the millions he killed.”

“I’m Jesus?”

“And you’re everyone who followed him.”

You fell silent.

“Every time you victimized someone,” I said, “you were victimizing yourself. Every act of kindness you’ve done, you’ve done to yourself. Every happy and sad moment ever experienced by any human was, or will be, experienced by you.”

You thought for a long time.

“Why?” You asked me. “Why do all this?”

“Because someday, you will become like me. Because that’s what you are. You’re one of my kind. You’re my child.”

“Whoa,” you said, incredulous. “You mean I’m a god?”

“No. Not yet. You’re a fetus. You’re still growing. Once you’ve lived every human life throughout all time, you will have grown enough to be born.”

“So the whole universe,” you said, “it’s just…”

“An egg.” I answered. “Now it’s time for you to move on to your next life.”

And I sent you on your way.

Miscellaneou$

MacBook 12 keyboard fiasco

I love you Apple and all, but honestly I don’t know dafuq was it with the person who approved this keyboard – namely the keys for up/down/left/right. I mean, have you ever used this?! Like, in real life, no just an image in Photoshop?!

Jeez, imagine typing on a full scale size keyboard for 20 years and now, what do you know, someone makes this utter garbage, arrrgh! On one of my previous laptops (HP G6) they made the same mistake and never went back to it again.

I didn’t like the small movement keys on Air either, but that was manageable since all were the same size, but with this – tears and pain :/

I see people hitting the SHIFT key waaay more often now :/. Blame the 20 year muscle memory 😛

On the bright side of life, iWatch  looks nice – we’ll just have to wait a bit longer till they do something with the battery.

Stack Overflow

Group by hour in mysql but include the first value from the hour+1 also

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Say you have data like this:

  time  value
  10:00   5
  10:15   12
  10:30   15
  10:45   27
  11:00   29

And a query like this:

SELECT MAX(value)- MIN(value), HOUR(time)FROM mytable GROUP BY HOUR(time);

You will get:

 value  time
   22   10

But, I would need it to include the value at 11:00, thus the result being 24 (29-5), and not 22. Is there a way to do this in SQL or do I have no other choice than to do this manually in the code level (so, without the grouping, just fetching the data and manually substracting).

The answer, by ATP_JD, was:

Depending on how consistent your data is, you might be able to do this with a self join, like so:

SELECT HOUR(a.`time`)AS grouper,
GREATEST(MAX(a.value),IFNULL(MIN(b.value),0))- MIN(a.value)AS diff
FROM mytable a
LEFTJOIN mytable b ONIF(HOUR(a.time)<=23, HOUR(a.time)+1,0)= HOUR(b.time)GROUP BY grouper

The LEFT JOIN on the same table allows you to get the next hour’s value for comparison purposes.

http://sqlfiddle.com/#!9/fe72a/16

Ionic, Quick tips

Handling Ionic CORS issue

CORS = Cross origin resource sharing – a pain in the butt when trying to do an ajax request when developing locally.

For local testing I ended up using a Chrome plugin: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en.

The site http://enable-cors.org/ gives a lot of info on how to solve the cors issue if you control the API server. Namely, for Apache: http://enable-cors.org/server_apache.html.

But, TBH, all this ended up not working for me, so what I did was I created a “proxy” .php page which is called first (not calling the json file directly) and the PHP code for that page looks like this:

<?php
	header('Access-Control-Allow-Origin: *'); 
	echo file_get_contents("myJSON.json");
?>

edit: I answered a similar question on StackOverflow and I wrote a full tutorial with downloadable project from Github about this.

Stack Overflow

Wait for click before starting the game in Phaser

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

The JSFiddle demo is here, but am pasting the code below also. My question is simple (though I can’t seem to find any example in how to realize this): right now if you start the game in JSFiddle you will see that the rectangle immediately “falls” down. I would somehow like the game to start when I click with the mouse (basically that nothing happens before the first click of a mouse) – any points on how to accomplish this?

JS:

// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var game_state = {};


// Creates a new 'main' state that wil contain the game
game_state.main = function () {};
game_state.main.prototype = {

    preload: function () {
        // Change the background color of the game
        this.game.stage.backgroundColor = '#71c5cf';

        // Load the bird sprite
        this.game.load.image('bird', 'https://lh6.googleusercontent.com/Xrz0PnR6Ezg5_k5zyFKxGv0LzehAP9SMj_ga3qQzIF4JAfv8xHm7TxfliwtBD8ihfw=s190');
        this.game.load.image('pipe', 'https://lh4.googleusercontent.com/RSMNhJ3KY4Xl0PQpUf6I9EayOdLhvOKKV9QV7_BXXYVedPy0oMNRFKANW14xV76NDA=s190');
    },

    create: function () {
        // Display the bird on the screen
        this.bird = this.game.add.sprite(100, 245, 'bird');

        // Add gravity to the bird to make it fall
        this.bird.body.gravity.y = 1000;

        // Call the 'jump' function when the spacekey is hit
        var space_key = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        space_key.onDown.add(this.jump, this);

        this.pipes = game.add.group();
        this.pipes.createMultiple(20, 'pipe');
        this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);

        this.score = 0;
        var style = {
            font: "30px Arial",
            fill: "#ffffff"
        };
        this.label_score = this.game.add.text(20, 20, "0", style);

    },

    update: function () {
        // If the bird is out of the world (too high or too low), call the 'restart_game' function
        this.game.physics.overlap(this.bird, this.pipes, this.restart_game, null, this);
        if (this.bird.inWorld == false) this.restart_game();
    },


    // Make the bird jump 
    jump: function () {
        // Add a vertical velocity to the bird
        this.bird.body.velocity.y = -350;
    },

    // Restart the game
    restart_game: function () {
        // Start the 'main' state, which restarts the game
        this.game.time.events.remove(this.timer);
        this.game.state.start('main');
    },

    add_one_pipe: function (x, y) {
        // Get the first dead pipe of our group
        var pipe = this.pipes.getFirstDead();

        // Set the new position of the pipe
        pipe.reset(x, y);

        // Add velocity to the pipe to make it move left
        pipe.body.velocity.x = -200;

        // Kill the pipe when it's no longer visible 
        pipe.outOfBoundsKill = true;
    },
    add_row_of_pipes: function () {
        this.score += 1;
        this.label_score.content = this.score;
        var hole = Math.floor(Math.random() * 5) + 1;

        for (var i = 0; i < 8; i++)
        if (i != hole && i != hole + 1) this.add_one_pipe(400, i * 60 + 10);
    },
};



// Add and start the 'main' state to start the game
game.state.add('main', game_state.main);
game.state.start('main');

CSS:

#game_div {
    width: 400px;
    margin: auto;
    margin-top: 50px;
}

HTML:

<div id="game_div"></div>

I found the answer to this one myself:

So, to not leave this question unanswered and to help further readers, here is the link to the updated jsFiddle where I solved my initial problem, and below is the code from jsFiddle.

However, if one will be interested I suggest taking a look at the freely available code on GitHub which uses game states and has a better structured code.

jsFiddle

CSS:

#game_div {
    width: 400px;
    margin: auto;
    margin-top: 50px;
}

HTML:

<div id="game_div"></div>

JS:

// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'game_div');
var game_state = {};
var gameStarted = false;


// Creates a new 'main' state that wil contain the game
game_state.main = function () {};
game_state.main.prototype = {

    game_start: function(){
        if (!gameStarted){
            this.bird.body.gravity.y = 1000;
            this.timer = this.game.time.events.loop(1500, this.add_row_of_pipes, this);
            this.label_start.content = "";
        }
        gameStarted = true;
    },
    preload: function () {
        // Change the background color of the game
        this.game.stage.backgroundColor = '#71c5cf';

        // Load the bird sprite
        this.game.load.image('bird', 'https://lh6.googleusercontent.com/Xrz0PnR6Ezg5_k5zyFKxGv0LzehAP9SMj_ga3qQzIF4JAfv8xHm7TxfliwtBD8ihfw=s190');
        this.game.load.image('pipe', 'https://lh4.googleusercontent.com/RSMNhJ3KY4Xl0PQpUf6I9EayOdLhvOKKV9QV7_BXXYVedPy0oMNRFKANW14xV76NDA=s190');
    },

    create: function () {
        // Display the bird on the screen
        this.bird = this.game.add.sprite(100, 245, 'bird');

        // Add gravity to the bird to make it fall


        // Call the 'jump' function when the spacekey is hit
        this.game.input.onDown.add(this.game_start, this);

        this.pipes = game.add.group();
        this.pipes.createMultiple(20, 'pipe');


        this.score = 0;
        var style = {
            font: "30px Arial",
            fill: "#ffffff"
        };
        this.label_score = this.game.add.text(20, 20, "0", style);
        this.label_start = this.game.add.text(35, 180, "Click to start the show", style);
        game.input.onDown.add(this.jump, this);
    },

    update: function () {
        // If the bird is out of the world (too high or too low), call the 'restart_game' function
        this.game.physics.overlap(this.bird, this.pipes, this.restart_game, null, this);
        if (this.bird.inWorld == false) this.restart_game();
    },


    // Make the bird jump 
    jump: function () {
        // Add a vertical velocity to the bird
        this.bird.body.velocity.y = -350;
    },

    // Restart the game
    restart_game: function () {
        // Start the 'main' state, which restarts the game
        this.game.time.events.remove(this.timer);
        this.game.state.start('main');
        gameStarted=false;
    },

    add_one_pipe: function (x, y) {
        // Get the first dead pipe of our group
        var pipe = this.pipes.getFirstDead();

        // Set the new position of the pipe
        pipe.reset(x, y);

        // Add velocity to the pipe to make it move left
        pipe.body.velocity.x = -200;

        // Kill the pipe when it's no longer visible 
        pipe.outOfBoundsKill = true;
    },
    add_row_of_pipes: function () {
        this.score += 1;
        this.label_score.content = this.score;
        var hole = Math.floor(Math.random() * 5) + 1;

        for (var i = 0; i < 8; i++)
        if (i != hole && i != hole + 1) this.add_one_pipe(400, i * 60 + 10);
    },
};



// Add and start the 'main' state to start the game
game.state.add('main', game_state.main);
game.state.start('main');

 

Angular

Speeding up Angular development with Yeoman

Yeoman helps you to kickstart new projects, prescribing best practices and tools to help you stay productive.

To do so, we provide a generator ecosystem. A generator is basically a plugin that can be run with the `yo` command to scaffold complete projects or useful parts…

First, install Yeoman with npm:

npm install yo -g

Now you need a “generator”, and most likely you’ll need grunt:

npm install -g generator-angular grunt

If you get the error like The package generator-karma does not satisfy its siblings’ peerDependencies requirements then try uninstalling generator-karma:

npm uninstall -g generator-karma

and running the previous npm install command again.

Btw,  you can use Yeoman’s CLI (by first executing yo) to search and install any of the existing generators.

To scaffold a new app, create some folder and execute the following command:

yo angular myApp

Yeoman will ask you few questions to which you can all give a default answer and it will start the installation process. After the installation is done you can do:

grunt serve

to actually see a live preview of your scaffolded app.

If you get an error like Warning: Couldn’t find the `compass` binary. Make sure it’s installed and in your $PATH Use –force to continue install it with (if you’re on Mac):

sudo gem install compass

Additional cool thing is that this generator comes with extra tools for quick scaffolding of routes, controllers, views, directives, services, filters… Be sure to check the project on GitHub for more info.

For example, the following command generates a controller and a view, and configures a route in app/scripts/app.js connecting them.

yo angular:route myroute

 

Stack Overflow

How can I make sure that DELETE SQL statement in Postgres using PHP was successfull?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Is there a function which would return true of false based on if the DELETE SQL statement succeded or not? For example something like this:

<?php
    $sql = "DELETE FROM table WHERE id=123";
    $result = pg_query($sql);

    if **function**($result)
        return true;
    else
        return false;
?>

The answer, by LolCoder, was:

Use mysql_affected_rows() to get number of affected rows in mysql.

Similary for postgres, it will be pg_affected_rows.

NodeJS, Quick tips

Keep your Node.js scripts running with Forever and Nodemon

edit (18.06.2015): Nowdays I’m using PM2, and here’s my post that explains how to use PM2.


Nodemon is a utility that will monitor for any changes in your source and automatically restart your server.  Install with npm:

npm install -g nodemon

Forever is a simple CLI tool for ensuring that a given script runs continuously (i.e. forever). Install with npm:

npm install -g forever

Forever & Nodemon running together:

forever start nodemon --exitcrash app.js

edit (24.02.2015):

If you get an error like this:

error:   Cannot start forever
error:   script /home/nikola/nodemon does not exist.

Try to run nodemon with the full path:

forever start /usr/bin/nodemon --exitcrash app.js

You can find out the path to nodemon by executing:

which nodemon
Stack Overflow

Writing small data to file and reading from it or query the database

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I have a situation where I would have to query the database for some data which is the same for all users and changes daily, so I figured I could make a file in which I would save this data (once per day) and then load it from that file each time a user visits my site.

Now, I know that this is a common practice (caching) when the requests from database are big but the data I’m about to write to the file is a simple 3 digit number, so my question is should this still be faster or is it just an overkill and I should stick with the database query?

 The answer, by Dukeling, was:

Caching, when done right, is always faster.

It depends how long storing and retrieving data from the file takes and how long requests to the database takes.

If the database query to get the number takes long, then caching may be a good idea, since the data is small.

If you were to do a search (e.g. sequential) in a file with lots of cached data (which doesn’t seem to be the case), it would take long.

Disk I/O could be slower than database I/O (which is unlikely, unless it’s a local DB).

Bottom line – benchmark.

For your scenario, caching is probably a good idea, but if it’s only a single 3-digit number for all users then I’d just try to stick it in RAM rather than in a file.

NodeJS

How to use Redis with Node.js

Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

Comparison with Memcache and Memcached can be found here, and the naming distinction can be found here.

You can download the installation zip file here (I used the Windows version), and extract it to C:\redis. To run the Redis server (in order to be able to save to it and query it) you have to execute the redis-server.exe from this directory.

To use Redis with Node.js you have install the redis module:

npm install redis

A simple usage example:

var redis = require("redis"),
    client = redis.createClient();

// if you'd like to select database 3, instead of 0 (default), call
// client.select(3, function() { /* ... */ });

client.on("error", function (err) {
    console.log("Error " + err);
});

client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
    console.log(replies.length + " replies:");
    replies.forEach(function (reply, i) {
        console.log("    " + i + ": " + reply);
    });
    client.quit();
});

A lot more examples here.

Page 39 of 51« First...102030«38394041»50...Last »

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak