Friday, November 30, 2012

Memory Layout for C variables

Here's a layout of memory in c for short and int variables (on 64bit OS compiled with -m32 and -m64 switch). In actual program variables are declared in reverse order than shown on images.

For this image, upper table, declaration was short, short, int, int and for the lower table declaration was: int, short, int, short.


This is how c would layout a long and int combination.

Saturday, November 17, 2012

Convert NSDate to SQLite timestamp

If you used Core Data with SQLite database you might noticed that dates are stored as number of seconds since 2001-01-01 00:00:00.

I made this NSDate to SQLite timestamp online converter hoping that it might be useful to you.

Enter date as yyyy-mm-dd hh:mm:ss

Friday, November 9, 2012

Add Core Data to Single View Application Tutorial (View-based application)

This post is written by beginner for beginners so there will be no in depth explanations. The purpose is to equip your app with Core Data as quickly as possible. You can use it to add Core Data to new or existing application.
As you might noticed, there is no built in template for single view application that integrates Core Data. To achieve such a capability we have to do few easy steps:
  1. create Entity with attributes and relationships to represent of our data (you can think of this as creating database layout)
    • create Entity object classes
  2. add Core Data framework to our TARGET (use pre-written tools to make our life easier)
  3. implement necessary code to allow our ViewController to communicate with database.
In this post I'll explain only how to access data in database.
At the end of this tutorial you'll end with application that outputs all your database rows in text view like this:


So lets begin.

0. Create new Single View Application

This tutorial is done on Xcode Version 4.4.1, so some of the screenshots may differ from those on your machine.
If you have existing application skip to step 1.


Write down Product Name and select Automatic Reference Counting



1. Create Entity

In this part of tutorial we'll create model to represent our data. There's also a few new terms which I'll try to explain using database notation.

You can think of Core Data as a middlemen between your application and your data (usually stored as SQLite database).
Model is collection of entities. Entity is blueprint for your objects with its attributes and relationships . This two lines can be thought as a Model is your database. It is consisted of tables - entities, and each row in table is object with its attributes (each attribute is represented as column or relationship in table).

Perhaps, if we want to build application that holds information about Star Trek androids we might create database that contains only one table MrDataEntity and three columns: androidId , androidName , productionDate .


Now lets create our MrDataModel. Go on and create new file as shown bellow.




New file will appear in your projects tree with file extension xcdatamodeld - that's our (empty) Model. Now lets add some entities. Well create an entity called MrDataEntity with three attributes: androidId (type int16), androidName (type String), productionDate (type Date).


If you select your entity now (MrDataEntity) you can see in right panel that it is declared as NSManagedObject class. That's OK, but if you leave it like that you must access your attributes via key string value. (If you don't have right panel shown on screen just press command+option+0).


Better approach is to generate Entity specific class, and thanks to Xcode we do that in just a few simple clicks. Go on and create new file, select Core Data and NSManagedObject subclass. Depending if your Entity was selected before creating new file, next two windows might not appear for you. At the end, click Create and two new files will be listed in your project tree MrDataEntity.h and MrDataEntity.m. They contain properties declarations for MrDataEntity.





