28 Eylül 2016 Çarşamba

gethostbyaddr metodu

Giriş
Big endian yani network formatındaki ip değerini string'e çevirir.

Metod aşağıdaki gibi çalışır.
UDP sunucu soketinde bize veri gönderenin adresini almak için şöyle yaparız.
struct sockaddr_in clientaddr; /* client addr */
int clientlen = sizeof(clientaddr);
int n = recvfrom(sockfd, ...,...,...,
     (struct sockaddr *) &clientaddr, &clientlen);
clientaddr nesnesindeki ip adresini string'e çevirmek için kullanırız.
Şöyle yaparız.
struct hostent *hostp;
hostp = gethostbyaddr((const char *)&clientaddr,
          sizeof(clientaddr), AF_INET);
if (hostp != NULL) {
  ...
}
Parametre
Parametre açıklaması şöyle
[...] The host address argument is a pointer to a struct of a type depending on the address type, for example a struct in_addr * (probably obtained via a call to inet_addr(3)) for address typeAF_INET.
Hata Kodu
Hata kodu errno değişkeninde değil h_errno değişkeninde saklanır. Açıklaması şöyle.
[...[ The gethostbyname() and gethostbyaddr() functions return the hostent structure or a null pointer if an error occurs. On error, the h_errno variable holds an error number.
Hata kodları şöyle
The variable h_errno can have the following values:
  • HOST_NOT_FOUND
    The specified host is unknown.
  • NO_ADDRESS or NO_DATA
    The requested name is valid but does not have an IP address.
  • NO_RECOVERY
    A nonrecoverable name server error occurred.
  • TRY_AGAIN
    A temporary error occurred on an authoritative name server. Try again later.

Hibernate SQLQuery Sınıfı

Giriş
Native SQL cümlesi çalıştırmamızı sağlar.

constructor
Şöyle yaparız.
String query = "SELECT x, y, z FROM ...";
SQLQuery query = session.createSQLQuery(query);
list metodu
Şöyle yaparız.
List result = query.list();
list metodu
Şöyle yaparız.
public List<T> findBySQL(String sql, String... params){
  SQLQuery query = getSession().createSQLQuery(sql);
  query.addEntity(clazz);
  for (int i = 0; i < params.length; i++){
    query.setParameter(i, params[i]);
  }
  List<T> list = query.list();
  return list;
}
setParameter metodu - Basit sql
Şöyle yaparız.
String var = ...;
String str = "select * from Food f where f.resname = ?";
query.setParameter(0,var);
setParameter metodu - like
Değişkenin önüne ve  sonuna % karakterini ekleriz. Şöyle yaparız.
String var = ...;
String str = "select * from Food f where f.resname like ? ";query.setParameter(0,"%"+var+"%");



22 Eylül 2016 Perşembe

Tail Call - Klasik Recursion

Giriş
Tail Call aynı zamanda Tail Recursion olarak da bilinir. Özel bir çeşit öz yinelemeli çağrıdır. Açıklaması şöyle
Tail recursion happens if a function, as its last operation, returns the result of calling itself. Tail recursion is easier to deal with because rather than having to jump to the beginning of some random function somewhere, you just do a goto back to the beginning of yourself, which is a darned simple thing to do.
Şöyledir.
sub foo (int a, int b) {
  if (b == 1) {
    return a;
  } else {
    return foo(a*a + a, b - 1);
  }
}
Bu kod derleyici tarafından şuna çevrilir.
sub foo (int a, int b) {
  label:
    if (b == 1) {
      return a;
    } else {
      a = a*a + a;
      b = b - 1;
      goto label;
   }
}
C++
Elimizde şöyle bir kod olsun.
void test2(int curIndex){
  if(curIndex == size) return;
  s+=A[curIndex];
  test2(curIndex+1);
}
Kod şuna çevrilir.
void test2(int curIndex){
  while(true)
  {
    if(curIndex == size) return;
    s+=A[curIndex];
    curIndex = curIndex + 1;
  }
}
Tail Recursion'ı Kaldırmak
Bazı kodlar Tail Recursion'ı call stack yüzünden kaldırıyor. Öreğin Quicksort. Açıklaması şöyle
Quicksort takes O(N2) time in the worst case.

In that worst case, if each call recurses separately on both halves, it also takes O(N) stack space.

That is too much space to waste on the call stack.

Practical implementations of quicksort recurse on the smaller half, and then loop to sort the larger half. This limits the worst case stack consumption to O(log N) in the worst case, which is quite reasonable.



21 Eylül 2016 Çarşamba

Simplified Wrapper and Interface Generator - SWIG

C++'tan kod üretmek
Header dosyalarını dahil etmek için şöyle yaparız.
%module example
 %{
 /* Includes the header in the wrapper code */
  #include "myheader.h"
 %}
...
-perl5 seçeneği
C/C++ kodunu Perl'den çağırmak için wrapper üretir.

15 Eylül 2016 Perşembe

Reliable UDP

Ne Zaman Kullanılır
Açıklaması şöyle.
The main reason people would choose UDP/RUDP over TCP is because of how TCP handles out of order packets. You may only care about the most recently received packet and want that as soon as it arrives. In TCP, if your most recently received packet is not the next one in sequence, TCP will not deliver it to you until everything else has been received.
If you need to guarantee sequence and delivery then just use TCPIf you need to guarantee sequence and delivery plus get the most recent packets as soon as they arrive, then use RUDP.
Genelde video gönderiminde kullanılır.

8 Eylül 2016 Perşembe

boost


boost ile kullandığım bazı sınıfları not olsun diye aşağıya ekliyorum.
boost ve namespace
Boost kendi içindeki sınıfları saklamak için genellikle namespace içinde başka namespace'ler açıyor. Dışarı açılması istenilmeyen sınıflar içerdeki namespace'e yerleştiriliyorlar. Örnek:
namespace super_cool_library {

    namespace detail {
        class bar { };
    }

    class foo : detail::bar {
    };

}
boost algorithm
join işlemi için String Algoritmaları yazısına bakabilirsiniz.

boost adaptor
Listeyi 4'er 4'er dolaşmak için
#include <boost/range/adaptor/sliced.hpp>
#include <vector>
#include <iostream>

int main(int argc, const char* argv[])
{
    std::vector<int> input={1,2,3,4,5,6,7,8,9};
    const int N = 4;
    using boost::adaptors::sliced;
    for (auto&& e: input | sliced(0, N))
        std::cout << e << std::endl;
}

boost asio
acceptor sınıfı
acceptor sınıf içine bir socket alır ve async_accept metodu çağırılır. Örnek:

void Server::Accept() {
  socket_.reset(new boost::asio::ip::tcp::socket(*io_service_));
  acceptor_.async_accept(*socket_,
                         boost::bind(&Server::HandleAccept, this, boost::asio::placeholders::error));
}

void Server::HandleAccept(const boost::system::error_code& error) {
  if (!error) {
    // TODO
  } else {
    TRACE_ERROR("Server::HandleAccept: Error!");
  }
  Accept();
}


boost atomic
Konu için Atomik İşlemler yazısına bakabilirsiniz.

boost bind
boost bind eğer bir nesnenin metoduna function pointer olarak kullanılacaksa, ikinci parametre olarak nesneyi geçmek gerekir. Örnek:
bind(&client::passwordAttemptCallBack, &myClient, _1)

boost datastructures
Bu projede envai çeşit heap veri yapısı var. En kolayı balanced binary heap.

fibonacci_heap
Örnek:

tpedef boost::heap::fibonacci_heap<struct c*, boost::heap::compare<compare>> myheap;
paring_heap
Örnek:

typedef boost::heap::pairing_heap<struct c, boost::heap::compare<my_compare> > myheap;
.
boost exceptionboost exception altındaki diagnostic_information sınıfı ile exception string'e çevirilebiliyor. Örnek:

boost flat_map
flat_map ile map arayüzüne sahip ancak arka tarafta array kullanan bir veri yapısı sunuluyor.

boost functional
hash alabilme yeteneği sunuyor. hash açıklamasını buraya taşıdım.

boost future
future ve promise bir şekilde beraber kullanılıyorlar sanırım. 

wait_for




boost::promise<void> p;
boost::future<void> f = p.get_future();
boost::thread t([&]() { invoke(request, response); p.set_value(); });
bool did_finish = (f.wait_for(boost::chrono::milliseconds(timeout)) == boost::future_status::ready)

boost generator iterator
Verilen generator kullanılarak bir input iterator yaratılır. Infinite sequence yapma örneği:



boost heap
priority heap örneği buradan geldi.

boost interval container library
boost::icl::interval_map için örnek bulmam lazım.

boost interprocess

Örneği buradan aldım.

#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstring>
#include <cstdlib>
#include <string>
using namespace boost::interprocess;

//Yazma için
//Create a native windows shared memory object.

windows_shared_memory shm (create_only, "MySharedMemory", read_write, 1000);

//Map the whole shared memory in this process
mapped_region region(shm, read_write);

//Write all the memory to 1
std::memset(region.get_address(), 1, region.get_size());

//Okuma için
//Open already created shared memory object.

windows_shared_memory shm (open_only, "MySharedMemory", read_only);

//Map the whole shared memory in this process
mapped_region region(shm, read_only);

//Check that memory was initialized to 1
char *mem = static_cast<char*>(region.get_address());
Buradaki örnekte ise windows_shared_memory yerine daha portable olduğunu sandığım bir başka kod kullanılmış.


#include "boost/interprocess/file_mapping.hpp"
#include "boost/interprocess/mapped_region.hpp"
using namespace boost::interprocess;

//Create a shared memory object.
file_mapping m_file("MySharedMemory", read_write);

//Map the whole shared memory in this process
mapped_region region(file_mapping, read_write);

//when done
file_mapping::remove("MySharedMemory");
Örnekte ise  memory mapped file üzerinde karakter karakter dolaşma var.

boost::irange
Range başlıklı yazıya bakınız.

boost iterator_adaptor
Verilen iki range'i birleştiren bir iterator adaptor örneği burada. Bir başka örnek ise burada.

iterator_adaptor tanımlamak için kullanılan kod aşağıdakine benzer.

class myiterator : public boost::iterator_adaptor<CRTP,iterator,iterator::value_type>
{
}

CRTP , Curiously recurring template pattern anlamına gelir. İkinci parametre gerçek iterator, üçüncü parametre ise iterator'ün döndürdüğü veri tipini anlamına gelir.
boost I/O kütüphanesi
Bu konu ile ilgili yazıları Boost I/O kütüphanesi başlıklı yazıya taşıdım.

boost::lock_guard
Bu konu ile ilgili Posix Eşzamanlılık Yapıları başlıklı yazıya göz atabilirsiniz.

boost math distribution
normal distribution
Örnek:



boost program_options
Komut Satırı Parse Etme yazısına bakılabilir.

boost range adaptors
boost range adaptors ile bir range dönüştürülerek başka bir range elde ediliyor.
Aşağıdaki örneği buradan aldım ve dönüşümü gösteriyor.

boost optional
Konuyu Nullable ve Optional başlıklı yazıya taşıdım.

boost scoped_ptr
std::auto_ptr'nin tersine release metodu yoktur ve pointer başka bir değişkene aktarılamaz.
boost::scoped_array de aynı mantıkla çalışır ancak array veri yapılarını "delete []" ile siler.


boost tuple
std::tuple çıktıktan sonra belki gerek kalmadı ancak örnek olsun diye aldım.
#include <boost/fusion/include/boost_tuple.hpp>
boost::tuple< std::string, int > t = boost::make_tuple( "foo", 42 );

 boost unit
boost unit kütüphanesi stream ile gayet iyi çalışıyor ancak printf gibi metodlarla çalışmıyor. Çalıştırmak için aşağıdaki örnek kullanılabilir.


3 Eylül 2016 Cumartesi

Apache Hive

Giriş
Hive HDF veya AWS S3 ile çalışabilir. Açıklaması şöyle
Apache Hive that works as a data warehouse system to query and analyze large datasets stored in the HDFS (Hadoop Distributed File System) or Amazon S3
Hive Dizin Kullanır
Hive HDF veya AWS S3 ile çalışabilir. Açıklaması şöyle
Hive is a simple directory-based design where actual data files are getting stored at the folder/directory level in HDFS. ...Hive keeps track of data at the folder level not in actual data files. 

Because of the directory-based model in Hive, listings are much slower, renames are not atomic, and results are eventually consistent. To work with data in a table, Hive needs to perform file list operations and this causes a performance bottleneck while executing SQL queries. 
Partitioning
Açıklaması şöyle
Hive partitioning can be done by dividing a table into related groups based on the values of a particular column like date, city, country, etc. Partitioning reduces the query response time in Apache Hive as data is stored in horizontal slices. In Hive partitioning, partitions are explicit and appear as a column and must be given partition values. 

Hive Kabuğu
Kabuk çalışırken > prompt karakterini görürüz

select
Örnek
Şöyle yaparız
hive> Select * from OrderData;
Örnek
Şöyle yaparız.
hive (default)> select * from tbl;
OK
1   2   3
1   3   4
2   3   4
5   6   7
8   9   0
1   8   3
Time taken: 0.101 seconds, Fetched: 6 row(s)
Hive Komutu
-e seçeneği
SQL çalıştırır. Şöyle yaparız.
1) hive -e "select ... from table where col1 between a and b"

AND.

2) hive -e "select ... from table where col >= a and col1 <= b"

