Is 42 ultimate answer for everyting?

The Blog

  • Join Us on Facebook!
  • Follow Us on Twitter!
  • LinkedIn
  • Subcribe to Our RSS Feed

Cloning HDD into SSD via dd

The easiest (probably the cheapest but longest) way to copy data from old HDD to new SSD/HDD:

1. Check disk using disk utility

iMac:~ shlee$ diskutil list
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *480.1 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:                  Apple_HFS Untitled                479.8 GB   disk0s2
/dev/disk1 (external, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *500.1 GB   disk1
   1:                        EFI EFI                     209.7 MB   disk1s1
   2:                  Apple_HFS Macintosh HD            459.2 GB   disk1s2
   3:                 Apple_Boot Recovery HD             650.0 MB   disk1s3
   4:       Microsoft Basic Data BOOTCAMP                40.0 GB    disk1s4

 2. Unmount target disk 

iMac:~ shlee$ diskutil unmountDisk /dev/disk0

Unmount of all volumes on disk0 was successful

3. run dd command to clone

iMac:~ shlee$ sudo dd if=/dev/disk1 of=/dev/disk0 bs=128m conv=noerror,sync
Password:
load: 0.83  cmd: dd 581 uninterruptible 0.06u 4.76s
3+0 records in
3+0 records out
402653184 bytes transferred in 381.353785 secs (1055852 bytes/sec)
load: 1.14  cmd: dd 581 uninterruptible 0.18u 15.74s
3365+0 records in
3365+0 records out
451642654720 bytes transferred in 59079.999325 secs (7644595 bytes/sec)
dd: /dev/disk0: end of device
3578+0 records in
3577+1 records out
480103985152 bytes transferred in 62748.253816 secs (7651272 bytes/sec)

 

Apache ReadMe

After a long time, came back to Apache:

Install
-------


- Unzip the Apache24 folder to c:/Apache24 (that is the ServerRoot in the config).
  Default folder for your your webpages is DocumentRoot "c:/Apache24/htdocs"

  When you unzip to an other location, change ServerRoot in the httpd.conf,
  and change in httpd.conf the Documenroot, Directories, ScriptAlias,
  also when you use the extra folder config file(s) change to your location there. 

Start apache in a DOS box:

>httpd.exe

Install as a service:

>httpd.exe -k install

ApacheMonitor:

Double click ApacheMonitor.exe, or put it in your Startup folder.



Upgrading
---------

- Upgrading from 2.2.x see: httpd.apache.org/docs/2.4/upgrading.html
  and see httpd.apache.org/docs/2.4/new_features_2_4.html .

- Updating from 2.3.x
  copy all the files over, except your changed .conf files.

just grabbed from a ReadMe.txt

Multiple WebBrowser Control to Login Automatically

If you want to make a console application that runs multiple web browsers to access a web site through automatic login.

You can make a simple threading application as follows:

using System;
using System.Threading;
using Application = System.Windows.Forms.Application;

namespace TestImageViewer
{
	class Program
	{
		private static int _winNumber;

		private const string WEB_HOST = @"http://localhost/";
		private const int NUMBER_OF_SCREEN = 2;

		private static readonly string[] studyPages =
			{
				WEB_HOST + @"/Pages/View/Default.aspx",
				WEB_HOST + @"/Pages/View2/Default.aspx",
			};

		private static void ThreadStart()
		{
			var loginPage = WEB_HOST + "/Pages/Login/Default.aspx";
			Application.Run(new TestBrowser(loginPage, studyPages[_winNumber], _winNumber, NUMBER_OF_SCREEN));
		}

		[STAThread]
		static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			for (int i = 0; i < studyPages.Length; i++)
			{
				var thread = new Thread(ThreadStart);
				thread.TrySetApartmentState(ApartmentState.STA);
				thread.Start();
				_winNumber = i;
				Console.WriteLine(@"Study #" + _winNumber);
				Thread.Sleep(500);
			}
		}
	}
}

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace TestImageViewer
{
	public class TestBrowser : Form
	{
		private WebBrowser _webBrowser1;

		private string _studyPage;
		private int _formNumber;
		private readonly int _numberOfScreen;

		private readonly int _minx, _miny, _maxx, _maxy;

		public TestBrowser(string loginPage, string studyPage, int formNumber, int numberOfScreen)
		{
			_minx = _miny = int.MaxValue;
			_maxx = _maxy = int.MinValue;

			_formNumber = formNumber;
			_numberOfScreen = numberOfScreen;

			foreach (Screen screen in Screen.AllScreens)
			{
				var bounds = screen.Bounds;
				_minx = Math.Min(_minx, bounds.X);
				_miny = Math.Min(_miny, bounds.Y);
				_maxx = Math.Max(_maxx, bounds.Right);
				_maxy = Math.Max(_maxy, bounds.Bottom);
			}

			OpenStudy(loginPage, studyPage);
			
		}

		public void OpenStudy(string loginPage, string studyPage)
		{
			_studyPage = studyPage;

			Application.EnableVisualStyles();

			var frm = new Form();
			frm.Width = _maxx / 6;
			frm.Height = _maxy / 3;
			frm.StartPosition = FormStartPosition.Manual;
			int yIndex = _formNumber / (3 * _numberOfScreen);
			if (_formNumber > (3 * _numberOfScreen) - 1)
				_formNumber -= (3 * _numberOfScreen) * yIndex;
			frm.Location = new Point(_formNumber * frm.Width, yIndex * frm.Height); 
			
			_webBrowser1 = new WebBrowser();
			frm.Controls.Add(_webBrowser1);
			_webBrowser1.Dock = DockStyle.Fill;
			_webBrowser1.DocumentCompleted += WebBrowser1OnDocumentCompleted;
			_webBrowser1.Navigate(loginPage);

			var ct = new Thread(
				delegate()
				{
					while (true)
					{
						string command = Console.ReadLine();
						switch (command)
						{
							case "close":
								frm.Invoke(new MethodInvoker(frm.Close));
								break;
							case "max":
								frm.Invoke(new MethodInvoker(
									delegate()
									{
										frm.WindowState = FormWindowState.Maximized;
									}));
								break;
							case "min":
								frm.Invoke(new MethodInvoker(
									delegate()
									{
										frm.WindowState = FormWindowState.Minimized;
									}));
								break;
							case "res":
								frm.Invoke(new MethodInvoker(
									delegate()
									{
										frm.WindowState = FormWindowState.Normal;
									}));
								break;
						}

					}
				});
			ct.Start();
			frm.Show();
			frm.Activate();
			Application.Run(frm);
			Environment.Exit(0);
		}

		private void WebBrowser1OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs webBrowserDocumentCompletedEventArgs)
		{
			HtmlDocument doc = _webBrowser1.Document;
			HtmlElement username = doc.GetElementById("UserName");
			HtmlElement password = doc.GetElementById("Password");
			HtmlElement submit = doc.GetElementById("LoginButton");
			username.SetAttribute("value", "id");
			password.SetAttribute("value", "pass");
			submit.InvokeMember("click");

			Thread.Sleep(3000);

			_webBrowser1.Navigate(_studyPage);
		}
	}
}
Yest, it's that simple.

