Search Results

Search found 1848 results on 74 pages for 'printf'.

Page 37/74 | < Previous Page | 33 34 35 36 37 38 39 40 41 42 43 44  | Next Page >

  • In Perl, is a while loop generally faster than a for loop?

    - by Mike
    I've done a small experiment as will be shown below and it looks like that a while loop is faster than a for loop in Perl. But since the experiment was rather crude, and the subject might be a lot more complicated than it seems, I'd like to hear what you have to say about this. Thanks as always for any comments/suggestions :) In the following two small scripts, I've tried while and for loops separately to calcaulte the factorial of 100,000. The one that has the while loop took 57 minutes 17 seconds to finish while the for loop equivalent took 1 hour 7 minutes 54 seconds. Script that has while loop: use strict; use warnings; use bigint; my $now = time; my $n =shift; my $s=1; while(1){ $s *=$n; $n--; last if $n==2; } print $s*$n; $now = time - $now; printf("\n\nTotal running time: %02d:%02d:%02d\n\n", int($now / 3600), int(($now % 3600) / 60), int($now % 60)); Script that has for loop: use strict; use warnings; use bigint; my $now = time; my $n =shift; my $s=1; for (my $i=2; $i<=$n;$i++) { $s = $s*$i; } print $s; $now = time - $now; printf("\n\nTotal running time: %02d:%02d:%02d\n\n", int($now / 3600), int(($now % 3600) / 60), int($now % 60));

    Read the article

  • Writing re-entrant lexer with Flex

    - by Viet
    I'm newbie to flex. I'm trying to write a simple re-entrant lexer/scanner with flex. The lexer definition goes below. I get stuck with compilation errors as shown below (yyg issue): reentrant.l: /* Definitions */ digit [0-9] letter [a-zA-Z] alphanum [a-zA-Z0-9] identifier [a-zA-Z_][a-zA-Z0-9_]+ integer [0-9]+ natural [0-9]*[1-9][0-9]* decimal ([0-9]+\.|\.[0-9]+|[0-9]+\.[0-9]+) %{ #include <stdio.h> #define ECHO fwrite(yytext, yyleng, 1, yyout) int totalNums = 0; %} %option reentrant %option prefix="simpleit_" %% ^(.*)\r?\n printf("%d\t%s", yylineno++, yytext); %% /* Routines */ int yywrap(yyscan_t yyscanner) { return 1; } int main(int argc, char* argv[]) { yyscan_t yyscanner; if(argc < 2) { printf("Usage: %s fileName\n", argv[0]); return -1; } yyin = fopen(argv[1], "rb"); yylex(yyscanner); return 0; } Compilation errors: vietlq@mylappie:~/Desktop/parsers/reentrant$ gcc lex.simpleit_.c reentrant.l: In function ‘main’: reentrant.l:44: error: ‘yyg’ undeclared (first use in this function) reentrant.l:44: error: (Each undeclared identifier is reported only once reentrant.l:44: error: for each function it appears in.)

    Read the article

  • Reading Serial Data From C (OSX /dev/tty)

    - by Jud Stephenson
    I am trying to read data from a bluetooth barcode scanner (KDC300) using C. Here is the code I have so far, and the program successfully establishes a bluetooth connection to the scanner, but when a barcode is scanned, no input is displayed on the screen (Eventually more will be done with the data, but we have to get it working first, right). Here is the program: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <sys/ioctl.h> int main (int argc, const char * argv[]) { // define vars int STOP = 0; //char buf[255]; if(argv[1]) { int fd = open("/dev/tty.KDC1", O_RDONLY); if(fd == -1) { printf("%s", strcat("Unable to open /dev/tty.", argv[1])); } int res; while(STOP == 0) { while((res = read(fd,buf,255)) == 0); { if(res > 0) { buf[res]=0; printf("%s:%d\n", buf, res); if(buf[sizeof(buf)]=='\n') break; } } } } return 0; } If anyone has any ideas, I am at a loss on this so far. If it is any help, I can run screen /dev/tty.KDC1 and any barcodes scanned on the scanner appear in the terminal, I just can't do anything with the data. Jud

    Read the article

  • Pipe overwrites buffer, don't know how to overcome

    - by Kalec
    I use a simple pipe. I read with a while, 1 char at a time, I think every time I read a char I overwrite something #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <string.h> int main () { int pipefd[2]; int cpid; char buf[31]; if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE) } cpid = fork(); if (cpid == -1) P perror("cpid"); exit(EXIT_FAILURE); } if (cpid == 0) { // child reads from pipe close (pipefd[1]); // close unused write end while (read (pipefd[0], &buf, 1)>0); printf ("Server receives: %s", buf); close (pipefd[0])l exit (EXIT_SUCCESS); } else { // parent writes to pipe close (pipefd[0]); // closing unused read end; char buf2[30]; printf("Server transmits: "); scanf ("%s", buf2); write (pipefd[1], buf2, strlen(buf2)+1); close(pipefd[1]); wait(NULL); exit(EXIT_SUCCESS); } return 0; } For example, if I input: "Flowers" it prints F and then ~6 unprintable characters

    Read the article

  • Tool for braceless, whitespace sensitive C syntax

    - by Ollie Saunders
    I'm writing some C at the moment and because I like whitespace sensitive syntax, I'd like to write it like this: #include <stdio.h> int main(void) printf("Hello, world!") return 0 Instead of this: #include <stdio.h> int main(void) { printf("Hello, world!"); return 0; } Does anybody know of a tool that will convert the former into the latter? Edit: I've really no interest in arguing with those that think this is a bad idea. By all means continue to think that, you have your reasons. But at least know this: I'm aware Python is a whitespace sensitive language but I have not used it. Why would I? I know Ruby already. Also know: I am not just learning C for the first time and I have used PHP and JavaScript for more than four years, so I am not requesting this out of some personal difficulty, lack of familiarity with block syntax, or dogmatic affiliation. I am also aware of what would be involved in writing one of these and that's not beyond my ability but I don't want this enough to justify spending the time writing one.

    Read the article

  • Array output for option of command in bash script

    - by dewaforex
    Hi, Sorry for my bad english I'm stuck figure out with my bash script with array for option of command I make bash script to extract attachments from mkv file, and at the end merge again that attachments to mkv file after the video/audio has been encoding.. this is for extract attachment #find the total of attachment A=$(mkvmerge -i input.mkv | grep -i attachment | awk '{printf $3 "\n"}' | sed 's;\:;;' | awk 'END { print NR }') #extract it for (( i=1; i<=$A; i++ )) do font[${i}]="$(mkvmerge -i input.mkv | grep -i attachment | awk '{for (i=11; i <= NF; i++) printf($i"%c" , (i==NF)?ORS:OFS) }' | sed "s/'//g" | awk "NR==$i")" mkvextract attachments input.mkv $i:"${font[${i}]}" done And now for merge again the attachment for (( i=1; i<=$A; i++ )) do #seach for space between file name and and '\' before the space because some attachment has space in filename font1[${i}]=$(echo ${font[${i}]} | sed 's/ /\\ /g') #make option for add attachment attachment[${i}]=$"--attach-file ${font1[${i}]}" done mkvmerge -o output.mkv -d 1 -S test.mp4 sub.ass ${attachment[*]} The problem, still can't work for file name with space. When I tried echo the ${attachment[*]}, It's seem all right --attach-file Beach.ttf --attach-file Candara.ttf --attach-file CASUCM.TTF --attach-file Complete\ in\ Him.ttf --attach-file CURLZ_.TTF --attach-file Frostys\ Winterland.TTF --attach-file stilltim.ttf But the output still recognize the file name with space only the first word. mkvmerge v3.0.0 ('Hang up your Hang-Ups') built on Dec 6 2010 19:19:04 Automatic MIME type recognition for 'Beach.ttf': application/x-truetype-font Automatic MIME type recognition for 'Candara.ttf': application/x-truetype-font Automatic MIME type recognition for 'CASUCM.TTF': application/x-truetype-font Error: The file 'Complete\' cannot be attached because it does not exist or cannot be read. I hope somebody can help me. Thanks

    Read the article

  • Windows console

    - by b-gen-jack-o-neill
    Hello. Well, I have a simple question, at least I hope its simple. I was interested in win32 console for a while. Our teacher told us, that windows console is just for DOS and real mode emulation purposes. Well, I know it is not true, becouse DOS applications are runned by emulator which only uses console to display output. Another thing I learned is that console is built into Windows since NT. Well. But what I could not find is, how actually are console programs written to use console. I use Visual C++ for programming (well, for learning). So, the only thing I need to do for using console is select console project. I first thought that windows decides wheather it run app in console or tries to run app in window mode. So I created win32 program and tried printf(). Well, I could not compile it. I know that by definition printf() prints text or variables to stdout. I also found that stdout is the console interface for output. But, I could not find what actually stdout is. So, basicly what I want to ask is, where is the difference between console app and win32 app. I thought that windows starts console when it gets command from "console-family" functions. But obvisously it does not, so there must be some code that actually commands windows to create console interface. And the second question is, when the console is created, how does windows recognize which console terminal is used for what app? I mean, what actually is stdout? Is it a area in memory , or some windows routine that is called? Thanks.

    Read the article

  • UTF-8 to Unicode conversion

    - by sandeep
    Hi, I am having problems with converting UTF-8 to Unicode. Below is the code: int charset_convert( char * string, char * to_string,char* charset_from, char* charset_to) { char *from_buf, *to_buf, *pointer; size_t inbytesleft, outbytesleft, ret; size_t TotalLen; iconv_t cd; if (!charset_from || !charset_to || !string) /* sanity check */ return -1; if (strlen(string) < 1) return 0; /* we are done, nothing to convert */ cd = iconv_open(charset_to, charset_from); /* Did I succeed in getting a conversion descriptor ? */ if (cd == (iconv_t)(-1)) { /* I guess not */ printf("Failed to convert string from %s to %s ", charset_from, charset_to); return -1; } from_buf = string; inbytesleft = strlen(string); /* allocate max sized buffer, assuming target encoding may be 4 byte unicode */ outbytesleft = inbytesleft *4 ; pointer = to_buf = (char *)malloc(outbytesleft); memset(to_buf,0,outbytesleft); memset(pointer,0,outbytesleft); ret = iconv(cd, &from_buf, &inbytesleft, &pointer, &outbytesleft);ing memcpy(to_string,to_buf,(pointer-to_buf); } main(): int main() { char UTF []= {'A', 'B'}; char Unicode[1024]= {0}; char* ptr; int x=0; iconv_t cd; charset_convert(UTF,Unicode,"UTF-8","UNICODE"); ptr = Unicode; while(*ptr != '\0') { printf("Unicode %x \n",*ptr); ptr++; } return 0; } It should give A and B but i am getting: ffffffff fffffffe 41 Thanks, Sandeep

    Read the article

  • CS 50- Pset 1 Mario Program

    - by boametaphysica
    the problem set asks us to create a half pyramid using hashes. Here is a link to an image of how it should look- I get the idea and have written the program until printing the spaces (which I have replaced by "_" just so that I can test the first half of it. However, when I try to run my program, it doesn't go beyond the do-while loop. In other words, it keeps asking me for the height of the pyramid and does not seem to run the for loop at all. I've tried multiple approaches but this problem seems to persist. Any help would be appreciated! Below is my code- # include <cs50.h> # include <stdio.h> int main(void) { int height; do { printf("Enter the height of the pyramid: "); height = GetInt(); } while (height > 0 || height < 24); for (int rows = 1; rows <= height, rows++) { for (int spaces = height - rows; spaces > 0; spaces--) { printf("_"); } } return 0; } Running this program yields the following output- Enter the height of the pyramid: 11 Enter the height of the pyramid: 1231 Enter the height of the pyramid: aawfaf Retry: 12 Enter the height of the pyramid:

    Read the article

  • When is a>a true ?

    - by Cricri
    Right, I think I really am living a dream. I have the following piece of code which I compile and run on an AIX machine: AIX 3 5 PowerPC_POWER5 processor type IBM XL C/C++ for AIX, V10.1 Version: 10.01.0000.0003 #include <stdio.h> #include <math.h> #define RADIAN(x) ((x) * acos(0.0) / 90.0) double nearest_distance(double radius,double lon1, double lat1, double lon2, double lat2){ double rlat1=RADIAN(lat1); double rlat2=RADIAN(lat2); double rlon1=lon1; double rlon2=lon2; double a=0,b=0,c=0; a = sin(rlat1)*sin(rlat2)+ cos(rlat1)*cos(rlat2)*cos(rlon2-rlon1); printf("%lf\n",a); if (a > 1) { printf("aaaaaaaaaaaaaaaa\n"); } b = acos(a); c = radius * b; return radius*(acos(sin(rlat1)*sin(rlat2)+ cos(rlat1)*cos(rlat2)*cos(rlon2-rlon1))); } int main(int argc, char** argv) { nearest_distance(6367.47,10,64,10,64); return 0; } Now, the value of 'a' after the calculation is reported as being '1'. And, on this AIX machine, it looks like 1 1 is true as my 'if' is entered !!! And my acos of what I think is '1' returns NanQ since 1 is bigger than 1. May I ask how that is even possible ? I do not know what to think anymore ! The code works just fine on other architectures where 'a' really takes the value of what I think is 1 and acos(a) is 0.

    Read the article

  • Does NULL and nil are equal?

    - by monish
    Hi Guys, Actually my question here is does Null and nil are equal or not? I had an Example but I am confused when they are equal when they are not. NSNull *nullValue = [NSNull null]; NSArray *arrayWithNull = [NSArray arrayWithObject:nullValue]; NSLog(@"arrayWithNull: %@", arrayWithNull); id aValue = [arrayWithNull objectAtIndex:0]; if (aValue == nil) { NSLog(@"equals nil"); } else if (aValue == [NSNull null]) { NSLog(@"equals NSNull instance"); if ([aValue isEqual:nil]) { NSLog(@"isEqual:nil"); } } Here in the above case it shows that both Null and nil are not equal and it displays "equals NSNull instance" NSString *str=NULL; id str1=nil; if(str1 == str) { printf("\n IS EQUAL........"); } else { printf("\n NOT EQUAL........"); } And in the second case it shows both are equal and it displays "IS EQUAL". Anyone's help will be much appreciated. Thank you, Monish.

    Read the article

  • Setting up a pc bluetooth server for android

    - by Del
    Alright, I've been reading a lot of topics the past two or three days and nothing seems to have asked this. I am writing a PC side server for my andriod device, this is for exchanging some information and general debugging. Eventually I will be connecting to a SPP device to control a microcontroller. I have managed, using the following (Android to pc) to connect to rfcomm channel 11 and exchange data between my android device and my pc. Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(11)); I have attempted the createRfcommSocketToServiceRecord(UUID) method, with absolutely no luck. For the PC side, I have been using the C Bluez stack for linux. I have the following code which registers the service and opens a server socket: int main(int argc, char **argv) { struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 }; char buf[1024] = { 0 }; char str[1024] = { 0 }; int s, client, bytes_read; sdp_session_t *session; socklen_t opt = sizeof(rem_addr); session = register_service(); s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); loc_addr.rc_family = AF_BLUETOOTH; loc_addr.rc_bdaddr = *BDADDR_ANY; loc_addr.rc_channel = (uint8_t) 11; bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr)); listen(s, 1); client = accept(s, (struct sockaddr *)&rem_addr, &opt); ba2str( &rem_addr.rc_bdaddr, buf ); fprintf(stderr, "accepted connection from %s\n", buf); memset(buf, 0, sizeof(buf)); bytes_read = read(client, buf, sizeof(buf)); if( bytes_read 0 ) { printf("received [%s]\n", buf); } sprintf(str,"to Android."); printf("sent [%s]\n",str); write(client, str, sizeof(str)); close(client); close(s); sdp_close( session ); return 0; } sdp_session_t *register_service() { uint32_t svc_uuid_int[] = { 0x00000000,0x00000000,0x00000000,0x00000000 }; uint8_t rfcomm_channel = 11; const char *service_name = "Remote Host"; const char *service_dsc = "What the remote should be connecting to."; const char *service_prov = "Your mother"; uuid_t root_uuid, l2cap_uuid, rfcomm_uuid, svc_uuid; sdp_list_t *l2cap_list = 0, *rfcomm_list = 0, *root_list = 0, *proto_list = 0, *access_proto_list = 0; sdp_data_t *channel = 0, *psm = 0; sdp_record_t *record = sdp_record_alloc(); // set the general service ID sdp_uuid128_create( &svc_uuid, &svc_uuid_int ); sdp_set_service_id( record, svc_uuid ); // make the service record publicly browsable sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP); root_list = sdp_list_append(0, &root_uuid); sdp_set_browse_groups( record, root_list ); // set l2cap information sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID); l2cap_list = sdp_list_append( 0, &l2cap_uuid ); proto_list = sdp_list_append( 0, l2cap_list ); // set rfcomm information sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID); channel = sdp_data_alloc(SDP_UINT8, &rfcomm_channel); rfcomm_list = sdp_list_append( 0, &rfcomm_uuid ); sdp_list_append( rfcomm_list, channel ); sdp_list_append( proto_list, rfcomm_list ); // attach protocol information to service record access_proto_list = sdp_list_append( 0, proto_list ); sdp_set_access_protos( record, access_proto_list ); // set the name, provider, and description sdp_set_info_attr(record, service_name, service_prov, service_dsc); int err = 0; sdp_session_t *session = 0; // connect to the local SDP server, register the service record, and // disconnect session = sdp_connect( BDADDR_ANY, BDADDR_LOCAL, SDP_RETRY_IF_BUSY ); err = sdp_record_register(session, record, 0); // cleanup //sdp_data_free( channel ); sdp_list_free( l2cap_list, 0 ); sdp_list_free( rfcomm_list, 0 ); sdp_list_free( root_list, 0 ); sdp_list_free( access_proto_list, 0 ); return session; } And another piece of code, in addition to 'sdptool browse local' which can verifty that the service record is running on the pc: int main(int argc, char **argv) { uuid_t svc_uuid; uint32_t svc_uuid_int[] = { 0x00000000,0x00000000,0x00000000,0x00000000 }; int err; bdaddr_t target; sdp_list_t *response_list = NULL, *search_list, *attrid_list; sdp_session_t *session = 0; str2ba( "01:23:45:67:89:AB", &target ); // connect to the SDP server running on the remote machine session = sdp_connect( BDADDR_ANY, BDADDR_LOCAL, SDP_RETRY_IF_BUSY ); // specify the UUID of the application we're searching for sdp_uuid128_create( &svc_uuid, &svc_uuid_int ); search_list = sdp_list_append( NULL, &svc_uuid ); // specify that we want a list of all the matching applications' attributes uint32_t range = 0x0000ffff; attrid_list = sdp_list_append( NULL, &range ); // get a list of service records that have UUID 0xabcd err = sdp_service_search_attr_req( session, search_list, \ SDP_ATTR_REQ_RANGE, attrid_list, &response_list); sdp_list_t *r = response_list; // go through each of the service records for (; r; r = r-next ) { sdp_record_t *rec = (sdp_record_t*) r-data; sdp_list_t *proto_list; // get a list of the protocol sequences if( sdp_get_access_protos( rec, &proto_list ) == 0 ) { sdp_list_t *p = proto_list; // go through each protocol sequence for( ; p ; p = p-next ) { sdp_list_t *pds = (sdp_list_t*)p-data; // go through each protocol list of the protocol sequence for( ; pds ; pds = pds-next ) { // check the protocol attributes sdp_data_t *d = (sdp_data_t*)pds-data; int proto = 0; for( ; d; d = d-next ) { switch( d-dtd ) { case SDP_UUID16: case SDP_UUID32: case SDP_UUID128: proto = sdp_uuid_to_proto( &d-val.uuid ); break; case SDP_UINT8: if( proto == RFCOMM_UUID ) { printf("rfcomm channel: %d\n",d-val.int8); } break; } } } sdp_list_free( (sdp_list_t*)p-data, 0 ); } sdp_list_free( proto_list, 0 ); } printf("found service record 0x%x\n", rec-handle); sdp_record_free( rec ); } sdp_close(session); } Output: $ ./search rfcomm channel: 11 found service record 0x10008 sdptool: Service Name: Remote Host Service Description: What the remote should be connecting to. Service Provider: Your mother Service RecHandle: 0x10008 Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 11 And for logcat I'm getting this: 07-22 15:57:06.087: ERROR/BTLD(215): ****************search UUID = 0000*********** 07-22 15:57:06.087: INFO//system/bin/btld(209): btapp_dm_GetRemoteServiceChannel() 07-22 15:57:06.087: INFO//system/bin/btld(209): ##### USerial_Ioctl: BT_Wake, 0x8003 #### 07-22 15:57:06.097: INFO/ActivityManager(88): Displayed activity com.example.socktest/.socktest: 79 ms (total 79 ms) 07-22 15:57:06.697: INFO//system/bin/btld(209): ##### USerial_Ioctl: BT_Sleep, 0x8004 #### 07-22 15:57:07.517: WARN/BTLD(215): ccb timer ticks: 2147483648 07-22 15:57:07.517: INFO//system/bin/btld(209): ##### USerial_Ioctl: BT_Wake, 0x8003 #### 07-22 15:57:07.547: WARN/BTLD(215): info:x10 07-22 15:57:07.547: INFO/BTL-IFS(215): send_ctrl_msg: [BTL_IFS CTRL] send BTLIF_DTUN_SIGNAL_EVT (CTRL) 10 pbytes (hdl 14) 07-22 15:57:07.547: DEBUG/DTUN_HCID_BZ4(253): dtun_dm_sig_link_up() 07-22 15:57:07.547: INFO/DTUN_HCID_BZ4(253): dtun_dm_sig_link_up: dummy_handle = 342 07-22 15:57:07.547: DEBUG/ADAPTER(253): adapter_get_device(00:02:72:AB:7C:EE) 07-22 15:57:07.547: ERROR/BluetoothEventLoop.cpp(88): pollData[0] is revented, check next one 07-22 15:57:07.547: ERROR/BluetoothEventLoop.cpp(88): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/253/hci0/dev_00_02_72_AB_7C_EE 07-22 15:57:07.777: WARN/BTLD(215): process_service_search_attr_rsp 07-22 15:57:07.787: INFO/BTL-IFS(215): send_ctrl_msg: [BTL_IFS CTRL] send BTLIF_DTUN_SIGNAL_EVT (CTRL) 13 pbytes (hdl 14) 07-22 15:57:07.787: INFO/DTUN_HCID_BZ4(253): dtun_dm_sig_rmt_service_channel: success=0, service=00000000 07-22 15:57:07.787: ERROR/DTUN_HCID_BZ4(253): discovery unsuccessful! 07-22 15:57:08.497: INFO//system/bin/btld(209): ##### USerial_Ioctl: BT_Sleep, 0x8004 #### 07-22 15:57:09.507: INFO//system/bin/btld(209): ##### USerial_Ioctl: BT_Wake, 0x8003 #### 07-22 15:57:09.597: INFO/BTL-IFS(215): send_ctrl_msg: [BTL_IFS CTRL] send BTLIF_DTUN_SIGNAL_EVT (CTRL) 11 pbytes (hdl 14) 07-22 15:57:09.597: DEBUG/DTUN_HCID_BZ4(253): dtun_dm_sig_link_down() 07-22 15:57:09.597: INFO/DTUN_HCID_BZ4(253): dtun_dm_sig_link_down device = 0xf7a0 handle = 342 reason = 22 07-22 15:57:09.597: ERROR/BluetoothEventLoop.cpp(88): pollData[0] is revented, check next one 07-22 15:57:09.597: ERROR/BluetoothEventLoop.cpp(88): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/253/hci0/dev_00_02_72_AB_7C_EE 07-22 15:57:09.597: DEBUG/BluetoothA2dpService(88): Received intent Intent { act=android.bluetooth.device.action.ACL_DISCONNECTED (has extras) } 07-22 15:57:10.107: INFO//system/bin/btld(209): ##### USerial_Ioctl: BT_Sleep, 0x8004 #### 07-22 15:57:12.107: DEBUG/BluetoothService(88): Cleaning up failed UUID channel lookup: 00:02:72:AB:7C:EE 00000000-0000-0000-0000-000000000000 07-22 15:57:12.107: ERROR/Socket Test(5234): connect() failed 07-22 15:57:12.107: DEBUG/ASOCKWRP(5234): asocket_abort [31,32,33] 07-22 15:57:12.107: INFO/BLZ20_WRAPPER(5234): blz20_wrp_shutdown: s 31, how 2 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): blz20_wrp_shutdown: fd (-1:31), bta -1, rc 0, wflags 0x0 07-22 15:57:12.107: INFO/BLZ20_WRAPPER(5234): __close_prot_rfcomm: fd 31 07-22 15:57:12.107: INFO/BLZ20_WRAPPER(5234): __close_prot_rfcomm: bind not completed on this socket 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): btlif_signal_event: fd (-1:31), bta -1, rc 0, wflags 0x0 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): btlif_signal_event: event BTLIF_BTS_EVT_ABORT matched 07-22 15:57:12.107: DEBUG/BTL_IFC_WRP(5234): wrp_close_s_only: wrp_close_s_only [31] (31:-1) [] 07-22 15:57:12.107: DEBUG/BTL_IFC_WRP(5234): wrp_close_s_only: data socket closed 07-22 15:57:12.107: DEBUG/BTL_IFC_WRP(5234): wsactive_del: delete wsock 31 from active list [ad3e1494] 07-22 15:57:12.107: DEBUG/BTL_IFC_WRP(5234): wrp_close_s_only: wsock fully closed, return to pool 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): btsk_free: success 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): blz20_wrp_write: wrote 1 bytes out of 1 on fd 33 07-22 15:57:12.107: DEBUG/ASOCKWRP(5234): asocket_destroy 07-22 15:57:12.107: DEBUG/ASOCKWRP(5234): asocket_abort [31,32,33] 07-22 15:57:12.107: INFO/BLZ20_WRAPPER(5234): blz20_wrp_shutdown: s 31, how 2 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): blz20_wrp_shutdown: btsk not found, normal close (31) 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): blz20_wrp_write: wrote 1 bytes out of 1 on fd 33 07-22 15:57:12.107: INFO/BLZ20_WRAPPER(5234): blz20_wrp_close: s 33 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): blz20_wrp_close: btsk not found, normal close (33) 07-22 15:57:12.107: INFO/BLZ20_WRAPPER(5234): blz20_wrp_close: s 32 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): blz20_wrp_close: btsk not found, normal close (32) 07-22 15:57:12.107: INFO/BLZ20_WRAPPER(5234): blz20_wrp_close: s 31 07-22 15:57:12.107: DEBUG/BLZ20_WRAPPER(5234): blz20_wrp_close: btsk not found, normal close (31) 07-22 15:57:12.157: DEBUG/Sensors(88): close_akm, fd=151 07-22 15:57:12.167: ERROR/CachedBluetoothDevice(477): onUuidChanged: Time since last connect14970690 07-22 15:57:12.237: DEBUG/Socket Test(5234): -On Stop- Sorry for bombarding you guys with what seems like a difficult question and a lot to read, but I've been working on this problem for a while and I've tried a lot of different things to get this working. Let me reiterate, I can get it to work, but not using service discovery protocol. I've tried a several different UUIDs and on two different computers, although I only have my HTC Incredible to test with. I've also heard some rumors that the BT stack wasn't working on the HTC Droid, but that isn't the case, at least, for PC interaction.

    Read the article

  • malloc works, cudaHostAlloc segfaults?

    - by Mikhail
    I am new to CUDA and I want to use cudaHostAlloc. I was able to isolate my problem to this following code. Using malloc for host allocation works, using cudaHostAlloc results in a segfault, possibly because the area allocated is invalid? When I dump the pointer in both cases it is not null, so cudaHostAlloc returns something... works in_h = (int*) malloc(length*sizeof(int)); //works for (int i = 0;i<length;i++) in_h[i]=2; doesn't work cudaHostAlloc((void**)&in_h,length*sizeof(int),cudaHostAllocDefault); for (int i = 0;i<length;i++) in_h[i]=2; //segfaults Standalone Code #include <stdio.h> void checkDevice() { cudaDeviceProp info; int deviceName; cudaGetDevice(&deviceName); cudaGetDeviceProperties(&info,deviceName); if (!info.deviceOverlap) { printf("Compute device can't use streams and should be discared."); exit(EXIT_FAILURE); } } int main() { checkDevice(); int *in_h; const int length = 10000; cudaHostAlloc((void**)&in_h,length*sizeof(int),cudaHostAllocDefault); printf("segfault comming %d\n",in_h); for (int i = 0;i<length;i++) { in_h[i]=2; } free(in_h); return EXIT_SUCCESS; } ~ Invocation [id129]$ nvcc fun.cu [id129]$ ./a.out segfault comming 327641824 Segmentation fault (core dumped) Details Program is run in interactive mode on a cluster. I was told that an invocation of the program from the compute node pushes it to the cluster. Have not had any trouble with other home made toy cuda codes.

    Read the article

  • Windows Messages Bizarreness

    - by jameszhao00
    Probably just a gross oversight of some sort, but I'm not receiving any WM_SIZE messages in the message loop. However, I do receive them in the WndProc. I thought the windows loop gave messages out to WndProc? LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { switch(message) { // this message is read when the window is closed case WM_DESTROY: { // close the application entirely PostQuitMessage(0); return 0; } break; case WM_SIZE: return 0; break; } printf("wndproc - %i\n", message); // Handle any messages the switch statement didn't return DefWindowProc (hWnd, message, wParam, lParam); } ... and now the message loop... while(TRUE) { // Check to see if any messages are waiting in the queue if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // translate keystroke messages into the right format TranslateMessage(&msg); // send the message to the WindowProc function DispatchMessage(&msg); // check to see if it's time to quit if(msg.message == WM_QUIT) { break; } if(msg.message == WM_SIZING) { printf("loop - resizing...\n"); } } else { //do other stuff } }

    Read the article

  • Parse and read data frame in C?

    - by user253656
    I am writing a program that reads the data from the serial port on Linux. The data are sent by another device with the following frame format: |start | Command | Data | CRC | End | |0x02 | 0x41 | (0-127 octets) | | 0x03| ---------------------------------------------------- The Data field contains 127 octets as shown and octet 1,2 contains one type of data; octet 3,4 contains another data. I need to get these data I know how to write and read data to and from a serial port in Linux, but it is just to write and read a simple string (like "ABD") My issue is that I do not know how to parse the data frame formatted as above so that I can: get the data in octet 1,2 in the Data field get the data in octet 3,4 in the Data field get the value in CRC field to check the consistency of the data Here the sample snip code that read and write a simple string from and to a serial port in Linux: int writeport(int fd, char *chars) { int len = strlen(chars); chars[len] = 0x0d; // stick a <CR> after the command chars[len+1] = 0x00; // terminate the string properly int n = write(fd, chars, strlen(chars)); if (n < 0) { fputs("write failed!\n", stderr); return 0; } return 1; } int readport(int fd, char *result) { int iIn = read(fd, result, 254); result[iIn-1] = 0x00; if (iIn < 0) { if (errno == EAGAIN) { printf("SERIAL EAGAIN ERROR\n"); return 0; } else { printf("SERIAL read error %d %s\n", errno, strerror(errno)); return 0; } } return 1; } Does anyone please have some ideas? Thanks all.

    Read the article

  • categorize a set of phrases into a set of similar phrases

    - by Dingo
    I have a few apps that generate textual tracing information (logs) to log files. The tracing information is the typical printf() style - i.e. there are a lot of log entries that are similar (same format argument to printf), but differ where the format string had parameters. What would be an algorithm (url, books, articles, ...) that will allow me to analyze the log entries and categorize them into several bins/containers, where each bin has one associated format? Essentially, what I would like is to transform the raw log entries into (formatA, arg0 ... argN) instances, where formatA is shared among many log entries. The formatA does not have to be the exact format used to generate the entry (even more so if this makes the algo simpler). Most of the literature and web-info I found deals with exact matching, a max substring matching, or a k-difference (with k known/fixed ahead of time). Also, it focuses on matching a pair of (long) strings, or a single bin output (one match among all input). My case is somewhat different, since I have to discover what represents a (good-enough) match (generally a sequence of discontinuous strings), and then categorize each input entries to one of the discovered matches. Lastly, I'm not looking for a perfect algorithm, but something simple/easy to maintain. Thanks!

    Read the article

  • Strange Bubble sort behaviour.

    - by user271528
    Can anyone explain why this bubble sort function doesn't work and why I loose number in my output. I'm very new to C, so please forgive me if this is something very obvious I have missed. #include <stdio.h> #include int bubble(int array[],int length) { int i, j; int temp; for(i = 0; i < (length); ++i) { for(j = 0; j < (length - 1); ++j) { if(array[i] array[i+1]) { temp = array[i+1]; array[i+1] = array[i]; array[i] = temp; } } } return 0; } int main() { int array[] = {12,234,3452,5643,0}; int i; int length; length = (sizeof(array)/sizeof(int)); printf("Size of array = %d\n", length); bubble(array, length); for (i = 0; i < (length); ++i) { printf("%d\n", array[i]); } return 0; } Output Size of array = 5 12 234 3452 0 0

    Read the article

  • sizeof abuse : get the size of a const table

    - by shodanex
    When declaring a const table, it is possible to get the size of the table using sizeof. However, once you stop using the symbol name, it does not work anymore. is there a way to have the following program output the correct size for table A, instead of 0 ? #include <stdio.h> struct mystruct { int a; short b; }; const struct mystruct tableA[] ={ { .a = 1, .b = 2, }, { .a = 2, .b = 2, }, { .a = 3, .b = 2, }, }; const struct mystruct tableB[] ={ { .a = 1, .b = 2, }, { .a = 2, .b = 2, }, }; int main(int argc, char * argv[]) { int tbl_sz; const struct mystruct * table; table = tableA; tbl_sz = sizeof(table)/sizeof(struct mystruct); printf("size of table A : %d\n", tbl_sz); table = tableB; tbl_sz = sizeof(tableB)/sizeof(struct mystruct); printf("size of table B : %d\n", tbl_sz); return 0; } Output is : size of table A : 0 size of table B : 2

    Read the article

  • Problem with writing a hexadecimal string

    - by quilby
    Here is my code /* gcc -c -Wall -g main.c gcc -g -lm -o main main.o */ #include <stdlib.h> #include <stdio.h> #include <string.h> void stringToHex(const char* string, char* hex) { int i = 0; for(i = 0; i < strlen(string)/2; i++) { printf("s%x", string[2*i]); //for debugging sprintf(&hex[i], "%x", string[2*i]); printf("h%x\n", hex[i]); //for debugging } } void writeHex(char* hex, int length, FILE* file, long position) { fseek(file, position, SEEK_SET); fwrite(hex, sizeof(char), length, file); } int main(int argc, char** argv) { FILE* pic = fopen("hi.bmp", "w+b"); const char* string = "f2"; char hex[strlen(string)/2]; stringToHex(string, hex); writeHex(hex, strlen(string)/2, pic, 0); fclose(pic); return 0; } I want it to save the hexadecimal number 0xf2 to a file (later I will have to write bigger/longer numbers though). The program prints out - s66h36 And when I use hexedit to view the file I see the number '36' in it. Why is my code not working? Thanks!

    Read the article

  • How to compile ocaml to native code

    - by Indra Ginanjar
    i'm really interested learning ocaml, it fast (they said it could be compiled to native code) and it's functional. So i tried to code something easy like enabling mysql event scheduler. #load "unix.cma";; #directory "+mysql";; #load "mysql.cma";; let db = Mysql.quick_connect ~user:"username" ~password:"userpassword" ~database:"databasename"();; let sql = Printf.sprintf "SET GLOBAL EVENT_SCHEDULER=1;" in (Mysql.exec db sql);; It work fine on ocaml interpreter, but when i was trying to compile it to native (i'm using ubuntu karmic), neither of these command worked ocamlopt -o mysqleventon mysqleventon.ml unix.cmxa mysql.cmxa ocamlopt -o mysqleventon mysqleventon.ml unix.cma mysql.cma i also tried ocamlc -c mysqleventon.ml unix.cma mysql.cma all of them resulting same message File "mysqleventon.ml", line 1, characters 0-1: Error: Syntax error Then i tried to remove the "# load", so the code goes like this let db = Mysql.quick_connect ~user:"username" ~password:"userpassword" ~database:"databasename"();; let sql = Printf.sprintf "SET GLOBAL EVENT_SCHEDULER=1;" in (Mysql.exec db sql);; The ocamlopt resulting message File "mysqleventon.ml", line 1, characters 9-28: Error: Unbound value Mysql.quick_connect I hope someone could tell me, where did i'm doing wrong.

    Read the article

  • Pointers in C# to make int array?

    - by Joshua
    The following C++ program compiles and runs as expected: #include <stdio.h> int main(int argc, char* argv[]) { int* test = new int[10]; for (int i = 0; i < 10; i++) test[i] = i * 10; printf("%d \n", test[5]); // 50 printf("%d \n", 5[test]); // 50 return getchar(); } The closest C# simple example I could make for this question is: using System; class Program { unsafe static int Main(string[] args) { // error CS0029: Cannot implicitly convert type 'int[]' to 'int*' int* test = new int[10]; for (int i = 0; i < 10; i++) test[i] = i * 10; Console.WriteLine(test[5]); // 50 Console.WriteLine(5[test]); // Error return (int)Console.ReadKey().Key; } } So how do I make the pointer?

    Read the article

  • Different Linux message queues have the same id?

    - by Halo
    I open a mesage queue in a .c file, and upon success it says the message queue id is 3. While that program is still running, in another terminal I start another program (of another .c file), that creates a new message queue with a different mqd_t. But its id also appears as 3. Is this a problem? server file goes like this: void server(char* req_mq) { struct mq_attr attr; mqd_t mqdes; struct request* msgptr; int n; char *bufptr; int buflen; pid_t apid; //attr.mq_maxmsg = 300; //attr.mq_msgsize = 1024; mqdes = mq_open(req_mq, O_RDWR | O_CREAT, 0666, NULL); if (mqdes == -1) { perror("can not create msg queue\n"); exit(1); } printf("server mq created, mq id = %d\n", (int) mqdes); and the client goes like: void client(char* req_mq, int min, int max, char* dir_path_name, char* outfile) { pid_t pid; /* get the process id */ if ((pid = getpid()) < 0) { perror("unable to get client pid"); } mqd_t mqd, dq; char pfx[50] = DQ_PRFX; char suffix[50]; // sprintf(suffix, "%d", pid); strcat(pfx, suffix); dq = mq_open(pfx, O_RDWR | O_CREAT, 0666, NULL); if (dq == -1) { perror("can not open data queue\n"); exit(1); } printf("data queue created, mq id = %d\n", (int) dq); mqd = mq_open(req_mq, O_RDWR); if (mqd == -1) { perror("can not open msg queue\n"); exit(1); } mqdes and dq seem to share the same id 3.

    Read the article

  • FILE* issue PPU side code

    - by Cristina
    We are working on a homework on CELL programming for college and their feedback response to our questions is kinda slow, thought i can get some faster answers here. I have a PPU side code which tries to open a file passed down through char* argv[], however this doesn't work it cannot make the assignment of the pointer, i get a NULL. Now my first idea was that the file isn't in the correct directory and i copied in every possible and logical place, my second idea is that maybe the PPU wants this pointer in its LS area, but i can't deduce if that's the bug or not. So... My question is what am i doing wrong? I am working with a Fedora 7 SDK Cell, with Eclipse as an IDE. Maybe my argument setup is wrong tho he gets the name of the file correctly. Code on request: images_t *read_bin_data(char *name) { FILE *file; images_t *img; uint32_t *buffer; uint8_t buf; unsigned long fileLen; unsigned long i; //Open file file = (FILE*)malloc(sizeof(FILE)); file = fopen(name, "rb"); printf("[Debug]Opening file %s\n",name); if (!file) { fprintf(stderr, "Unable to open file %s", name); return NULL; } //....... } Main launch: int main(int argc,char* argv[]) { int i,img_width; int modif_this[4] __attribute__ ((aligned(16))) = {1,2,3,4}; images_t *faces, *nonfaces; spe_context_ptr_t ctxs[SPU_THREADS]; pthread_t threads[SPU_THREADS]; thread_arg_t arg[SPU_THREADS]; //intializare img_width img_width = atoi(argv[1]); printf("[Debug]Img size is %i\n",img_width); faces = read_bin_data(argv[3]); //....... } Thanks for the help.

    Read the article

  • Compiled Haskell libraries with FFI imports are invalid when imported into GHCI

    - by John Millikin
    I am using GHC 6.12.1, in Ubuntu 10.04 When I try to use the FFI syntax for static storage, only modules running in interpreted mode (ie GHCI) work properly. Compiled modules have invalid pointers, and do not work. I'd like to know whether anybody can reproduce the problem, whether this an error in my code or GHC, and (if the latter) whether it's a known issue. I'm using sys_siglist because it's present in a standard library on my system, but I don't believe the actual storage used matters (I discovered this while writing a binding to libidn). If it helps, sys_siglist is defined in <signal.h> as: extern __const char *__const sys_siglist[_NSIG]; I thought this type might be the problem, so I also tried wrapping it in a plain C procedure: #include<stdio.h> const char **test_ffi_import() { printf("C think sys_siglist = %X\n", sys_siglist); return sys_siglist; } However, importing that doesn't change the result, and the printf() call prints the same pointer value as show siglist_a. My suspicion is that it's something to do with static and dynamic library loading. Update: somebody in #haskell suggested this might be 64-bit specific; if anybody tries to reproduce it, can you mention your architecture and whether it worked in a comment? Code as follows: -- A.hs {-# LANGUAGE ForeignFunctionInterface #-} module A where import Foreign import Foreign.C foreign import ccall "&sys_siglist" siglist_a :: Ptr CString -- -- B.hs {-# LANGUAGE ForeignFunctionInterface #-} module B where import Foreign import Foreign.C foreign import ccall "&sys_siglist" siglist_b :: Ptr CString -- -- Main.hs {-# LANGUAGE ForeignFunctionInterface #-} module Main where import Foreign import Foreign.C import A import B foreign import ccall "&sys_siglist" siglist_main :: Ptr CString main = do putStrLn $ "siglist_a = " ++ show siglist_a putStrLn $ "siglist_b = " ++ show siglist_b putStrLn $ "siglist_main = " ++ show siglist_main peekSiglist "a " siglist_a peekSiglist "b " siglist_b peekSiglist "main" siglist_main peekSiglist name siglist = do ptr <- peekElemOff siglist 2 str <- maybePeek peekCString ptr putStrLn $ "siglist_" ++ name ++ "[2] = " ++ show str I would expect something like this output, where all pointer values identical and valid: $ runhaskell Main.hs siglist_a = 0x00007f53a948fe00 siglist_b = 0x00007f53a948fe00 siglist_main = 0x00007f53a948fe00 siglist_a [2] = Just "Interrupt" siglist_b [2] = Just "Interrupt" siglist_main[2] = Just "Interrupt" However, if I compile A.hs (with ghc -c A.hs), then the output changes to: $ runhaskell Main.hs siglist_a = 0x0000000040378918 siglist_b = 0x00007fe7c029ce00 siglist_main = 0x00007fe7c029ce00 siglist_a [2] = Nothing siglist_b [2] = Just "Interrupt" siglist_main[2] = Just "Interrupt"

    Read the article

  • How do I get Bison/YACC to not recognize a command until it parses the whole string?

    - by chucknelson
    I have some bison grammar: input: /* empty */ | input command ; command: builtin | external ; builtin: CD { printf("Changing to home directory...\n"); } | CD WORD printf("Changing to directroy %s\n", $2); } ; I'm wondering how I get Bison to not accept (YYACCEPT?) something as a command until it reads ALL of the input. So I can have all these rules below that use recursion or whatever to build things up, which either results in a valid command or something that's not going to work. One simple test I'm doing with the code above is just entering "cd mydir mydir". Bison parses CD and WORD and goes "hey! this is a command, put it to the top!". Then the next token it finds is just WORD, which has no rule, and then it reports an error. I want it to read the whole line and realize CD WORD WORD is not a rule, and then report an error. I think I'm missing something obvious and would greatly appreciate any help - thanks! Also - I've tried using input command NEWLINE or something similar, but it still pushes CD WORD to the top as a command and then parses the extra WORD separately.

    Read the article

< Previous Page | 33 34 35 36 37 38 39 40 41 42 43 44  | Next Page >