tisdagen den 18:e juni 2013

C++11 Overloading operators for strongly typed enumerations.

C++11 has support for strongly typed enumerations. To overload for example &, | and > I have provided an example below:

  enum class CollisionType
  : Uint16 { NONE = 0x0000,
      DYNAMIC = 0x0001,
      STATIC = 0x0002,
      KINEMATIC = 0x0004,
      SENSOR = 0x0008,
      BULLET = 0x0010,      
      };

  inline constexpr CollisionType
  operator&(CollisionType l, CollisionType r){
    return static_cast<CollisionType>(static_cast<Uint16>(l) & static_cast<Uint16>(r));
  }

  inline constexpr bool
  operator>(CollisionType l, int n){
    return static_cast<Uint16>(l) > n;
  }

  inline constexpr CollisionType
  operator|(CollisionType l, CollisionType r){
    return static_cast<CollisionType>(static_cast<Uint16>(l) | static_cast<Uint16>(r));
  }

tisdagen den 4:e juni 2013

Indent whole buffer with a keystroke

(defun my-indent-region ()
  "Mark whole buffer and indent."
  (interactive)
  (save-excursion
    (mark-whole-buffer) 
    (if (region-active-p)
 (progn
   (indent-region (point-min) (point-max))))))

Declare the function in your .emacs file. then bind it with:


(global-set-key (kbd "<f8>") 'my-indent-region)

A way to use C++11 variadic template functions

  
namespace Log {
    inline void write() {
      std::cout << std::endl;
    }

    template<typename T, typename ...U>
    inline void write(T head, U... tail){
      std::cout << head;
      Log::write(tail...);
    }
  }
Overload an empty write() to end recursion. Then you can use it like this:

Log::write("test", 10.0f, 'd'); 

Log::write(1,2,3,4,5,6,7);

onsdagen den 19:e december 2012

List running process id's on linux

This is how to list all running process id's (pids) in C. Every numbered dir in /proc correlates to a running process. Open the file status to get more detailed information about the process.


#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

int main(int argc, char **argv){
  DIR *dp;
  struct dirent *ep;
  char *num = "0123456789";

  dp = opendir("/proc");
  if(dp != NULL){
    while((ep = readdir(dp))){
      if(strspn(ep->d_name, num)){
        printf("%s\n", ep->d_name);
      }
    }
    closedir(dp);
  } else {
    perror("Couldn't open the directory");
  }
  return 0;
}

söndagen den 18:e december 2011

Generic Makefile for Go

If you want to have a directory with alot of Go files for testing you can use this Makefile.

# Generic Makefile for GO
ifeq ($(GOARCH),386)
O:=8
else
O:=6
endif

GC=${O}g
LD=${O}l

GO_FILES = $(wildcard *.go)
GO_PRGS = $(basename $(GO_FILES))
GO_OBJS = $(addsuffix .$O, $(GO_PRGS))

all: $(GO_PRGS)

$(GO_PRGS): $(GO_OBJS)
        $(LD) -o $@ $@.$O;

$(GO_OBJS): %.$O: %.go
        $(GC) $<
 

clean:
        rm $(GO_OBJS) $(GO_PRGS)


torsdagen den 29:e september 2011

Gstickies a notes program for gnome released under GPLv2

You can find it for free at GitHub:

https://github.com/QubeX2/gstickies























//QubeX2

Tips #2 Add javascript: click() prototype to HTMLElement's for Firefox etc.

If you want to use the click() method on a HTML element on a webbrowser other than Microsoft's Internet Explorer you can add this code at the start somewhere of your code.

if(typeof HTMLElement!='undefined'&&!HTMLElement.prototype.click)
    HTMLElement.prototype.click=function(){
        var evt = this.ownerDocument.createEvent('MouseEvents');
        evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
        this.dispatchEvent(evt);
    }


//QubeX2

onsdagen den 28:e september 2011

Problem #1 How to encrypt data between PHP and C#

One important note. When you want to encrypt the data on the
C# side you have to pad the iv to length of 32.


In PHP encrypt data like this:
<?php
$iv
"01234567890123456789012345678901";
$key"this is they key"; 

$text"This text will be encrypted..."; 
$bsize mcrypt_get_block_size(MCRYPT_RIJNDAEL_256MCRYPT_MODE_CBC);
$pad$bsize - (strlen($text) % $bsize);
$text .= str_repeat(chr($pad), $pad);
$encrypted mcrypt_encrypt(MCRYPT_RIJNDAEL_256$key$textMCRYPT_MODE_CBC$iv);
$enc_text base64_encode($encrypted);
 

echo "$enc_text";

/* the output
 *  MCfBJe4H7U+9Qb48RkHlXUt1/it10mx+TG7lrCUjO4w=
 */
?>


In C# decrypt data like this:

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Encryption
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            string enc_text = @"MCfBJe4H7U+9Qb48RkHlXUt1/it10mx+TG7lrCUjO4w=";
            string iv = "01234567890123456789012345678901";
            string key = "this is they key";
            byte[] bytes = Base64_Decode(enc_text);
            Console.WriteLine(Decrypt(bytes, key, iv));
        }

        public static byte[] Base64_Decode (string str)
        {
            return Convert.FromBase64String (str);
        }
        
        public static string Decrypt (byte[] cipher, string key, string iv)
        {
            string retVal = "";
            UTF8Encoding encoding = new UTF8Encoding ();
            byte[] Key = encoding.GetBytes (key);
            byte[] IV = encoding.GetBytes (iv);
            using (RijndaelManaged rj = new RijndaelManaged ()) {
                try {
                    rj.Padding = PaddingMode.PKCS7;
                    rj.Mode = CipherMode.CBC;
                    rj.KeySize = 256;
                    rj.BlockSize = 256;
                    rj.Key = Key;
                    rj.IV = IV;
                    using (MemoryStream ms = new MemoryStream (cipher)) {
                        using (CryptoStream cs = new CryptoStream (ms, rj.CreateDecryptor (Key, IV), CryptoStreamMode.Read)) {
                            using (StreamReader sr = new StreamReader (cs)) {
                                retVal = sr.ReadLine ();
                            }
                        }
                    }
                } finally {
                    rj.Clear ();
                }
            }
            return retVal;
        }
    }
}

//QubeX2

Tips #1 Batch resize images with Bash

find ./ -iname "*.jp*" -exec /-mogrify -resize 800 {} \;

The argument -iname makes find match case insensitive.
The argument -exec continues until it finds a backslash escaped ; eg. "\;".

Good luck
/QubeX2

torsdagen den 24:e februari 2011

Att använda Javascript i Windows Forms

Ett litet exempel på hur man kan använda Javascript i Windows Forms

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSScriptControl;

namespace Blog.Script
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ScriptControlClass script = new ScriptControlClass();
            script.Language = "JScript";
            script.AddCode("var v = 10;");

            StringBuilder js = new StringBuilder();
            js.AppendLine("function max(x,y){ return x > y ? x : y; }");
            js.AppendLine("max(v,3);");

            string result = "";

            try
            {
                result = script.Eval(js.ToString()).ToString();
            }
            catch
            {
                result = script.Error.Line + "," + script.Error.Column + " " script.Error.Description;
            }
            MessageBox.Show(result);
        }
    }
}