1 Eylül 2016 Perşembe

GoF - Template Method Örüntüsü

Not : GoF Tasarım Örüntüleri yazısına bakabilirsiniz.

Template Method - Davranışsal Örüntü
Template Method az kullanılan örüntülerden bir tanesi. Açıklamasındaki önemli nokta şu
...behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure...
Yani algoritmanın iskeletini bir template metod tanımlıyor.

1. Adımlar virtual metodlar olmalıdır.
2. Kalıtan sınıfta adımları gerçekleştiren metodlar genellikle public değildir.

C++
Şöyle yaparız. Kalıtım ve public olmayan metodlara dikkat etmek gerekir.
class B { 
public:
  virtual int f();
};

class D : public B { 
private: 
  int f(); 
}; 

void f() { 
  D d; 
  B* pb = &d; 
  D* pd = &d; 
  pb->f();     // OK: B::f() is public, 
               // D::f() is invoked
  pd->f();     // error: D::f() is private
} 
Java
Şöyle yaparız. addSpread () metodu kalıtan sınıfın gerçekleştireceği adımdır.
abstract class SandwichMaker<S extends Spread> {
  public void make(S spread) {
    toastBread();
    addSpread(spread);
    enjoy();
  }

  protected void toastBread() {
    System.out.println("...toasting bread");
  }

  protected abstract void addSpread(S spread);

  protected void enjoy() {
    System.out.println("this is yummy!");
  }
}