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
C#

Proper singleton implementation in C#

Taken from: http://msdn.microsoft.com/en-us/library/ff650316.aspx

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

Static initialization

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}

Multithreaded singleton

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

Test program; on first form you have two buttons, one which sets the amount of singleton, and second button which opens up another form which then sets the amount again. Once returned to the first form, the value updates to the one set on second form.

//Form1.cs
public partial class Form1 : Form
{
    myClass mc;
    public Form1()
    {
        InitializeComponent();
        mc = myClass.Instance;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        mc.iznos = 10;
        updateUI();
    }

    public void updateUI()
    {
        label1.Text = mc.iznos.ToString();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog();
    }

    private void Form1_Activated(object sender, EventArgs e)
    {
        updateUI();
    }
}

 

//Form2.cs
public partial class Form2 : Form
{
    myClass mc;
    public Form2()
    {
        InitializeComponent();
        
        mc = myClass.Instance;
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        mc.iznos = 5;
        updateUI();
    }

    public void updateUI()
    {
        label1.Text = mc.iznos.ToString();
    }
}
public class myClass{
    private static readonly myClass _instance = new myClass();

    private myClass(){}
    public static myClass Instance
    {
        get 
        {
            return _instance; 
        }
    }

    public int iznos { get; set; }
}
Miscellaneou$

Look up

Especially today, when you’re reading this post on your computer/laptop/mobile phone/tablet, this message may be one of the last wake up calls for us. I myself sit at the desk for way too much hours a day, and even though I try to compensate by using a standing desk at home, I still somehow feel that we should try to go (at least few times a week) back to the old days when we were kids and we played in the playground, or built bows in the forest… Meh, I’ll stop writing here and go out for the rest of the day…

C#

How to use App.config in Visual Studio C# .NET

Add reference to System.Configuration :

references

and include it using the using statement:

using System.Configuration;

Edit App.config so that you add your settings in the appSettings  node in an add  element with key  and value  parameters.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

    <appSettings>
      <add key="server" value="localhost" />
      <add key="port" value="5432" />
      <add key="username" value="myusername" />
      <add key="password" value="mypass" />
      <add key="database" value="mydb" />
    </appSettings>
</configuration>

Now you can access your settings in code like this:

string server = ConfigurationManager.AppSettings["server"].ToString();
string port = ConfigurationManager.AppSettings["port"].ToString();
string username = ConfigurationManager.AppSettings["username"].ToString();
string password = ConfigurationManager.AppSettings["password"].ToString();
string database = ConfigurationManager.AppSettings["database"].ToString();

 

Linux, Quick tips

Installing CasperJS on RHEL Linux distribution

First you have to install NodeJS. You can do that via package manager for your distribution. In my case (RHEL) it is easily done with:

sudo yum install nodejs npm --enablerepo=epel

Installing CasperJS is easy via npm (Node package manager):

sudo npm install -g casperjs

You will get output similar to this:

Copying extracted folder /usr/lib/node_modules/casperjs/node_modules/phantomjs/phantomjs/phantomjs-1.9.7-linux-x86_64.tar.bz2-extract-1396259124118/phantomjs-1.9.7-linux-x86_64 -> /usr/lib/node_modules/casperjs/node_modules/phantomjs/lib/phantom
Writing location.js file
Done. Phantomjs binary available at /usr/lib/node_modules/casperjs/node_modules/phantomjs/lib/phantom/bin/phantomjs
/usr/bin/casperjs -> /usr/lib/node_modules/casperjs/bin/casperjs
npm WARN unmet dependency /usr/lib/node_modules/block-stream requires inherits@'~2.0.0' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/fstream requires inherits@'~2.0.0' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/fstream-ignore requires inherits@'2' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/fstream-npm requires inherits@'2' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/glob requires inherits@'2' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/npmconf requires inherits@'~2.0.0' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN unmet dependency /usr/lib/node_modules/tar requires inherits@'2' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
[email protected] /usr/lib/node_modules/casperjs
âââ [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
[[email protected] ~]$ casperjs
Fatal: [Errno 2] No such file or directory; did you install phantomjs?
[[email protected] ~]$ /usr/bin/casperjs
Fatal: [Errno 2] No such file or directory; did you install phantomjs?
[[email protected] ~]$ /usr/lib/node_modules/casperjs/node_modules/phantomjs/lib/phantom/bin/phantomjs
phantomjs>
[[email protected] ~]$ /usr/lib/node_modules/casperjs/node_modules/phantomjs/lib/phantom/bin/phantomjs --version
1.9.7

To have the binaries in my path every time I log in I added this alias to my .bashrc:

alias phantomset="export PATH=$PATH:/usr/lib/node_modules/casperjs/node_modules/phantomjs/lib/phantom/bin/"

and my .bash_profile looks like this:

# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH
phantomset
Books

The Art of War – Sun Tzu

My favourite quotes from the book The Art of War by Sun Tzu:

Hold out baits to entice the enemy. Faint disorder, and crush him.

If it is to your advantage, make a forward move; if not, stay where you’re.

If you know you’re enemy and you know yourself, you need not to fear the result of hundredth of battles . If you know yourself but not the enemy, for every victory gained you’ll also suffer a defeat. If you know neither your enemy nor yourself you will succumb in every battle.

Care about your team but also be a “hardass”.

Hire only great people.

Plan ahead.

Know your enemy.

All warfare is based on deception.

Exploit enemy’s weaknesses, avoid his strengths

Books

Speed reading and learning

Since I like to read (like, a lot), I realized I should test my reading speed and as it turned out I’m at an average person reading speed of 230 WPM. That was not a too big of a surprise as I always thought I read slow. Anyways, I decided to take one of those “increase your reading speed classes”, and here are my notes from these lectures:

Inner voice makes us read at the speed as we talk! Subvocalization is the root of all evil.

RAS – Reticular Activating System (example when you’re looking to buy some new phone you’re seeing the phone commercials everywhere, but once you buy it the commercials ‘dissapear’)

TV is passive medium, you can learn something, but you end up forgetting it quite easily.

AVOID SKIPPING BACK – 30% skipping back, save 20% time! – imagine you can’t go back – you will increase attention after you read and thought to yourself “I didn’t understand”, and if the book is good it will repeat the premise.

When brain is on 20 cycles per second then you’re in the “zone”.

METRONOM + POINTER!

First, when you start reading on a higher speed the comprehension drops, but if you force that speed the comprehension will rise up and exceed the previous one.

Eyerobics – open wide, close hard, blink hard, left-right look, all around look, look to the window.

MIN – MAX method – min 1 page per day, max 50, normal 15, but the point is to read everyday!

Check this out: Timothy Ferris: The 4-hour workweek

Pareto principle – 80/20 – 20% efforts => 80% results. 80% additional efforts => 20% results

Tim Doner speaks > 20 languages! Benny Lewis – Fluent in three months

I want to succeed in this course because:

  • I want to be able to read all the books I, now, don’t have the time to read both techincal and fictional
  • I want to learn new things and retain as much information as possible as this will make me a better man, father, software engineer
  • I want to earn more by knowing more
  • I want to help others by knowing more stuff
  • I want to personally grow by knowing more

Neurons and synapses

Hose => Funnel => bucket – order of necessary upgrades goes backwards! So, first you have to improve your memory in your head (bucket) then increase the amount of info going in (funnel) and then increase the speed of increased data that’s going in (hose).

Superlearners create dense connections

Transform concepts and ideas into pictures => so we can remember them better.

Exercise: read an article and try to remember 10 things in a way that you connect them with pictures.

Image types:  fictional, personal, graphical, stereotypical

3 memory stages: encoding, storage, retrieval

30sec pause every 10mins, 1sec pause every paragraph!

Working memory – from this to next level => 1sec pause every paragraph
Short term mem – from this to next level => 30 sec pause every 10 min
Long term mem

Short term memory lasts for about 10 min and if we don’t commit (think git commit) it to a long term memory then we forget it (think git reset –hard HEAD).

High quality markers:

  • are details we can describe in 1-2 words
  • themselves encoded with rich detail
  • clearly & logically interconnected
  • emphasize answers not questions
  • more is better

Go for details => concepts (basically you go bottoms up, so that you remember details and then you connect them in a main story)

Creating markers is the real deal!, practice making detailed markers.

Pre-reading 2,3 sec per page! Make a pre-reading and remember just a few words and then when you start reading you’re eager to answer the questions you formed during pre-reading.

The adult learner requirements

  • use of prior experience and knowledge
  • clear goals and appropriate readiness
  • internal motivation and self direction
  • practical application in their lives
  • understanding of relevance
  • respect 

Adult students become ready to learn when they experience a need to learn in order to cope more satisfyingly with real-life tasks or problems.

Andragogy (Malcom Knowles): teaching adult people how to learn.

Imagine two or three separate columns on the page. Eyes are faster in jumping then in line movements. Jumps are called Sacades –  rapid movements of the eyes between fixation points.

Never ever go back in text. Reading with a card – cover up and drag down.

Push yourself!

Do tests with 250, 350, 500, 700 i 1000 WPM

No pain no gain bro!

If everything seems under control you’re not going fast enough!

Exercise: in 5 seconds do a pre-reading flash 3 times focusing first on left, then middle then right part.

There is no substitute for hard work.
~ T. A. Edison

Memory temple vs mind mapping

Mapping numbers 0-9 to words and then making a sentence out of them.

22-24 mins power nap (this I have been conducting for the past 2 months now and I recommend it to everyone!)

Refresh learned after 1 week, month, 3 months and you’ll never forget it!

Some apps that may help with speed reading: https://github.com/ds300/jetzt, http://www.spritzinc.com/ (and my blog post on Spritz).

Bottom line, my speed is now at a solid 450 WPM which is almost 100% more than when I started – yay for me! If you’re skeptic about this as I was (fearing your understanding will go down) just give it a try and decide for yourself if this is something worth pursuing – IMHO it is.

Books

A Short History of Nearly Everything – Bill Bryson

My favourite quotes from the book A Short History of Nearly Everything by Bill Bryson:

Once in a great while, and few times in history, a human mind produces observation so acute and so unexpected that people can’t quite decide which is more amazing, the fact or the thinking of it.

Scientists dealt with this paradox in the handiest possible way – they ignored it.

Sometimes world just isn’t ready for a good idea.

The good news appears is that it takes an awful lot to extinguish species. The bad news is good news can never be counted on.

Three stages in scientific discovery: 1: people deny that it’s true. 2: then they deny that it’s important. 3: finally they credit the wrong person.

It’s an unnerving thought that we may be the living universe’s supreme achievement and its worst nightmare simultaneously.

CodeProject, JavaScript

Simple official Spritz API usage

TL;DR: See it in action here or here, and official site here.

Spritz – change the way people read and make communication faster, easier, and more effective.

So, there has been a lot of buzz about this lately and today I too got my API key to test this out. I must say that using Spritz is really easy, and they have a very good documentation with examples so I will keep this short.

After you register to their developer program you will get your API key. A simple use case to get you started is to make a HTML document with the following content:

<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
	<script type="text/javascript">
        var SpritzSettings = {
            clientId: "4aac1453ff37b364f",
            redirectUri: "http://www.nikola-breznjak.com/codez/spritz/login_success.html",
        };
    </script>

 	<script type="text/javascript" src="spritz.min.js"></script>
</head>

<body>
    <h1>Spritz test</h1>

  	<div data-role="spritzer"></div>

    <div>This is some demo text that will be Spritzt</div>
  	</div>
</body>
</html>

Important things to note here are that Spritz uses jQuery and you have to use your clientId and put this rediretUri file to your server (on which you host the domain with which you registered your Spritz application).

A little more advanced example is here: http://www.nikola-breznjak.com/codez/spritz/ (you can just view the source of it and I’m sure you’ll know how to take it from there).

Worth noting is that there are some open source versions of this like Open Spritz, though I think this one is way better as it has whole research and the science behind it.

Using this on a simple HTML page was, well, simple. I tried to incorporate this into my wordpress blog (the one you’re reading right now), and though it works nicely when I put the code in the index.php file (the main template file which lists all of the posts), it does not work when I put the same exact code to the single.php (template for showing specific posts). The error that I’m getting in the latter case is this:

Unable to spritz: Unable to retrieve contentVersion, contentId=5343e07be4b063e2752c379b: HTTP call failed, status: 500, message: Internal Server Error

So, if someone got the same error, how did you go about it?

Books

The Cuckoo’s Calling – Robert Galbraith

My favourite quotes from the book The Cuckoo’s Calling by Robert Galbraith aka J.K.Rowling:

There were other routes to woman’s intimacy than to admire her figure in tight dress.

And the best plan is, as the popular saying was, to profit by the folly of others.

He’s about five fucking feet too short to model.

Lose some weight, he told Strike as a parting shot, and I’ll send you something XXL.

The dead can only speak through the mouths of those left behind, and through the signs they left scattered behind them.

He’s not sane, which isn’t to say he’s not a clever fucker.

CodeProject, PHP

POST JSON Data With PHP cURL wrapper class

PHP biceps cURL 🙂

Following is the PHP cURL wrapper class which I use to make GET and POST requests. The examples are below. Disclamer:  be sure that you have permission to scrape and use the content you’re after.

This code is also available on GitHub at this link: https://github.com/Hitman666/PHPcURLWrapper

Class code and simple GET request

//CurlWrapper_static.php

class CurlWrapper {
    private static $useragents = array(            
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; WOW64; Trident/4.0; SLCC1)",
        "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14"
    );

	private static $cookiesFile = "curlCookies.txt";

    private static function getUserAgent() {
    	$rand = rand(0, count(self::$useragents) - 1);

    	return self::$useragents[$rand];
    }

    public static function SendRequest($url, $ref = "", $type = "GET", $postData = "", $headers = "", $proxy = "") {
        $useragent = self::getUserAgent();

        $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_TIMEOUT,120);
		curl_setopt($ch, CURLOPT_USERAGENT, self::getUserAgent());

		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);

		curl_setopt($ch, CURLOPT_COOKIEJAR, realpath(self::$cookiesFile)); 
		curl_setopt($ch, CURLOPT_COOKIEFILE, realpath(self::$cookiesFile));

		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        //options
        if ($ref != "") {
            curl_setopt($ch, CURLOPT_REFERER, $ref);
        }

		if ($proxy != "") {
			curl_setopt($ch, CURLOPT_PROXY, $proxy);
		}

		if ($type == "POST"){
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
		}

		if ($headers != ""){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		}

        $result = curl_exec($ch);
		curl_close($ch);

		return $result;
	}
}