First AngularJS

Very simple angular code:

1. angularjs.html

<!doctype html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script>
	<script src="app.js"></script>
  </head>
  <body ng-app="MyApp">
    <p>This is your first angular expression: {{ 1 + 2 }}</p>
	Enter your name: <input type="text" ng-model="name"></input>
	<p>Hello {{name | uppercase }}!</p>
	<div ng-controller="MyCtrl">
      <button ng-click="toggle()">Toggle</button>
      <p ng-show="visible">Hello World!</p>
    </div>
	<div ng-controller="User">
    <form ng-submit="submit()" novalidate>
      <label>Firstname</label>
      <input type="text" ng-model="user.firstname"/>
      <label>Lastname</label>
      <input type="text" ng-model="user.lastname"/>
      <label>Age</label>
      <input type="text" ng-model="user.age"/>
	  <p>{{ age }}</p> 
      <br>
      <button class="btn">Submit</button>
    </form>
    User Model: {{user}}
    <br>
    Form was submitted: {{wasSubmitted}}
  </div>
  </body>
</html>

2. app.js

var app = angular.module("MyApp", []);

app.controller("User", function($scope) {
  $scope.user = {};
  $scope.wasSubmitted = false;

  $scope.submit = function() {
    $scope.wasSubmitted = true;
  };
  
  $scope.age = (new Date() - (new Date('2001-01-01')).getTime()) / (86400000 * 365);//$scope.user.age;
});


