ffmpeg -i "concat:tmpDev/VIDEO_TS/VTS_01_1.VOB|tmpDev/VIDEO_TS/VTS_01_2.VOB|tmpDev/VIDEO_TS/VTS_01_3.VOB|tmpDev/VIDEO_TS/VTS_01_4.VOB" -acodec copy -vcodec libx264 ./out.mp4
Chitika
Wednesday, September 18, 2013
Monday, September 16, 2013
gnu c/gcc exception handling
man setjmp states:
"setjmp() and longjmp(3) are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. setjmp() saves the stack context/environment in env for later use by longjmp(3). The stack context will be invalidated if the function which called setjmp() returns."
man lngjmp states:
"longjmp() and setjmp(3) are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. longjmp() restores the environment saved by the last call of setjmp(3) with the corresponding env argument. After longjmp() is completed, program execution continues as if the corresponding call of setjmp(3) had just returned the value val. longjmp() cannot cause 0 to be returned. If longjmp() is invoked with a second argument of 0, 1 will be returned instead."
Example at wikipedia:
#include <setjmp.h> #include <stdio.h> #include <stdlib.h> enum { SOME_EXCEPTION = 1 } exception; jmp_buf state; int main(void) { if(!setjmp(state)) // try { if(/* something happened */) { exception = SOME_EXCEPTION; longjmp(state, 0); // throw SOME_EXCEPTION } } else switch(exception) { case SOME_EXCEPTION: // catch SOME_EXCEPTION puts("SOME_EXCEPTION caught"); break; default: // catch ... puts("Some strange exception"); } return EXIT_SUCCESS; }
Try/Catch in C: (source: http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html)
#include <stdio.h> #include <setjmp.h> #define TRY do{ jmp_buf ex_buf__; if( !setjmp(ex_buf__) ){ #define CATCH } else { #define ETRY } }while(0) #define THROW longjmp(ex_buf__, 1) int main(int argc, char** argv) { TRY { printf("In Try Statement\n"); THROW; printf("I do not appear\n"); } CATCH { printf("Got Exception!\n"); } ETRY; return 0; }
Advanced Try...Catch...Finally: (source: http://www.di.unipi.it/~nids/docs/longjump_try_trow_catch.html)#include <stdio.h> #include <setjmp.h> #define TRY do{ jmp_buf ex_buf__; switch( setjmp(ex_buf__) ){ case 0: while(1){ #define CATCH(x) break; case x: #define FINALLY break; } default: #define ETRY } }while(0) #define THROW(x) longjmp(ex_buf__, x) #define FOO_EXCEPTION (1) #define BAR_EXCEPTION (2) #define BAZ_EXCEPTION (3) int main(int argc, char** argv) { TRY { printf("In Try Statement\n"); THROW( BAR_EXCEPTION ); printf("I do not appear\n"); } CATCH( FOO_EXCEPTION ) { printf("Got Foo!\n"); } CATCH( BAR_EXCEPTION ) { printf("Got Bar!\n"); } CATCH( BAZ_EXCEPTION ) { printf("Got Baz!\n"); } FINALLY { printf("...et in arcadia Ego\n"); } ETRY; return 0; }
Monday, September 2, 2013
grails db-reverse-engineer
Create application:
> grails create-app
Reverse engineer DB, following is the great tutorial for it:
http://grails-plugins.github.io/grails-db-reverse-engineer/docs/manual/guide/single.html
> grails db-reverse-engineer
Remember following points:
1. every thing in db should be in small case, separating words with underscore ("_"), instead of camel notation.
2. when joining tables, foreign key should be named as follows: table_name + underscore + id, e.g. foreign key for table "data" should be named: data_id, in all the tables joined with data table
Generate controllers:
> grails generate-all "*"
Run application:
> grails run-app
NOTE: if error occurred, set JDK path:
> export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
> grails create-app
Reverse engineer DB, following is the great tutorial for it:
http://grails-plugins.github.io/grails-db-reverse-engineer/docs/manual/guide/single.html
> grails db-reverse-engineer
Remember following points:
1. every thing in db should be in small case, separating words with underscore ("_"), instead of camel notation.
2. when joining tables, foreign key should be named as follows: table_name + underscore + id, e.g. foreign key for table "data" should be named: data_id, in all the tables joined with data table
Generate controllers:
> grails generate-all "*"
Run application:
> grails run-app
NOTE: if error occurred, set JDK path:
> export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
Labels:
database,
grails,
orm,
rdb,
reverse-engineering
Wednesday, August 21, 2013
linux: secure, quick and easy sock5 proxy over ssh
Connect to remote server using following ssh command:
> ssh -D 12345 remote-server.com
a sock5 server will started on localhost:12345, port is 12345.
install tsocks package, as sock5 client
> sudo apt-get install tsocks
edit /etc/tsocks.conf
> vi /etc/tsocks.conf
remove everything, and enter following lines:
server = 127.0.0.1
server_type = 5
server_port = 12345
> ssh -D 12345 remote-server.com
a sock5 server will started on localhost:12345, port is 12345.
install tsocks package, as sock5 client
> sudo apt-get install tsocks
edit /etc/tsocks.conf
> vi /etc/tsocks.conf
remove everything, and enter following lines:
server = 127.0.0.1
server_type = 5
server_port = 12345
save and quit
Now to run firefox (or any other network application), using sock5, execute following command:
> tsocks firefox
enjoy, secure, quick and easy sock5 proxy over ssh.
Tuesday, July 2, 2013
C/C++ Profiling
Compilation
compile and link program using gcc/g++, without using ld command, with flag -pg
Autotools
for auto tools, clean project (make clean),
execute $> CFLAGS=-pg ./configure && make && sudo make install
Generation
execute the program /bin/prog.exe (or test suite), gmon.out file will be created in working directory
NOTE: gmon.out file will be created on program exit, killing the process, would not generate gmon.out
Post Processing
In order to generate profiling information from gmon.out, execute following command:
$> gprof /bin/prog.exe gmon.out > analyse.txt
Profiling information will be generated in analyse.txt file.
NOTE: provide complete path to program and complete path to gmon.out (here gmon.out is present in current directory)
compile and link program using gcc/g++, without using ld command, with flag -pg
Autotools
for auto tools, clean project (make clean),
execute $> CFLAGS=-pg ./configure && make && sudo make install
Generation
execute the program /bin/prog.exe (or test suite), gmon.out file will be created in working directory
NOTE: gmon.out file will be created on program exit, killing the process, would not generate gmon.out
Post Processing
In order to generate profiling information from gmon.out, execute following command:
$> gprof /bin/prog.exe gmon.out > analyse.txt
Profiling information will be generated in analyse.txt file.
NOTE: provide complete path to program and complete path to gmon.out (here gmon.out is present in current directory)
Tuesday, June 25, 2013
GDB debugging
Following are the useful commands to debug:
debug with program arguments:
gdb --args prog arg1 arg2 arg3
Debugging an application with complex configuration files setup in different directories:
compile the program with -g switch, and install it
debug the installed program as follows:
sudo gdb --args prog arg1 arg2 arg3
add break point to function:
b func_foo
add break point to line in file:
b file:line_num
step into:
s
step over:
n
continue program execution:
c
start/restart program:
r
print variable:
p var
x/s str_var
print 10 bytes in hex
x/10x str_var
list program statements being in debug
l
get call stack: (backtrace)
bt
get value of some variable in function call in back in call stack at row 2:
f 2
p var
get all break points (info break):
i b
delete a break point 3:
d 3
watch a variable for change:
wa var
get threads list (info threads):
i th
change to different thread context (e.g. thread 2):
t 2
attaching to an already running process for debugging (first get process id using ps -ef):
at process_id
detaching to debugging process:
det
debugging save state (checkpoint, only for single threaded application):
checkpoint
info checkpoint
restore program state to the checkpoint (e.g. 2):
restart 2
debug with program arguments:
gdb --args prog arg1 arg2 arg3
Debugging an application with complex configuration files setup in different directories:
compile the program with -g switch, and install it
debug the installed program as follows:
sudo gdb --args prog arg1 arg2 arg3
add break point to function:
b func_foo
add break point to line in file:
b file:line_num
step into:
s
step over:
n
continue program execution:
c
start/restart program:
r
print variable:
p var
x/s str_var
print 10 bytes in hex
x/10x str_var
list program statements being in debug
l
get call stack: (backtrace)
bt
get value of some variable in function call in back in call stack at row 2:
f 2
p var
get all break points (info break):
i b
delete a break point 3:
d 3
watch a variable for change:
wa var
get threads list (info threads):
i th
change to different thread context (e.g. thread 2):
t 2
attaching to an already running process for debugging (first get process id using ps -ef):
at process_id
detaching to debugging process:
det
debugging save state (checkpoint, only for single threaded application):
checkpoint
info checkpoint
restore program state to the checkpoint (e.g. 2):
restart 2
GDB hex dump
Create file in home folder, named '.gdbinit', and put following contents in it:
define xxd
dump binary memory dump.bin $arg0 $arg0+$arg1
shell xxd dump.bin
end
during debugging execute following command to get hex dump of any memory area, by specifying starting address (or name of variable) and length:
(gdb) xxd var 112
0000000: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000010: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000020: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000030: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000040: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000050: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000060: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
Ref:
http://stackoverflow.com/questions/9233095/memory-dump-formatted-like-xxd-from-gdb
http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_chapter/gdb_18.html#SEC195
define xxd
dump binary memory dump.bin $arg0 $arg0+$arg1
shell xxd dump.bin
end
during debugging execute following command to get hex dump of any memory area, by specifying starting address (or name of variable) and length:
(gdb) xxd var 112
0000000: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000010: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000020: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000030: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000040: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000050: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
0000060: aabb ccdd eeff 0011 2233 4455 6677 8899 ................
Ref:
http://stackoverflow.com/questions/9233095/memory-dump-formatted-like-xxd-from-gdb
http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_chapter/gdb_18.html#SEC195
Thursday, May 16, 2013
Sets Difference algorithm
Lets assume you have two sets as follows:
example sets:
Set A
1
2
3
4
Set B
3
4
5
6
now we want to get difference of these sets:
(assume a cleared (0) flag "added" for each element of set B)
algorithm:
1. for each element E in set B, iterate over elements in set A
i. if value of element E is found in set A, remove that entry from A
ii. if value of element E is not found in set A, set (1) "added" flag of element E
4. Remaining elements in set A, represents set difference A-B
5. elements in set B, having flag "added" set (1), represents set difference B-A
6. elements in set B, having flag "added" cleared(0), represents set intersections
7. All remaining elements in set A and value of all elements in set B represents union of set A and B
result:
Set A
1
2
Set B
3
4
5 -> added
6 -> added
A-B = 1,2
B-A = 5,6
A intersection B = 3,4
A union B = 1,2,3,4,5,6
optimizations:
if set A is sorted, iterated over elements of set A, until element value in set A is less than element E of set B
similarly, further optimizations are possible when both sets are sorted.
example sets:
Set A
1
2
3
4
Set B
3
4
5
6
now we want to get difference of these sets:
(assume a cleared (0) flag "added" for each element of set B)
algorithm:
1. for each element E in set B, iterate over elements in set A
i. if value of element E is found in set A, remove that entry from A
ii. if value of element E is not found in set A, set (1) "added" flag of element E
4. Remaining elements in set A, represents set difference A-B
5. elements in set B, having flag "added" set (1), represents set difference B-A
6. elements in set B, having flag "added" cleared(0), represents set intersections
7. All remaining elements in set A and value of all elements in set B represents union of set A and B
result:
Set A
1
2
Set B
3
4
5 -> added
6 -> added
A-B = 1,2
B-A = 5,6
A intersection B = 3,4
A union B = 1,2,3,4,5,6
optimizations:
if set A is sorted, iterated over elements of set A, until element value in set A is less than element E of set B
similarly, further optimizations are possible when both sets are sorted.
Monday, May 13, 2013
perl cpan install module
> perl -MCPAN -e shell
> install module_name
e.g.:
> install Net::DNS::Check
Monday, May 6, 2013
update perl modules to latest versions
Ubuntu environment:
Execute:
> sudo apt-get install cpanminus
> sudo cpanm App::cpanoutdated
> sudo cpan-outdated -p | cpanm
Update single module from CPAN: download, build and install
cpanm Net::DNS
cpanm LWP
Execute:
> sudo apt-get install cpanminus
> sudo cpanm App::cpanoutdated
> sudo cpan-outdated -p | cpanm
Update single module from CPAN: download, build and install
cpanm Net::DNS
cpanm LWP
Wednesday, February 13, 2013
linux enable sftp
To enable sftp on linux (having openssh-server installed), one have to uncomment/open following line in /etc/ssh/sshd_config file, and restart sshd server (this line is already enabled in all the distributions by default, means sftp is already working):
Subsystem sftp /usr/lib/ssh/sftp-server
To connect to linux sftp, use sftp user@server from command line and use normal ftp (put/get/mput/mget) commands to retrieve and send files to server.
Subsystem sftp /usr/lib/ssh/sftp-server
To connect to linux sftp, use sftp user@server from command line and use normal ftp (put/get/mput/mget) commands to retrieve and send files to server.
Tuesday, February 12, 2013
C# Cross thread GUI update issue
Following is the pattern to handle C# cross thread GUI update issue (ref: stackoverflow)
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
Monday, February 11, 2013
debug c++ activeX control of different project
Sometimes solutions are big, consisting of different project. When we have to debug these projects we get the notification that: Breakpoint will not currently be hit. No symbol loaded for this document.
To debug such project, following are the steps:
To debug such project, following are the steps:
- Clean solution
- Rebuild solution
- Run the executable project (by setting it as startup project)
- When the said activeX just launched by the executable, go to debug and attach to the executable containing the activeX
- now, easily debug the activeX project.
Thursday, February 7, 2013
JNI NDK for android developers (and casual c programmer)
- Download NDK
- extract NDK on c drive (no space in path)
- create jni folder in eclipse android project, put c file(s), make file and libraries (.a/.o) in this folder
- c file should be as follows (lowlevelfunctions.c), note signature of function:
#include <jni.h>
#include "thirdpartylib.h"
jstring Java_com_example_LowLevelFunctions_getInfo(JNIEnv* env, jobject javaThis) {
return (*env)->NewStringUTF(env, "hello world");
}
/************************************
*** and make file as follows (Android.mk): ***
************************************/
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := lowlevelfunctions
LOCAL_MODULE_TAGS := lowlevelfunctions
LOCAL_SRC_FILES := lowlevelfunctions.c
LOCAL_ARM_MODE := arm
LOCAL_LDFLAGS = $(LOCAL_PATH)/thirdpartylib.a
#LOCAL_STATIC_LIBRARIES := thirdpartylib
include $(BUILD_SHARED_LIBRARY)
5. on cmd, navigate to jni folder
6. on the jni folder, execute ndk-build executable directly from NDK root path
7. liblowlevelfunctions.so will be created to the parent folder's lib folder
8. to include it in the java, note the function name in c file, it should be added in the class LowLevelFunctions of com.example package, named getInfo, as follows:
package com.example;
class LowLevelFunctions {
static {
System.loadLibrary("lowlevelfunctions"); // as defined in make file LOCAL_MODULE
}
public static native String getInfo();
}
9. If you want to create executable, include int main() function in c file and include $(BUILD_EXECUTABLE) in last line of make file.
Wednesday, February 6, 2013
Editing dot net resource .resx file
.Net Resource Editors are third party programs/freewares, which could be used to edit resource files (having extension .resx).
Following is similar utility:
http://fishcodelib.com/files/ResourceNet2.zip
Following is similar utility:
http://fishcodelib.com/files/ResourceNet2.zip
C# get fully qualified domain name
Use following code snippet to get fully qualified domain name of current machine:
string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
string fqdn = "";
string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
string fqdn = "";
if (!hostName.Contains(domainName))
fqdn = hostName + "." + domainName;
else
fqdn = hostName;
fqdn = hostName + "." + domainName;
else
fqdn = hostName;
C# Auto detect default IP Address
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
if (localIPs != null &&
localIPs.Length > 0)
{
tbServerName.Text = (from localIP in localIPs
where localIP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
select localIP.ToString()).FirstOrDefault();
}
else
{
tbServerName.Text = "";
}
Thursday, February 23, 2012
javascript send message to child window from parent window
Parent Window
function ProcessMsgParent(msg) {
.
.
.
}
// open child window
var win = window.open(...);
// send message to child window
win.ProcessMsgChild(msg_to_child);
Child Window
function ProcessMsgChild(msg) {
.
.
.
}
// send message to parent window
window.opener.ProcessMsgParent(msg);
function ProcessMsgParent(msg) {
.
.
.
}
// open child window
var win = window.open(...);
// send message to child window
win.ProcessMsgChild(msg_to_child);
Child Window
function ProcessMsgChild(msg) {
.
.
.
}
// send message to parent window
window.opener.ProcessMsgParent(msg);
Monday, February 6, 2012
C# Printing
private PrintDocument doc = null;
.
.
.
doc = new PrintDocument();
PrintController printController = new StandardPrintController();
doc.PrintController = printController;
doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
.
.
.
doc.Print();
.
.
.
private void doc_PrintPage(object sender, PrintPageEventArgs e)
{
try
{
Graphics gfxObj = e.Graphics;
// for upside down printing
graphics.RotateTransform(180.0F);
// graphics operations
.
.
.
}
catch
{
}
finally
{
}
}
Thursday, February 2, 2012
VC++ DLL
DLL:
Create new Win32DLL project, say dllProj.
In header file define:
#ifdef PROJ_EXPORTS
#define PROJ_API __declspec(dllexport)
#else
#define PROJ_API __declspec(dllimport)
#endif
Add functions in header files with PROJ_API prefix and definitions in source file with PROJ_API prefix.
PROJ_API int foo();
Usage:
Create new Win32Console project.
define:
Top define:
extern int foo();
In function, call:
a=foo();
right click project, click Reference..., Common Properties, Frameworks and References, Add New Reference, Select dllProj project.
compile and run :)
Dotnet Usage:
Using command like linux "strings", read the function signature in the dll, which would be like ?foo@@YAHPAD@Z.
In c#, declare as:
[DllImport("dllProj.dll", CharSet = CharSet.Ansi, EntryPoint = "?foo@@YAHPAD@Z")]
private static extern int foo(string port);
Now, use it in the class as normal static function.
Create new Win32DLL project, say dllProj.
In header file define:
#ifdef PROJ_EXPORTS
#define PROJ_API __declspec(dllexport)
#else
#define PROJ_API __declspec(dllimport)
#endif
Add functions in header files with PROJ_API prefix and definitions in source file with PROJ_API prefix.
PROJ_API int foo();
Usage:
Create new Win32Console project.
define:
Top define:
extern int foo();
In function, call:
a=foo();
right click project, click Reference..., Common Properties, Frameworks and References, Add New Reference, Select dllProj project.
compile and run :)
Dotnet Usage:
Using command like linux "strings", read the function signature in the dll, which would be like ?foo@@YAHPAD@Z.
In c#, declare as:
[DllImport("dllProj.dll", CharSet = CharSet.Ansi, EntryPoint = "?foo@@YAHPAD@Z")]
private static extern int foo(string port);
Now, use it in the class as normal static function.
Monday, January 30, 2012
Perl get all HTML Ids
#!/usr/bin/perl
while (<STDIN>) {
$p = $_;
while ($p) {
if($p =~ m/id=\s*\"(\w+)\"/g) {
print $1."\n";
} else { last; }
$p = $';
}
}
Usage:
cat file.html | ./getIds.pl
while (<STDIN>) {
$p = $_;
while ($p) {
if($p =~ m/id=\s*\"(\w+)\"/g) {
print $1."\n";
} else { last; }
$p = $';
}
}
Usage:
cat file.html | ./getIds.pl
Thursday, January 26, 2012
MFC Database
Connection:
CDatabase dbase;
dbase.OpenEx("DSN=ecx;UID=sa;PWD=wavetec;");
...
dbase.Close();
Retrieve:
CRecordset rs(&dbase);
rs.Open(CRecordset::dynaset, _T("select id,c1, c2, c3 from tbl")); // preserve same order
//while reading c1, c2,c3
CDBVariant varValue;
while( !rs.IsEOF( ) )
{
rec.GetFieldValue(_T("id"), varValue, SQL_C_SLONG);
id = varValue.m_lVal;
rec.GetFieldValue(_T("c1"), varValue, SQL_C_CHAR);
val = varValue.m_pstringA->GetString();
...
rs.MoveNext( );
}
rs.Close();
Update/Delete:
CString strQl = "update tble set ts=getdate() where c1='";
strQl += c1
strQl += "'";
dbase.ExecuteSQL(strQl);
CDatabase dbase;
dbase.OpenEx("DSN=ecx;UID=sa;PWD=wavetec;");
...
dbase.Close();
Retrieve:
CRecordset rs(&dbase);
rs.Open(CRecordset::dynaset, _T("select id,c1, c2, c3 from tbl")); // preserve same order
//while reading c1, c2,c3
CDBVariant varValue;
while( !rs.IsEOF( ) )
{
rec.GetFieldValue(_T("id"), varValue, SQL_C_SLONG);
id = varValue.m_lVal;
rec.GetFieldValue(_T("c1"), varValue, SQL_C_CHAR);
val = varValue.m_pstringA->GetString();
...
rs.MoveNext( );
}
rs.Close();
Update/Delete:
CString strQl = "update tble set ts=getdate() where c1='";
strQl += c1
strQl += "'";
dbase.ExecuteSQL(strQl);
Wednesday, January 25, 2012
c++ Win UDP Communication
Init:
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", iResult);
return 1;
}
SOCKET sockRecv,
sockSend;
Send:
sockSend = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
addr.sin_family = AF_INET;
addr.sin_port = htons(srcPort);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sockSend, (sockaddr *) &addr, sizeof(addr));
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(dstPort);
addr.sin_addr.s_addr = inet_addr(this->ipAddress.c_str());
lastMsgLen = SerialLength;
memcpy(lastMsg, Buffer, lastMsgLen);
int ret = sendto(sockSend, (char *)Buffer, SerialLength, 0, (SOCKADDR *) &addr, sizeof(addr));
Receive:
sockRecv = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(this->port+1);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sockRecv, (sockaddr *) &addr, sizeof(addr));
struct sockaddr_in raddr;
int fromLen = sizeof(raddr);
fd_set rd;
FD_ZERO(&rd);
FD_SET(sockRecv, &rd);
timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
if(select(0, &rd, NULL, NULL, &tv) > 0) {
if(FD_ISSET(sockRecv, &rd)) {
int recv = recvfrom(sockRecv, (char *) &pktRecv, sizeof(pktRecv), 0, (sockaddr *)&raddr, &fromLen);
readStatus = 1;
break;
} else {
ResentLastMsg();
readStatus = 0;
}
} else {
ResentLastMsg();
readStatus = 0;
}
Shutdown:
WSACleanup();
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", iResult);
return 1;
}
SOCKET sockRecv,
sockSend;
Send:
sockSend = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
addr.sin_family = AF_INET;
addr.sin_port = htons(srcPort);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sockSend, (sockaddr *) &addr, sizeof(addr));
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(dstPort);
addr.sin_addr.s_addr = inet_addr(this->ipAddress.c_str());
lastMsgLen = SerialLength;
memcpy(lastMsg, Buffer, lastMsgLen);
int ret = sendto(sockSend, (char *)Buffer, SerialLength, 0, (SOCKADDR *) &addr, sizeof(addr));
Receive:
sockRecv = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(this->port+1);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sockRecv, (sockaddr *) &addr, sizeof(addr));
struct sockaddr_in raddr;
int fromLen = sizeof(raddr);
fd_set rd;
FD_ZERO(&rd);
FD_SET(sockRecv, &rd);
timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
if(select(0, &rd, NULL, NULL, &tv) > 0) {
if(FD_ISSET(sockRecv, &rd)) {
int recv = recvfrom(sockRecv, (char *) &pktRecv, sizeof(pktRecv), 0, (sockaddr *)&raddr, &fromLen);
readStatus = 1;
break;
} else {
ResentLastMsg();
readStatus = 0;
}
} else {
ResentLastMsg();
readStatus = 0;
}
Shutdown:
WSACleanup();
Tuesday, January 17, 2012
ListView detail view image in column
Set OwnerDraw=true;
Override DrawSubItem and DrawHeader
DrawHeader implement as e.DrawDefault=true
DrawSubItem implementation as:
if (e.ColumnIndex == 1)
{
e.DrawDefault = false;
e.DrawBackground();
int index = e.Item.ImageIndex;
Image img = imgLstWallHBState.Images[index];
e.Graphics.DrawImage(img, e.Bounds.Location);
}
else
{
e.DrawDefault = true;
}
Override DrawSubItem and DrawHeader
DrawHeader implement as e.DrawDefault=true
DrawSubItem implementation as:
if (e.ColumnIndex == 1)
{
e.DrawDefault = false;
e.DrawBackground();
int index = e.Item.ImageIndex;
Image img = imgLstWallHBState.Images[index];
e.Graphics.DrawImage(img, e.Bounds.Location);
}
else
{
e.DrawDefault = true;
}
Wednesday, December 7, 2011
Shift characters left in string
Recently I have to received data from serial port, but data was asynchronous, so I have to match the sentinal value in the string. I read a buffer then I keep reading one character at a time and shifting string left one character and searching string to find the sentinal value, following is the function to shift characters left:
char *shiftLeft(char *str, int count) {
char *savPtr=str;
int len = strlen(str);
while(*str) {
if(str+count <= savPtr + len) {
*str = *(str+count);
str++;
} else {
*str = 0;
}
}
return savPtr;
}
char *shiftLeft(char *str, int count) {
char *savPtr=str;
int len = strlen(str);
while(*str) {
if(str+count <= savPtr + len) {
*str = *(str+count);
str++;
} else {
*str = 0;
}
}
return savPtr;
}
Subscribe to:
Posts (Atom)