Simple GET request:

require("CurlWrapper_static.php");

$googleHTML = CurlWrapper::SendRequest('https://www.google.com');
echo $googleHTML;

If you’re a firm non-static lover here’s a “normal” class:

//CurlWrapper_nonStatic.php

class CurlWrapper{    
    private $_useragents = array(            
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; WOW64; Trident/4.0; SLCC1)",
        "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14"
    );

	private $_cookiesFile = "curlCookies.txt";

    private function getUserAgent(){
    	$rand = rand(0, count($this->_useragents));

    	return $useragents[$rand];
    }

    public function SendRequest($url, $ref = "", $type = "GET", $postData = "", $headers = "", $proxy = "") {
        $useragent = $this->getUserAgent();
        echo $useragent;

        $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_TIMEOUT,120);
		curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);

		curl_setopt($ch, CURLOPT_COOKIEJAR, realpath($this->_cookiesFile)); 
		curl_setopt($ch, CURLOPT_COOKIEFILE, realpath($this->_cookiesFile));

		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        //options
        if ($ref != "") {
            curl_setopt($ch, CURLOPT_REFERER, $ref);
        }

		if ($proxy != "") {
			curl_setopt($ch, CURLOPT_PROXY, $proxy);
		}

		if ($type == "POST"){
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
		}

		if ($headers != ""){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		}

        $result = curl_exec($ch);
		curl_close($ch);

		return $result;
	}
}