function MyCtrl($scope) {
  $scope.visible = true;

  $scope.toggle = function() {
    $scope.visible = !$scope.visible;
  };
}

3. Output will look like:

This is your first angular expression: 3

Enter your name:

Hello TEST!

Hello World!

15.464767482052257

User Model: {"firstname":"test","lastname":"test","age":"12"}
Form was submitted: true 

Disable NSLog

I didn't realize NSLog can make app slow. Here is a good tip how to disable it.

Add following code at the .pch file:

#ifndef DEBUG
  #define NSLog(...) /* suppress NSLog when in release mode */
#endif

React Native

1. create a project

$ react-native init [Project Name]


-----

upgrade react-native

$ react-native upgrade


install react-native-web and use webpack

$ npm install --save react@0.14 react-dom@0.14 react-native-web
$ gulp webpack-dev-server

or

$ webpack index.js
$ wepack-dev-server => default http://localhost:8080/webpack-dev-server/

Useful resources:
React Native: Into a new world of rapid iOS development



https://facebook.github.io/react-native/docs/getting-started.html#content

https://github.com/mfikes/cljsrn-tvos/tree/master/rnt/Examples/2048

https://github.com/jondot/awesome-react-native

To run your app on iOS:
   cd d:\react\FirstProject
   react-native run-ios
   - or -
   Open d:\react\FirstProject\ios\FirstProject.xcodeproj in Xcode
   Hit the Run button
To run your app on Android:
   Have an Android emulator running (quickest way to get started), or a device connected
   cd d:\react\FirstProject
   react-native run-android

https://www.raywenderlich.com/126063/react-native-tutorial

https://rnplay.org/ leeksh


1. create an array with length of 16
var numbersObj = {},
    numbersArray = [];

// your existing for statement here
for (var i=0; i<data.length; i++) {
   var currentNumber = Math.floor(Math.random() * 100);

if (!numbersObj[currentNumber])
   // put the number in the object (as a key)
   numersObj[currentNumber] = true;
} else {
i--;
}


