2016년 12월 24일 토요일

unordered_set / unordered_map with custom object in C++

http://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key



To be able to use std::unordered_map (or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
  1. A hash function; this must be a class that overrides operator() and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash template for your key-type.
  2. A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator(), or as a specialization of std::equal, or – easiest of all – by overloading operator==() for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
 
struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      using std::size_t;
      using std::hash;
      using std::string;

      // Compute individual hash values for first,
      // second and third and combine them using XOR
      // and bit shifting:

      return ((hash()(k.first)
               ^ (hash()(k.second) << 1)) >> 1)
               ^ (hash()(k.third) << 1);
    }
  };

}
With this in place, you can instantiate a std::unordered_map for the key-type:
int main()
{
  std::unordered_map<Key,std::string> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}
It will automatically use std::hash as defined above for the hash value calculations, and the operator== defined as member function of Key for equality checks.
If you don't want to specialize template inside the std namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
    using std::size_t;
    using std::hash;
    using std::string;

    return ((hash()(k.first)
             ^ (hash()(k.second) << 1)) >> 1)
             ^ (hash()(k.third) << 1);
  }
};

int main()
{
  std::unordered_map<Key,std::string,KeyHasher> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value and hash_combine function template from the Boost library. The former acts in a similar way as std::hash for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include 

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
      using boost::hash_value;
      using boost::hash_combine;

      // Start with a hash value of 0    .
      std::size_t seed = 0;

      // Modify 'seed' by XORing and bit-shifting in
      // one member of 'Key' after the other:
      hash_combine(seed,hash_value(k.first));
      hash_combine(seed,hash_value(k.second));
      hash_combine(seed,hash_value(k.third));

      // Return the result.
      return seed;
  }
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
    template <>
    struct hash<Key>
    {
        size_t operator()( const Key& k ) const
        {
            // Compute individual hash values for first, second and third
            // http://stackoverflow.com/a/1646913/126995
            size_t res = 17;
            res = res * 31 + hash()( k.first );
            res = res * 31 + hash()( k.second );
            res = res * 31 + hash()( k.third );
            return res;
        }
    };
}

2016년 12월 18일 일요일

random number generation in C++. with better distribution.

random number generation in C++.  with better distribution.


int getRand() //generater random number between 1 to 5
{
    std::default_random_engine generator;
    generator.seed(std::random_device()());
    std::uniform_int_distribution distribution(1,5);
    int randomNumber = distribution(generator);
    return randomNumber;
}

2016년 12월 8일 목요일

firefox cache management

http://lifehacker.com/5687850/speed-up-firefox-by-moving-your-cache-to-ram-no-ram-disk-required

Since your computer can access data in RAM faster than on a hard drive, moving cached data to RAM can improve your page load times. In Firefox, all you need to do to move your caches to RAM is open up about:config and make a few tweaks.
Once you get into about:config, type browser.cache into the filter bar at the top. Find browser.cache.disk.enable and set it to false by double clicking on it. You'll then want to set browser.cache.memory.enable to true (mine seemed to already be set as such), and create a new preference by right clicking anywhere, hitting New, and choosing Integer. Call the preference browser.cache.memory.capacity and hit OK. In the next window, type in the number of kilobytes you want to assign to the cache (for example, typing 100000 would create a cache of 100,000 kilobytes or 100 megabytes). A value of -1 will tell Firefox to dynamically determine the cache size depending on how much RAM you have.

2016년 12월 7일 수요일

linux iptables

https://www.rackaid.com/blog/how-to-block-ssh-brute-force-attacks/

Methods to Stop SSH Brute Force Attacks
There are basically four approaches to dealing with SSH brute force attacks:

    Restrict SSH access by IP address
    Change SSH to another Port
    Use intrusion prevention tools to dynamically block access
    Rates limit SSH sessions using IPTables

All of these approaches have theirs benefits and drawbacks.

While restricting SSH access by IP address is the most secure method, such restrictions are often not possible when dealing with web hosting services as you have multiple users with constantly changing IP addresses.

Changing the SSH port may defeat bot scans but does little against targeted attacks.  Also, this usually just frustrates your users.

Intrusion prevention tools like fail2ban and denyhosts have their place but they are subject to log based attacks.  These tools essential analyze logs using regular expressions.  Hackers have found ways around both of these tools in the past.

Lastly, you have a great tool to block ssh brute force attacks right on your server: IPtables.
Using IPtables to Stop SSH Brute Force Attacks

I like to think of this approach similar to flow rates with pipes.  Bigger pipes allow more water to flow.  Smaller pipes can handle less water.

control ssh access with iptables

To block a SSH brute force attack, we just need to slow down the flow of requests. We can do this by rate-limiting requests to SSH with iptables.

Essentially, we create a smaller pipe for new SSH sessions.  This slows brute force attacks to a point where they become ineffective.

The iptables rules are relatively simple.
   
/usr/sbin/iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --set
/usr/sbin/iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent  --update --seconds 60 --hitcount 4 -j DROP

This rule will block an IP if it attempts more than 3 connections per minute to SSH. Notice that the state is set to NEW. This means only new connections not established ones are impacted. Established connections are the result of a successful SSH authentication, so users who authenticate properly will not be blocked.

If you need to see what’s being done, you may want to log these drops. You can do so by setting up a log rule and then using these rules instead.
   
/sbin/iptables -N LOGDROP
/sbin/iptables -A LOGDROP -j LOG
/sbin/iptables -A LOGDROP -j DROP
iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --set
iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent  --update --seconds 60 --hitcount 4 -j LOGDROP



please use iptables-persistent; it's the easy way: Install iptables-persistent:

    sudo apt-get install iptables-persistent

After it's installed, you can save/reload iptables rules anytime:

    sudo /etc/init.d/iptables-persistent save
    sudo /etc/init.d/iptables-persistent reload

2016년 12월 4일 일요일

Ubuntu joypad setting

install jstest for joypad
sudo apt-get install jstest-gtk

test if joypad is working by following command.
jstest /dev/input/js0

ubuntu 16.04 medafen sound fix

Ubuntu fix mednafen broken sound

setting file is created under .mednafen in user directory after a user executes mednafen once
//mednafen-09x.cfg

The configuration would be:

;Select sound output device.
sound.device sexyal-literal-default

;Select sound driver.
sound.driver SDL

sublime close without confirmation

  Close without confirm   Yes, you can just write a plugin to set the view as scratch and close it. Then create a keybinding for that c...