How to use it with simple GET request:

require("CurlWrapper_nonStatic.php");

$curl = new CurlWrapper();
$googleHTML = $curl->SendRequest('https://www.google.com');
echo $googleHTML;

JSON POST request

Here’s an example of sending a JSON POST request to imaginitive URL ‘http://service.com/getData.json’ with some data array:

	require("CurlWrapper_static.php");

	$cookieSettingUrl = 'http://service.com/';
	$cookie = CurlWrapper::SendRequest($cookieSettingUrl);

	$data = array(
		"year" => 2014,
		"day" => 3,
                "month" => 4,
		"id" => 20
    );
	$postData = json_encode($data);

	$jsonUrl = 'http://service.com/getData.json';
	$headers = array('Accept: application/json','Content-Type: application/json');

	$resultsHTML = CurlWrapper::SendRequest($jsonUrl, $cookieSettingUrl, "POST", $postData, $headers);
	$resultsJson = json_decode($resultsHTML);
	var_dump($resultsJson);

Important to note is that you have to add proper $headers array, and that you json_encode your data array as shown when POSTing to a service which expects JSON data.

Cookies

The reason why I first used these two lines:

$cookieSettingUrl = 'http://service.com/';
$cookie = CurlWrapper::SendRequest($cookieSettingUrl);

is to set any cookies (and you will find that some services do this) that may be needed to be sent along with the request to ‘http://service.com/getData.json’. Cookies are set to ‘curlCookies.txt’ in the CurlWrapper_* class. You can change this to your liking, and you have to make sure that you set proper permissions for this file.

Hope this proves useful to someone.

Page 48 of 51« First...102030«47484950»...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