(If your run your application now, you'll just get a blank screen.)

2. Add Core Data framework to our TARGET

Next step is to add Core Data framework.

From left panel select root of your project tree and then select your target. Make sure you are on Summary tab and scroll down to Linked Frameworks and Libraries. Now click on + button to add framework.


The window with all available frameworks will appear. Filter the list by typing data in search field. Now select CoreData.framework and click Add. There should be new toolbox icon in Linked Framework and Libraries list and also one on top of your project tree in left panel (you can drag it in Frameworks group).



3. Implement necessary code

All you did in previous two steps didn't affect our application in any way. There wasn't even any "hard copy" database created.

If you don't want to write import core data header file in each file, you can do it only once and it will be imported project wide. Locate file with extension pch (in our case MrData-Prefix.pch inside Supporting Files group) and add this line #import <CoreData/CoreData.h>
Core Data requires three things: NSManagedObjectModel, NSManagedObjectContext, NSPersistentStoreCoordinator. Here's brief description taken from Apple developer site:
  • NSManagedObjectModel - object describes a schema collection of entities (data models) that you use in your application
  • NSManagedObjectContext - scratch pad in an application. Its primary responsibility is to manage a collection of managed objects.
  • NSPersistentStoreCoordinator - mediate between the persistent store and the managed object context or contexts.
Let's open our AppDelegate.h and add these lines before @end.
Now open AppDelegate.m and after @implementation AppDelegate add:
In the same file add this big chunk of pre-boiled Apple's Core Data code:
There are two things in above code you must edit according to your files naming. First is the name of your bundle in managedObjectModel method. It must be the same as you named your model previously (file with .xcdatamodeld extension).
Second one is opinial, that's database name in persistentStoreCoordinator method.
For test run, add just one more line to application didFinishLaunchingWithOptions method before return statement:
If you run your application now it will still be blank, but now we've created hard copy of our database. To locate it go on and add this line to  persistentStoreCoordinator method right below storeURL declaration.
It will print out the path to your application in Simulator folder four your machine.

Since our application is empty we will manually add few rows to it. We could do that from sqlite3 terminal, but we'll use nice free plugin for Firefox called SQLite Manager https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/

Install and start SQLite Manager plugin.


Click on Open button, press Command + Shift + G on keyboard and write down the path to your database (printed earlier with NSLog in Xcode output panel). Mine is: /Users/XXXXX/Library/Application Support/iPhone Simulator/5.1/Applications/ . Hit enter and chose appropriate UUID for your app (also listed in Xcode output panel), go to Documents and there's our database.


To add rows to it, in left panel, select Tables and table named same as your Data Model file (.xcdatamodeld). Click Add button on right side and input form will appear.


It's time to write print those records in our app!

Open AppDelegate.m and import "MrDataEntity.h".
Now replace line we added earlier in application didFinishLaunchingWithOptions method with lines bellow. Watch out to write appropriate entityForName (in our case that was: MrDataEntity).
You should see our data printed in output panel!


Connect ViewController with our data

Final step of this tutorial is to connect our ViewController with our data. To do so we need to declare NSManagedObjectContext property in ViewController.h file. Add this line before @end statement:
And add this line to AppDelegate.m file -  application didFinishLaunchingWithOptions method before: [self.window makeKeyAndVisible];
You can cut the code for fetching and printing results and paste it in to the ViewController.m to viewDidLoad method. Also add import statement for entity description header file and synthesize  managedObjectContext. Here is how it would look like if we want to print out our data to UITextField:
Here's a running application:


That's all for today!

Saturday, July 2, 2011

Linux Live CD Non Graphical Boot

Booting LiveCD Without X
LiveCD environments can usually be helpful for testing, but if you're troubleshooting a problem where X does not start up, that makes it difficult to retrieve the log files and other such things. But it can be done:

0. Obtain a Live CD for the release you're testing: http://cdimage.ubuntu.com/releases/

1. At the CD boot menu, add "text" to the boot options: https://help.ubuntu.com/community/BootParameters

2. The CD will now boot but not start X.

3. You can grab xrandr data without starting an X session like this:


xinit -e 'sh -c "xrandr --verbose > xrandr.txt" '
This will try to start X and log some information about the active screen resolution to the file xrandr.log before it stops X again.

4. Start up an X session like this:


startx
or


/usr/X11R6/bin/X :0

Tuesday, September 1, 2009

ifconfig

Renews the IP address.
dhclient eth0

Assign eth0 with the above values for IP, netmask and broadcast address.
ifconfig eth0 192.168.1.102 netmask 255.255.255.0 broadcast 192.168.1.255

Thursday, August 20, 2009

Rearrange table columns order

MODIFY [column] column_definition [FIRST ¦ AFTER col_name]
ALTER TABLE tableName MODIFY COLUMN originalColName int(4) AFTER destinationColName

Sunday, July 5, 2009

linux folder size

ls -skh folderlist folder sizes
du -skh * |sort -n -r list folder sizes
du -sh folder folder size

sshfs remote mount

sudo chmod og-rwx localFolder/
sudo sshfs user@remoteHost:remoteFolder/ localFolder/ -o allow_other

scp remote copy with port select

scp -P 22 sourceFile user@remoteHost:folder

Thursday, June 25, 2009

Excel export chart to jpg png

Hi,

Requires code. Syntax: Activechart.Export ,

You can use this in the immediate window,(ALT+F11 CTRL+G)

Activechart.export "C:\mychart.jpg"

Saturday, December 6, 2008

Mysql windows (xampp) case sensitive tables

Open file C:/xampp/mysql/bin/my.cnf and under [mysqld] add
lower_case_table_names=0

Thursday, November 27, 2008

Evince papersize

Add the a line with
LC_PAPER="en_HR@hrnum"
in
/etc/environment
Evince will use A4 as default paper format after your next login.

What is en_HR?

en_HR is locale meant to be used by computer users whose native language is Croatian, but who are primarily used to US English based interface. Therefore en_HR features US English messages, and US style of writing numbers. US numeric style is chosen because of the decimal separator - in US style the decimal separator is `.', which is commonly used in mathematics and by SI, while Croatian decimal separator is `,'. If you would rather use Croatian numeric style, then use en_HR@hrnum instead of en_HR. Collate, ctype, monetary, paper, telephone, measurement, name and adress settings are the same ones from hr_HR locale. Date and time format conforms to ISO 8601 standard.

Wednesday, November 12, 2008

ssh tunel from linux

ssh -L 8080:192.168.2.254:80 user@address.org -p 22



Open your browser and go to http://localhost:8080 to see if your tunnel is working.

ssh -L localport:host:hostport user@ssh_server -N

where:
-L - port forwarding parameters (see below)
localport - local port (chose a port that is not in use by other service)
host - server that has the port (hostport) that you want to forward
hostport - remote port
-N - do not execute a remote command, (you will not have the shell, see below)
user - user that have ssh access to the ssh server (computer)
ssh_server - the ssh server that will be used for forwarding/tunneling

Without the -N option you will have not only the forwardig port but also the remote
shell. Try with and without it to see the difference.

Note:
1. Privileged ports (localport lower then 1024) can only be forwarded by root.
2. In the ssh line you can use multiple -L like in the example...
3. Of course, you must have ssh user access on secure_computer and moreover
the secure computer must have access to host:hostport
4. Some ssh servers do not allow port forwarding (tunneling). See the sshd man
pages for more about port forwarding (the AllowTcpForwarding keyword is set to
NO in sshd_config file, by default is set to YES)...

Example:


ssh -L 8888:www.linuxhorizon.ro:80 user@computer -N
ssh -L 8888:www.linuxhorizon.ro:80 -L 110:mail.linuxhorizon.ro:110 \
25:mail.linuxhorizon.ro:25 user@computer -N


The second example (see above) show you how to setup your ssh tunnel for web, pop3
and smtp. It is useful to recive/send your e-mails when you don't have direct access
to the mail server.

For the ASCII art and lynx browser fans here is illustrated the first example:

+----------+<--port 22-->+----------+<--port 80-->o-----------+
|SSH Client|-------------|ssh_server|-------------| host |
+----------+ +----------+ o-----------+
localhost:8888 computer www.linuxhorizon.ro:80

...And finally:
Open your browser and go to http://localhost:8888 to see if your tunnel is working.

Wednesday, September 24, 2008

linux adduser bash batch script

#!/bin/bash

NEW_USERS="/path/to/file.txt" #space separated user password group
HOME_BASE="/home/"

cat ${NEW_USERS} | \
while read USER password GROUP
do
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -g ${GROUP} -p ${pass} -m -d ${HOME_BASE}${USER} ${USER}
done

Monday, September 22, 2008

sshfs mount

sudo mkdir /mount/remote
sudo modprobe fuse
sshfs asdf@192.168.0.251:/ /mount/remote/

Friday, September 5, 2008

ltsp - xserver configuration

first in /etc/ltsp/dhcp.conf add/change this line: option root-path "/var/lib/tftpboot/ltsp/i386";
dhcp example:

authoritative;
subnet 192.168.0.0 netmask 255.255.255.0 {
range 192.168.0.200 192.168.0.250;
option domain-name "example.com";
option domain-name-servers 192.168.0.150;
option broadcast-address 192.168.0.255;
option routers 192.168.0.150;
# next-server 192.168.0.1;
# get-lease-hostnames true;
option subnet-mask 255.255.255.0;
# option root-path "/opt/ltsp/i386";
option root-path "/var/lib/tftpboot/ltsp/i386";
if substring( option vendor-class-identifier, 0, 9 ) = "PXEClient" {
filename "/ltsp/i386/pxelinux.0";
} else {
filename "/ltsp/i386/nbi.img";
}
}


Then edit your /var/lib/tftpboot/ltsp/i386/lts.conf file.
Example:

[00:12:FB:01:74:AF]
# LDM_AUTOLOGIN=true
# LDM_USERNAME=ucenik01
# LDM_PASSWORD=ucenik
SOUND=False
XSERVER = sis
X_MODE_0 = 1280x1024
X_MODE_1 = 1024x768
X_MODE_2 = 800x600


Sunday, July 20, 2008

mpg123

VirginRadio
mpg123 -C -k 64 http://85.159.184.42:80

Play single mp3
mpg321 MP3_FILE_NAME

Create a list of all MP3 Files in the current folder…
find . -name "*.mp3"|sed 's/\.\///;'|sort>List.lst

Use this list as the play list for mpg321
mpg123 --list List.lst

Saturday, May 10, 2008

How to turn on automatic logon in Windows XP

1. Click Start, and then click Run.
2. In the Open box, type control userpasswords2, and then click OK.

Note When users try to display help information in the User Accounts window in Windows XP Home Edition, the help information is not displayed. Additionally, users receive the following error message:
Cannot find the Drive:\Windows\System32\users.hlp Help file. Check to see that the file exists on your hard disk drive. If it does not exist, you must reinstall it.
3. Clear the "Users must enter a user name and password to use this computer" check box, and then click Apply.
4. In the Automatically Log On window, type the password in the Password box, and then retype the password in the Confirm Password box.
5. Click OK to close the Automatically Log On window, and then click OK to close the User Accounts window.

Sunday, May 4, 2008

This will shutdown your box 1 minute after the file download completes:

sudo -s; wget http://www.theaddress.com/fiesty.iso; shutdown -h +1

TOO CANCEL A SHUTDOWN:

sudo shutdown -c

Wednesday, April 30, 2008

usb privelages

Give the user permission to load drivers, you can access this going to the
Control Panel > Administrative Tools > Local Security Policy > Local
Policies > User Rights Assignment > Load and Unload Device Drivers.