2. create a problem array
for (var i = 0; i < data.lenght; i++)
if (tileArray[
tileArray[i] = Math.floor(Math.random() * 100);
2. get random number from 0 to 100
randomNumber: function(){
    return Math.floor(Math.random() * 100);
  },

Import SQL data into Redis

Brief procedure to load data from SQL Server into Redis


1. download Redis from http://redis.io/download

2. .NET client https://github.com/StackExchange/StackExchange.Redis

3. run Redis

4. Usefule sites for Redis

http://bosoa.egloos.com/3871510 (real time application in Korean)

http://baijian.github.io/2013/10/12/import-data-from-mysql-to-redis.html (import data with file)

http://www.tobez.org/presentations/2011-NPW-redis.html#(1) Replacing Relational DB with Redis: a Case Study in Perl

http://db-engines.com/en/system/Memcached%3BMicrosoft+SQL+Server%3BRedis (comparison)

http://blogs.msdn.com/b/frcogno/archive/2014/11/14/microsoft-sql-server-meets-redis-an-elegant-logging-platform-at-your-doorstep.aspx

5. sql to json

D:\Redis>sqlcmd -S localhost\DB -U cc -P PASSWORD -i d:\redis\jsonOWLS.sql > tmp

6. import json data to redis

D:\Redis>redis-cli < tmp

7. query

redis 127.0.0.1:6379> get 80B6DA62-9C96-4204-9A9C-9CCA00C52A68

"[{\"ID\":\"F4398A75-2185-4B78-81D0-000055F6E8C3\"...}]"


.NET real time push application with SignalR

It's useful to implement real time application with automatic update when there are changes in the database. One of the promising way is using SignalR with ASP.NET framework.

1. Create a project with ASP.NET MVC

2. Add AspNet.SignalR.

PM> Install-Package Microsoft.AspNet.SignalR

3. if you are using .NET framework less than 4.5, you may need to get older version

PM> Install-Package Microsoft.AspNet.SignalR -Version 1.1.3

4. Add mew item "SignalR Hub Class"

5. Implement the hub as follows:

public class MyRisHub : Hub
    {
        public void BroadcastMessageToAll(string message)
        {
            Clients.All.newMessageReceived(message);
        }
        public void JoinAGroup(string group)
        {
            Groups.Add(Context.ConnectionId, group);
        }
        public void RemoveFromAGroup(string group)
        {
            Groups.Remove(Context.ConnectionId, group);
        }
        public void BroadcastToGroup(string message, string group)
        {
            Clients.Group(group).newMessageReceived(message);
        }
        public void Hello()
        {
            Clients.All.hello();
        }
    }

6. To implement client, get SignalR client -Version 1.1.3 if you are using older .NET

PM> Install-Package Microsoft.AspNet.SignalR.Client

7. Windows form application implemented as follows:

public partial class Form1 : Form
{
HubConnection hubConnection;
IHubProxy hubProxy;
public Form1()
{
InitializeComponent();
hubConnection = new HubConnection("http://localhost:3256/signalr/hubs");

hubProxy = hubConnection.CreateHubProxy("MyRisHub");
hubProxy.On<string>("newMessageReceived", (message) => AddTextToListBox(message));
hubConnection.Start().Wait();
}
private delegate void stringDelegate(string s);
private void AddTextToListBox(string text)
{
if (listMessage.InvokeRequired)
{
stringDelegate sd = new stringDelegate(AddTextToListBox);
this.Invoke(sd, new object[] { text });
}
else
{
listMessage.Items.Add(text);
}
}
private void button1_Click(object sender, EventArgs e)
{
hubProxy.Invoke("BroadcastMessageToAll", textBox1.Text).Wait();
}
}

8. run multiple clients to check updating all of them with same data.

ref. http://www.codeguru.com/columns/experts/how-to-push-data-from-server-to-client-using-signalr.htm


SingalR with Redis.docx (116.4KB)

Node.js Web App to return Youtube Search Result as JSON

It's an experimental code using express

var express = require('express');
var app = express();

app.use(express.bodyParser());

var quotes = [
  { url: "https://www.googleapis.com/youtube/v3/search?key=[]&part=snippet,id&order=date&maxResults=50&type=video"},
  { url: "https://www.googleapis.com/youtube/v3/search?key=[]&channelId=[]&part=snippet,id&order=date&maxResults=50&type=video"},
  { url: "https://www.googleapis.com/youtube/v3/search?key=[]&q=[]&part=snippet,id&order=date&maxResults=50&videoDefinition=high&type=video"}
];

app.get('/', function(req, res) {
        res.json(quotes);
});

app.get('/quote/random', function(req, res) {
        var id = Math.floor(Math.random() * quotes.length);
        var q = quotes[id];
        res.json(q);
});

app.get('/quote/:id', function(req, res) {
        if(quotes.length <= req.params.id || req.params.id < 0) {
                res.statusCode = 404;
                return res.send('Error 404: No quote found');
        }
        var q = quotes[req.params.id];
        res.json(q);
});


app.post('/quote', function(req, res) {
        if(!req.body.hasOwnProperty('author') ||
        !req.body.hasOwnProperty('text')) {
                res.statusCode = 400;
                return res.send('Error 400: Post syntax incorrect.');
        }

        var newQuote = {
                url: req.body.author
        };

        quotes.push(newQuote);
        res.json(true);
});

app.delete('/quote/:id', function(req, res) {
  if(quotes.length <= req.params.id) {
    res.statusCode = 404;
    return res.send('Error 404: No quote found');
  }

quotes.splice(req.params.id, 1);
  res.json(true);
});

app.listen(process.env.PORT || 80);