Search Results

Search found 266 results on 11 pages for 'sprintf'.

Page 10/11 | < Previous Page | 6 7 8 9 10 11  | Next Page >

  • jQuery: Can't get tooltip plugin to work

    - by Rosarch
    I'm trying to use this tooltip plugin: http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/. I can't seem to get it to work. <head> <script type="text/javascript" src="/static/JQuery.js"></script> <script type="text/javascript" src="/static/jquery-ui-1.8.1.custom.min.js"></script> <script type="text/javascript" src="/static/jquery.json-2.2.min.js"></script> <script type="text/javascript" src="/static/jquery.form.js"></script> <script type="text/javascript" src="/static/js-lib/jquery.bgiframe.js"></script> <script type="text/javascript" src="/static/js-lib/jquery.delegate.js"></script> <script type="text/javascript" src="/static/js-lib/jquery.dimensions.js"></script> <script type="text/javascript" src="/static/jquery.tooltip.js"></script> <script type="text/javascript" src="/static/sprintf.js"></script> <script type="text/javascript" src="/static/clientside.js"></script> </head> I try it out in a simple example: clientside.js: $(document).ready(function () { $("#set1 *").tooltip(); }); The target html: <div id="set1"> <p id="welcome">Welcome. What is your email?</p> <form id="form-username-form" action="api/user_of_email" method="get"> <p> <label for="form-username">Email:</label> <input type="text" name="email" id="form-username" /> <input type="submit" value="Submit" id="form-submit" /> </p> </form> <p id="msg-user-accepted"></p> </div> Unfortunately, nothing happens. What am I doing wrong?

    Read the article

  • How to use Crtl in a Delphi unit in a C++Builder project? (or link to C++Builder C runtime library)

    - by Craig Peterson
    I have a Delphi unit that is statically linking a C .obj file using the {$L xxx} directive. The C file is compiled with C++Builder's command line compiler. To satisfy the C file's runtime library dependencies (_assert, memmove, etc), I'm including the crtl unit Allen Bauer mentioned here. unit FooWrapper; interface implementation uses Crtl; // Part of the Delphi RTL {$L FooLib.obj} // Compiled with "bcc32 -q -c foolib.c" procedure Foo; cdecl; external; end. If I compile that unit in a Delphi project (.dproj) everthing works correctly. If I compile that unit in a C++Builder project (.cbproj) it fails with the error: [ILINK32 Error] Fatal: Unable to open file 'CRTL.OBJ' And indeed, there isn't a crtl.obj file in the RAD Studio install folder. There is a .dcu, but no .pas. Trying to add crtdbg to the uses clause (the C header where _assert is defined) gives an error that it can't find crtdbg.dcu. If I remove the uses clause, it instead fails with errors that __assert and _memmove aren't found. So, in a Delphi unit in a C++Builder project, how can I export functions from the C runtime library so they're available for linking? I'm already aware of Rudy Velthuis's article. I'd like to avoid manually writing Delphi wrappers if possible, since I don't need them in Delphi, and C++Builder must already include the necessary functions. Edit For anyone who wants to play along at home, the code is available in Abbrevia's Subversion repository at https://tpabbrevia.svn.sourceforge.net/svnroot/tpabbrevia/trunk. I've taken David Heffernan's advice and added a "AbCrtl.pas" unit that mimics crtl.dcu when compiled in C++Builder. That got the PPMd support working, but the Lzma and WavPack libraries both fail with link errors: [ILINK32 Error] Error: Unresolved external '_beginthreadex' referenced from ABLZMA.OBJ [ILINK32 Error] Error: Unresolved external 'sprintf' referenced from ABWAVPACK.OBJ [ILINK32 Error] Error: Unresolved external 'strncmp' referenced from ABWAVPACK.OBJ [ILINK32 Error] Error: Unresolved external '_ftol' referenced from ABWAVPACK.OBJ AFAICT, all of them are declared correctly, and the _beginthreadex one is actually declared in AbLzma.pas, so it's used by the pure Delphi compile as well. To see it yourself, just download the trunk (or just the "source" and "packages" directories), disable the {$IFDEF BCB} block at the bottom of AbDefine.inc, and try to compile the C++Builder "Abbrevia.cbproj" project.

    Read the article

  • Increase efficiency for an R simulator of the Monty Hall Puzzle

    - by jahan_m
    The Monty Hall Problem is a simple puzzle involving probability that even stumps professionals in careers dealing with some heavy-duty math. Here's the basic problem: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice? You can find numerous explanations of the solution here: http://en.wikipedia.org/wiki/Monty_Hall_problem Goal of my simulation: Prove that a switching strategy will win you the car 2/3 of the time. I got curious and wanted to write a little function that simulates the problem many times and returns the proportion of wins if you switched and the proportion of wins if you stayed with your first choice. The function then plots the cumulative wins. First and foremost, I'm interested in hearing if my simulation is indeed replicating the Monty Problem, or if some aspect of the code got it wrong. Secondly, this function takes a long time to run once I get to about 10,000 simulations. I know I don't need this many simulations to prove this but I'd love to hear some ideas on how to make it more efficient. Thanks for your feedback! Monty_Hall=function(repetitions){ doors=c('A','B','C') stay_wins=0 switch_wins=0 series=data.frame(sim_num=seq(repetitions),cum_sum_stay=replicate(repetitions,0),cum_sum_switch=replicate(repetitions,0)) for(i in seq(repetitions)){ winning_door=sample(doors,1) contestant_chooses=sample(doors,1) if(contestant_chooses==winning_door) stay_wins=stay_wins+1 else switch_wins=switch_wins+1 series[i,'cum_sum_stay']=stay_wins series[i,'cum_sum_switch']=switch_wins } plot(series$sim_num,series$cum_sum_switch,col=2,ylab='Cumulative # of wins', xlab='Simulation #',main=sprintf('%d Simulations of the Monty Hall Paradox',repetitions),type='l') lines(series$sim_num,series$cum_sum_stay,col=4) legend('topleft',legend=c('Cumulative wins from switching', 'Cumulative wins from staying'),col=c(2,4),lty=1) result=list(series=series,stay_wins=stay_wins,switch_wins=switch_wins, proportion_stay_wins=stay_wins/repetitions, proportion_switch_wins=switch_wins/repetitions) return(result) } #Theory predicts that it is to the contestant's advantage if he #switches his choice to the other door. This function simulates the game #many times, and shows you the proportion of games in which staying or #switching would win the car. It also plots the cumulative wins for each strategy. Monty_Hall(100)

    Read the article

  • adding a class when link is clicked from Wordpress loop

    - by Carey Estes
    I am trying to isolate and add a class to a clicked anchor tag. The tags are getting pulled from a Wordpress loop. I can write JQuery to remove the "static" class, but it is removing the class from all tags in the div rather than just the one clicked and not adding the "active" class. Here is the WP loop <div class="more"> <a class="static" href="<?php bloginfo('template_url'); ?>/work/">ALL</a> <?php foreach ($tax_terms as $tax_term) { echo '<a class="static" href="' . esc_attr(get_term_link($tax_term, $taxonomy)) . '" title="' . sprintf( __( "View all posts in %s" ), $tax_term->name ) . '" ' . '>' . $tax_term->name.'</a>'; } ?> </div> Generates this html: <div class="more"> <a class="static" href="#">ALL</a> <a class="static" href="#">Things</a> <a class="static" href="#"> More Things</a> <a class="static" href="#">Objects</a> <a class="static" href="#">Goals</a> <a class="static" href="#">Books</a> <a class="static" href="#">Drawings</a> <a class="static" href="#">Thoughts</a> </div> JQuery: $("div.more a").on("click", function () { $("a.static").removeClass("static"); $(this).addClass("active"); }); I have reviwed the other similar questions here and here, but neither solution is working for me. Can this be done with JQuery or should I put a click event in the html inline anchor? It looks like it is working just for a second until the page reloads.

    Read the article

  • whats wrong with this php mysql_real_escape_string

    - by skyhigh
    Hi Atomic Number Latin English Abbreviation * check the variables for content */ /*** a list of filters ***/ $filters = array( 'searchtext' => array( 'filter' => FILTER_CALLBACK, 'options' => 'mysql_real_escape_string'), 'fieldname' => array( 'filter' => FILTER_CALLBACK, 'options' => 'mysql_real_escape_string') ); /*** escape all POST variables ***/ $input = filter_input_array(INPUT_POST, $filters); /*** check the values are not empty ***/ if(empty($input['fieldname']) || empty($input['searchtext'])) { echo 'Invalid search'; } else { /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'username'; /*** mysql password ***/ $password = 'password'; /*** mysql database name ***/ $dbname = 'periodic_table'; /*** connect to the database ***/ $link = @mysql_connect($hostname, $username, $password); /*** check if the link is a valid resource ***/ if(is_resource($link)) { /*** select the database we wish to use ***/ if(mysql_select_db($dbname, $link) === TRUE) { /*** sql to SELECT information***/ $sql = sprintf("SELECT * FROM elements WHERE %s = '%s'", $input['fieldname'], $input['searchtext']); /*** echo the sql query ***/ echo '<h3>'.$sql.'</h3>'; /*** run the query ***/ $result = mysql_query($sql); /*** check if the result is a valid resource ***/ if(is_resource($result)) { /*** check if we have more than zero rows ***/ if(mysql_num_rows($result) !== 0) { echo '<table>'; while($row=mysql_fetch_array($result)) { echo '<tr> <td>'.$row['atomicnumber'].'</td> <td>'.$row['latin'].'</td> <td>'.$row['english'].'</td> <td>'.$row['abbr'].'</td> </tr>'; } echo '</table>'; } else { /*** if zero results are found.. ***/ echo 'Zero results found'; } } else { /*** if the resource is not valid ***/ 'No valid resource found'; } } /*** if we are unable to select the database show an error ****/ else { echo 'Unable to select database '.$dbname; } /*** close the connection ***/ mysql_close($link); } else { /*** if we fail to connect ***/ echo 'Unable to connect'; } } } else { echo 'Please Choose An Element'; } ? I got this code from phppro.org tutorials site and i tried to run it. It gives Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established. .... Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'ODBC'@'localhost' (using password: NO).... I went to php.net and look it up "Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used." My questions are: 1-why they put single quotation around mysql_real_escape_string ? 2-They should establish a connection first, then use the $filter array statement with mysql_real_escape_string ?

    Read the article

  • Why I get a segmentation fault?

    - by frx08
    Why I get a segmentation fault? int main() { int height, width, step, step_mono, channels; int y, x; char str[15]; uchar *data, *data_mono; CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* contour = 0; CvPoint* p; CvFont font; CvCapture *capture; IplImage *frame = 0, *mono_thres = 0; capture = cvCaptureFromAVI("source.avi"); //capture video if(!cvGrabFrame(capture)) exit(0); frame = cvRetrieveFrame(capture); //capture the first frame from video source cvNamedWindow("Result", 1); while(1){ mono_thres = cvCreateImage(cvGetSize(frame), 8, 1); height = frame -> height; width = frame -> width; step = frame -> widthStep; step_mono = mono_thres -> widthStep; channels = frame -> nChannels; data = (uchar *)frame -> imageData; data_mono = (uchar *)mono_thres -> imageData; //converts the image to a binary highlighting the lightest zone for(y=0;y < height;y++) for(x=0;x < width;x++) data_mono[y*step_mono+x*1+0] = data[y*step+x*channels+0]; cvThreshold(mono_thres, mono_thres, 230, 255, CV_THRESH_BINARY); cvFindContours(mono_thres, storage, &contour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); //gets the coordinates of the contours and draws a circle and the coordinates in that point p = CV_GET_SEQ_ELEM(CvPoint, contour, 1); cvCircle(frame, *p, 1, CV_RGB(0,0,0), 2); cvInitFont(&font, CV_FONT_HERSHEY_PLAIN, 1.1, 1.1, 0, 1); sprintf(str, "(%d ,%d)", p->x, p->y); cvPutText(frame, str, cvPoint(p->x+5,p->y-5), &font, CV_RGB(0,0,0)); cvShowImage("Result", mono_thres); //next frame if(!cvGrabFrame(capture)) break; frame = cvRetrieveFrame(capture); if((cvWaitKey(10) & 255) == 27) break; } cvReleaseCapture(&capture); cvDestroyWindow("Result"); return 0; }

    Read the article

  • How to create a simple Proxy to access web servers in C

    - by jesusiniesta
    Hi. I’m trying to create an small Web Proxy in C. First, I’m trying to get a webpage, sending a GET frame to the server. I don’t know what I have missed, but I am not receiving any response. I would really appreciate if you can help me to find what is missing in this code. int main (int argc, char** argv) { int cache_size, //size of the cache in KiB port, port_google = 80, dir, mySocket, socket_google; char google[] = "www.google.es", ip[16]; struct sockaddr_in socketAddr; char buffer[10000000]; if (GetParameters(argc,argv,&cache_size,&port) != 0) return -1; GetIP (google, ip); printf("ip2 = %s\n",ip); dir = inet_addr (ip); printf("ip3 = %i\n",dir); /* Creation of a socket with Google */ socket_google = conectClient (port_google, dir, &socketAddr); if (socket_google < 0) return -1; else printf("Socket created\n"); sprintf(buffer,"GET /index.html HTTP/1.1\r\n\r\n"); if (write(socket_google, (void*)buffer, LONGITUD_MSJ+1) < 0 ) return 1; else printf("GET frame sent\n"); strcpy(buffer,"\n"); read(socket_google, buffer, sizeof(buffer)); // strcpy(message,buffer); printf("%s\n", buffer); return 0; } And this is the code I use to create the socket. I think this part is OK, but I copy it just in case. int conectClient (int puerto, int direccion, struct sockaddr_in *socketAddr) { int mySocket; char error[1000]; if ( (mySocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("Error when creating the socket\n"); return -2; } socketAddr->sin_family = AF_INET; socketAddr->sin_addr.s_addr = direccion; socketAddr->sin_port = htons(puerto); if (connect (mySocket, (struct sockaddr *)socketAddr,sizeof (*socketAddr)) == -1) { snprintf(error, sizeof(error), "Error in %s:%d\n", __FILE__, __LINE__); perror(error); printf("%s\n",error); printf ("-- Error when stablishing a connection\n"); return -1; } return mySocket; } Thanks!

    Read the article

  • multi-thread access MySQL error

    - by user188916
    I have written a simple multi-threaded C program to access MySQL,it works fine except when i add usleep() or sleep() function in each thread function. i created two pthreads in the main method, int main(){ mysql_library_init(0,NULL,NULL); printf("Hello world!\n"); init_pool(&p,100); pthread_t producer; pthread_t consumer_1; pthread_t consumer_2; pthread_create(&producer,NULL,produce_fun,NULL); pthread_create(&consumer_1,NULL,consume_fun,NULL); pthread_create(&consumer_2,NULL,consume_fun,NULL); mysql_library_end(); } void * produce_fun(void *arg){ pthread_detach(pthread_self()); //procedure while(1){ usleep(500000); printf("producer...\n"); produce(&p,cnt++); } pthread_exit(NULL); } void * consume_fun(void *arg){ pthread_detach(pthread_self()); MYSQL db; MYSQL *ptr_db=mysql_init(&db); mysql_real_connect(); //procedure while(1){ usleep(1000000); printf("consumer..."); int item=consume(&p); addRecord_d(ptr_db,"test",item); } mysql_thread_end(); pthread_exit(NULL); } void addRecord_d(MYSQL *ptr_db,const char *t_name,int item){ char query_buffer[100]; sprintf(query_buffer,"insert into %s values(0,%d)",t_name,item); //pthread_mutex_lock(&db_t_lock); int ret=mysql_query(ptr_db,query_buffer); if(ret){ fprintf(stderr,"%s%s\n","cannot add record to ",t_name); return; } unsigned long long update_id=mysql_insert_id(ptr_db); // pthread_mutex_unlock(&db_t_lock); printf("add record (%llu,%d) ok.",update_id,item); } the program output errors like: [Thread debugging using libthread_db enabled] [New Thread 0xb7ae3b70 (LWP 7712)] Hello world! [New Thread 0xb72d6b70 (LWP 7713)] [New Thread 0xb6ad5b70 (LWP 7714)] [New Thread 0xb62d4b70 (LWP 7715)] [Thread 0xb7ae3b70 (LWP 7712) exited] producer... producer... consumer...consumer...add record (31441,0) ok.add record (31442,1) ok.producer... producer... consumer...consumer...add record (31443,2) ok.add record (31444,3) ok.producer... producer... consumer...consumer...add record (31445,4) ok.add record (31446,5) ok.producer... producer... consumer...consumer...add record (31447,6) ok.add record (31448,7) ok.producer... Error in my_thread_global_end(): 2 threads didn't exit [Thread 0xb72d6b70 (LWP 7713) exited] [Thread 0xb6ad5b70 (LWP 7714) exited] [Thread 0xb62d4b70 (LWP 7715) exited] Program exited normally. and when i add pthread_mutex_lock in function addRecord_d,the error still exists. So what exactly the problem is?

    Read the article

  • Comet with multiple channels

    - by mark_dj
    Hello, I am writing an web app which needs to subscribe to multiple channels via javascript. I am using Atmosphere and Jersey as backend. However the jQuery plugin they work with only supports 1 channel. I've start buidling my own implementation. Now it works oke, but when i try to subscribe to 2 channels only 1 channel gets notified. Is the XMLHttpRequest blocking the rest of the XMLHttpRequests? Here's my code: function AtmosphereComet(url) { this.Connected = new signals.Signal(); this.Disconnected = new signals.Signal(); this.NewMessage = new signals.Signal(); var xhr = null; var self = this; var gotWelcomeMessage = false; var readPosition; var url = url; var onIncomingXhr = function() { if (xhr.readyState == 3) { if (xhr.status==200) // Received a message { var message = xhr.responseText; console.log(message); if(!gotWelcomeMessage && message.indexOf("") -1) { gotWelcomeMessage = true; self.Connected.dispatch(sprintf("Connected to %s", url)); } else { self.NewMessage.dispatch(message.substr(readPosition)); } readPosition = this.responseText.length; } } else if (this.readyState == 4) { self.disconnect(); } } var getXhr = function() { if ( window.location.protocol !== "file:" ) { try { return new window.XMLHttpRequest(); } catch(xhrError) {} } try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(activeError) {} } this.connect = function() { xhr = getXhr(); xhr.onreadystatechange = onIncomingXhr; xhr.open("GET", url, true); xhr.send(null); } this.disconnect = function() { xhr.onreadystatechange = null; xhr.abort(); } this.send = function(message) { } } And the test code: var connection1 = AtmosphereConnection("http://192.168.1.145:9999/botenveiling/b/product/status/2", AtmosphereComet); var connection2 = AtmosphereConnection("http://192.168.1.145:9999/botenveiling/b/product/status/1", AtmosphereComet); var output = function(msg) { alert(output); }; connection1.NewMessage.add(output); connection2.NewMessage.add(output); connection1.connect(); In AtmosphereConnection I instantiate the given AtmosphereComet with "new". I iterate over the object to check if it has to methods: "send", "connect", "disconnect". The reason for this is that i can switch the implementation later on when i complete the websocket implementation :) However I think the problem rests with the XmlHttpRequest object, or am i mistaken? P.S.: signals.Signal is a js observer/notifier library: http://millermedeiros.github.com/js-signals/ Testing: Firefox 3.6.1.3

    Read the article

  • What the best approach to iterate and "store" files over a directory in C (Linux) ?

    - by Andrei Ciobanu
    I have written a function that checks if to files are duplicates or not. This function signature is: int check_dup_memmap(char *f1_name, char *f2_name) It returns: (-1) - If something went wrong; (0) - If the two files are similar; (+1) - If the two files are different; The next step is to write a function that iterates through all the files in a certain directory,apply the previous function, and gives a report on every existing duplicates. Initially I've thought to write a function that generates a file with all the filenames in a certain directory and then, read that file again and gain and compare every two files. Here is that version of the function, that gets all the filenames in a certain directory. void *build_dir_tree(char *dirname, FILE *f) { DIR *cdir = NULL; struct dirent *ent = NULL; struct stat buf; if(f == NULL){ fprintf(stderr, "NULL file submitted. [build_dir_tree].\n"); exit(-1); } if(dirname == NULL){ fprintf(stderr, "NULL dirname submitted. [build_dir_tree].\n"); exit(-1); } if((cdir = opendir(dirname)) == NULL){ char emsg[MFILE_LEN]; sprintf(emsg, "Cannot open dir: %s [build_dir_tree]\t",dirname); perror(emsg); } chdir(dirname); while ((ent = readdir(cdir)) != NULL) { lstat(ent->d_name, &buf); if (S_ISDIR(buf.st_mode)) { if (strcmp(".", ent->d_name) == 0 || strcmp("..", ent->d_name) == 0) { continue; } build_dir_tree(ent->d_name, f); } else{ fprintf(f, "/%s/%s\n",util_get_cwd(),ent->d_name); } } chdir(".."); closedir(cdir); } Still I consider this approach a little inefficient, as I have to parse the file again and again. In your opinion what are other approaches should I follow: Write a datastructure and hold the files instead of writing them in the file ? I think for a directory with a lot of files, the memory will become very fragmented. Hold all the filenames in auto-expanding array, so that I can easy access every file by their index, because they will in a contiguous memory location. Map this file in memory using mmap() ? But mmap may fail, as the file gets to big. Any opinions on this. I want to choose the most efficient path, and access as few resources as possible. This is the requirement of the program... EDIT: Is there a way to get the numbers of files in a certain directory, without iterating through it ?

    Read the article

  • Linux termios VTIME not working?

    - by San Jacinto
    We've been bashing our heads off of this one all morning. We've got some serial lines setup between an embedded linux device and an Ubuntu box. Our reads are getting screwed up because our code usually returns two (sometimes more, sometimes exactly one) message reads instead of one message read per actual message sent. Here is the code that opens the serial port. InterCharTime is set to 4. void COMBaseClass::OpenPort() { cerr<< "openning port"<< port <<"\n"; struct termios newtio; this->fd = -1; int fdTemp; fdTemp = open( port, O_RDWR | O_NOCTTY); if (fdTemp < 0) { portOpen = 0; cerr<<"problem openning "<< port <<". Retrying"<<endl; usleep(1000000); return; } newtio.c_cflag = BaudRate | CS8 | CLOCAL | CREAD ;//| StopBits; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; /* set input mode (non-canonical, no echo,...) */ newtio.c_lflag = 0; newtio.c_cc[VTIME] = InterCharTime; /* inter-character timer in .1 secs */ newtio.c_cc[VMIN] = readBufferSize; /* blocking read until 1 char received */ tcflush(fdTemp, TCIFLUSH); tcsetattr(fdTemp,TCSANOW,&newtio); this->fd = fdTemp; portOpen = 1; } The other end is configured similarly for communication, and has one small section of particular iterest: while (1) { sprintf(out, "\r\nHello world %lu", ++ulCount); puts(out); WritePort((BYTE *)out, strlen(out)+1); sleep(2); } //while Now, when I run a read thread on the receiving machine, "hello world" is usually broken up over a couple messages. Here is some sample output: 1: Hello 2: world 1 3: Hello 4: world 2 5: Hello 6: world 3 where number followed by a colon is one message recieved. Can you see any error we are making? Thank you. Edit: For clarity, please view section 3.2 of this resource href="http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html. To my understanding, with a VTIME of a couple seconds (meaning vtime is set anywhere between 10 and 50, trial-and-error), and a VMIN of 1, there should be no reason that the message is broken up over two separate messages.

    Read the article

  • How do you return a string from a function correctly in Dynamic C?

    - by aquanar
    I have a program I am trying to debug, but Dynamic C apparently treats strings differently than normal C does (well, character arrays, anyway). I have a function that I made to make an 8 character long (well, 10 to include the \0 ) string of 0s and 1s to show me the contents of an 8-bit char variable. (IE, I give it the number 13, it returns the string "0001101\0" ) When I use the code below, it prints out !{happy face] 6 times (well, the second one is the happy face alone for some reason), each return comes back as 0xDEAE or "!\x02. I thought it would dereference it and return the appropriate string, but it appears to just be sending the pointer and attempting to parse it. This may seem silly, but my experience was actually in C++ and Java, so going back to C brings up a few issues that were dealt with in later programming languages that I'm not entirely sure how to deal with (like the lack of string variables). How could I fix this code, or how would be a better way to do what I am trying to do (I thought maybe sending in a pointer to a character array and working on it from the function might work, but I thought I should ask to see if maybe I'm just trying to reinvent the wheel). Currently I have it set up like this: this is an excerpt from the main() display[0] = '\0'; for(i=0;i<6;i++) { sprintf(s, "%s ", *char_to_bits(buffer[i])); strcat(display, s); } DispStr(8,5, display); and this is the offending function: char *char_to_bits(char x) { char bits[16]; strcpy(bits,"00000000\0"); if (x & 0x01) bits[7]='1'; if (x & 0x02) bits[6]='1'; if (x & 0x04) bits[5]='1'; if (x & 0x08) bits[4]='1'; if (x & 0x10) bits[3]='1'; if (x & 0x20) bits[2]='1'; if (x & 0x40) bits[1]='1'; if (x & 0x80) bits[0]='1'; return bits; } and just for the sake of completion, the other function is used to output to the stdio window at a specific location: void DispStr(int x, int y, char *s) { x += 0x20; y += 0x20; printf ("\x1B=%c%c%s", x, y, s); }

    Read the article

  • Unable to list contents/remove directory (linux ext3)

    - by RedKrieg
    System is CentOS5 x86_64, completely up to date. I've got a folder that can't be listed (ls just hangs, eating memory until it is killed). The directory size is nearly 500k: root@server [/home/user/public_html/domain.com/wp-content/uploads/2010/03]# stat . File: `.' Size: 458752 Blocks: 904 IO Block: 4096 directory Device: 812h/2066d Inode: 44499071 Links: 2 Access: (0755/drwxr-xr-x) Uid: ( 3292/ user) Gid: ( 3287/ user) Access: 2012-06-29 17:31:47.000000000 -0400 Modify: 2012-10-23 14:41:58.000000000 -0400 Change: 2012-10-23 14:41:58.000000000 -0400 I can see the file names if I use ls -1f, but it just repeats the same 48 files ad infinitum, all of which have non-ascii characters somewhere in the file name: La-critic\363-al-servicio-la-privacidad-300x160.jpg When I try to access the files (say to copy them or remove them) I get messages like the following: lstat("/home/user/public_html/domain.com/wp-content/uploads/2010/03/Sebast\355an-Pi\361era-el-balc\363n-150x120.jpg", 0x7fff364c52c0) = -1 ENOENT (No such file or directory) I tried altering the code found on this man page and modified the code to call unlink for each file. I get the same ENOENT error from the unlink call: unlink("/home/user/public_html/domain.com/wp-content/uploads/2010/03/Marca-naci\363n-Madrid-150x120.jpg") = -1 ENOENT (No such file or directory) I also straced a "touch", grabbed the syscalls it makes and replicated them, then tried to unlink the resulting file by name. This works fine, but the folder still contains an entry by the same name after the operation completes and the program runs for an arbitrarily long time (strace output ended up at 20GB after 5 minutes and I stopped the process). I'm stumped on this one, I'd really prefer not to have to take this production machine (hundreds of customers) offline to fsck the filesystem, but I'm leaning toward that being the only option at this point. If anyone's had success using other methods for removing files (by inode number, I can get those with the getdents code) I'd love to hear them. (Yes, I've tried find . -inum <inode> -exec rm -fv {} \; and it still has the problem with unlink returning ENOENT) For those interested, here's the diff between that man page's code and mine. I didn't bother with error checking on mallocs, etc because I'm lazy and this is a one-off: root@server [~]# diff -u listdir-orig.c listdir.c --- listdir-orig.c 2012-10-23 15:10:02.000000000 -0400 +++ listdir.c 2012-10-23 14:59:47.000000000 -0400 @@ -6,6 +6,7 @@ #include <stdlib.h> #include <sys/stat.h> #include <sys/syscall.h> +#include <string.h> #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) @@ -17,7 +18,7 @@ char d_name[]; }; -#define BUF_SIZE 1024 +#define BUF_SIZE 1024*1024*5 int main(int argc, char *argv[]) { @@ -26,11 +27,16 @@ struct linux_dirent *d; int bpos; char d_type; + int deleted; + int file_descriptor; fd = open(argc > 1 ? argv[1] : ".", O_RDONLY | O_DIRECTORY); if (fd == -1) handle_error("open"); + char* full_path; + char* fd_path; + for ( ; ; ) { nread = syscall(SYS_getdents, fd, buf, BUF_SIZE); if (nread == -1) @@ -55,7 +61,24 @@ printf("%4d %10lld %s\n", d->d_reclen, (long long) d->d_off, (char *) d->d_name); bpos += d->d_reclen; + if ( d_type == DT_REG ) + { + full_path = malloc(strlen((char *) d->d_name) + strlen(argv[1]) + 2); //One for the /, one for the \0 + strcpy(full_path, argv[1]); + strcat(full_path, (char *) d->d_name); + + //We're going to try to "touch" the file. + //file_descriptor = open(full_path, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666); + //fd_path = malloc(32); //Lazy, only really needs 16 + //sprintf(fd_path, "/proc/self/fd/%d", file_descriptor); + //utimes(fd_path, NULL); + //close(file_descriptor); + deleted = unlink(full_path); + if ( deleted == -1 ) printf("Error unlinking file\n"); + break; //Break on first try + } } + break; //Break on first try } exit(EXIT_SUCCESS);

    Read the article

  • Get Asynchronous HttpResponse through Silverlight (F#)

    - by jack2010
    I am a newbie with F# and SL and playing with getting asynchronous HttpResponse through Silverlight. The following is the F# code pieces, which is tested on VS2010 and Window7 and works well, but the improvement is necessary. Any advices and discussion, especially the callback part, are welcome and great thanks. module JSONExample open System open System.IO open System.Net open System.Text open System.Web open System.Security.Authentication open System.Runtime.Serialization [<DataContract>] type Result<'TResult> = { [<field: DataMember(Name="code") >] Code:string [<field: DataMember(Name="result") >] Result:'TResult array [<field: DataMember(Name="message") >] Message:string } // The elements in the list [<DataContract>] type ChemicalElement = { [<field: DataMember(Name="name") >] Name:string [<field: DataMember(Name="boiling_point") >] BoilingPoint:string [<field: DataMember(Name="atomic_mass") >] AtomicMass:string } //http://blogs.msdn.com/b/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx //http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!194.entry type System.Net.HttpWebRequest with member x.GetResponseAsync() = Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse) type RequestState () = let mutable request : WebRequest = null let mutable response : WebResponse = null let mutable responseStream : Stream = null member this.Request with get() = request and set v = request <- v member this.Response with get() = response and set v = response <- v member this.ResponseStream with get() = responseStream and set v = responseStream <- v let allDone = new System.Threading.ManualResetEvent(false) let getHttpWebRequest (query:string) = let query = query.Replace("'","\"") let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) request.Method <- "GET" request.ContentType <- "application/x-www-form-urlencoded" request let GetAsynResp (request : HttpWebRequest) (callback: AsyncCallback) = let myRequestState = new RequestState() myRequestState.Request <- request let asyncResult = request.BeginGetResponse(callback, myRequestState) () // easy way to get it to run syncrnously w/ the asynch methods let GetSynResp (request : HttpWebRequest) : HttpWebResponse = let response = request.GetResponseAsync() |> Async.RunSynchronously downcast response let RespCallback (finish: Stream -> _) (asynchronousResult : IAsyncResult) = try let myRequestState : RequestState = downcast asynchronousResult.AsyncState let myWebRequest1 : WebRequest = myRequestState.Request myRequestState.Response <- myWebRequest1.EndGetResponse(asynchronousResult) let responseStream = myRequestState.Response.GetResponseStream() myRequestState.ResponseStream <- responseStream finish responseStream myRequestState.Response.Close() () with | :? WebException as e -> printfn "WebException raised!" printfn "\n%s" e.Message printfn "\n%s" (e.Status.ToString()) () | _ as e -> printfn "Exception raised!" printfn "Source : %s" e.Source printfn "Message : %s" e.Message () let printResults (stream: Stream)= let result = try use reader = new StreamReader(stream) reader.ReadToEnd(); finally () let data = Encoding.Unicode.GetBytes(result); let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L let JsonSerializer = Json.DataContractJsonSerializer(typeof<Result<ChemicalElement>>) let result = JsonSerializer.ReadObject(stream) :?> Result<ChemicalElement> if result.Code<>"/api/status/ok" then raise (InvalidOperationException(result.Message)) else result.Result |> Array.iter(fun element->printfn "%A" element) let test = // Call Query (w/ generics telling it you wand an array of ChemicalElement back, the query string is wackyJSON too –I didn’t build it don’t ask me! let request = getHttpWebRequest "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]" //let response = GetSynResp request let response = GetAsynResp request (AsyncCallback (RespCallback printResults)) () ignore(test) System.Console.ReadLine() |> ignore

    Read the article

  • Symfony, in remote host: Error 500. Unknown record property / related component "algorithm" on "sfGu

    - by user248959
    Hi, after deploying, i get the error below after loggingin. Sf 1.3, sfDoctrineGuardPlugin. And i have this schema.yml in config/doctrine: Usuario: inheritance: extends: sfGuardUser type: simple columns: username: type: string(128) notnull: false unique: true nombre_apellidos: string(60) sexo: string(5) fecha_nac: date provincia: string(60) localidad: string(255) email_address: string(255) fotografia: string(255) avatar: string(255) avatar_mensajes: string(255) relations: Usuario: local: user1_id foreign: user2_id refClass: AmigoUsuario equal: true 500 | Internal Server Error | Doctrine_Record_UnknownPropertyException Unknown record property / related component "algorithm" on "sfGuardUser" stack trace * at () in SF_ROOT_DIR/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Record/Filter/Standard.php line 55 ... 52. */ 53. public function filterGet(Doctrine_Record $record, $name) 54. { 55. throw new Doctrine_Record_UnknownPropertyException(sprintf('Unknown record property / related component "%s" on "%s"', $name, get_class($record))); 56. } 57. } * at Doctrine_Record_Filter_Standard->filterGet(object('sfGuardUser'), 'algorithm') in SF_ROOT_DIR/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Record.php line 1382 ... 1379. $success = false; 1380. foreach ($this->_table->getFilters() as $filter) { 1381. try { 1382. $value = $filter->filterGet($this, $fieldName); 1383. $success = true; 1384. } catch (Doctrine_Exception $e) {} 1385. } * at Doctrine_Record->_get('algorithm', 1) in SF_ROOT_DIR/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Record.php line 1337 ... 1334. return $this->$accessor($load); 1335. } 1336. } 1337. return $this->_get($fieldName, $load); 1338. } 1339. 1340. protected function _get($fieldName, $load = true) * at Doctrine_Record->get('algorithm') in SF_ROOT_DIR/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/record/sfDoctrineRecord.class.php line 212 ... 209. return call_user_func_array( 210. array($this, $verb), 211. array_merge(array($entityName), $arguments) 212. ); 213. } else { 214. $failed = true; 215. } * at sfDoctrineRecord->__call(array(object('sfGuardUser'), 'get'), array('algorithm')) in n/a line n/a ... * at sfGuardUser->getAlgorithm('getAlgorithm', array()) in SF_ROOT_DIR/plugins/sfDoctrineGuardPlugin/lib/model/doctrine/PluginsfGuardUser.class.php line 96 ... 93. */ 94. public function checkPasswordByGuard($password) 95. { 96. $algorithm = $this->getAlgorithm(); 97. if (false !== $pos = strpos($algorithm, '::')) 98. { 99. $algorithm = array(substr($algorithm, 0, $pos), substr($algorithm, $pos + 2)); * at PluginsfGuardUser->checkPasswordByGuard() in SF_ROOT_DIR/plugins/sfDoctrineGuardPlugin/lib/model/doctrine/PluginsfGuardUser.class.php line 83 ... 80. } 81. else 82. { 83. return $this->checkPasswordByGuard($password); 84. } 85. } 86. * at PluginsfGuardUser->checkPassword('m') in SF_ROOT_DIR/lib/sfGuardValidatorUserByEmail.class.php line 28 ... 25. { 26. // password is ok? 27. 28. if ($user->checkPassword($password)) 29. { 30. 31. //die("entro"); * at sfGuardValidatorUserByEmail->doClean('m') Any idea? Javi

    Read the article

  • Creating a Comment Anchor

    - by John
    Hello, The function below allows a user to insert a comment into a MySQL table called "comment." Then, the file "comments2.php" displays all comments for a given submission. Right after a user submits a comment, I would like the top of the user's browser to be anchored by the comment the user just submitted. How can I do this? Thanks in advance, John The function: function show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl) { echo '<form action="http://www...com/.../comments/comments2.php" method="post"> <input type="hidden" value="'.$_SESSION['loginid'].'" name="uid"> <input type="hidden" value="'.$submissionid.'" name="submissionid"> <input type="hidden" value="'.stripslashes($submission).'" name="submission"> <input type="hidden" value="'.$url.'" name="url"> <input type="hidden" value="'.$submittor.'" name="submittor"> <input type="hidden" value="'.$submissiondate.'" name="submissiondate"> <input type="hidden" value="'.$countcomments.'" name="countcomments"> <input type="hidden" value="'.$dispurl.'" name="dispurl"> <label class="addacomment" for="title">Add a comment:</label> <textarea class="checkMax" name="comment" type="comment" id="comment" maxlength="1000"></textarea> <div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div> </form> '; } The file comments2.php contains: $query = sprintf("INSERT INTO comment VALUES (NULL, %d, %d, '%s', NULL)", $uid, $subid, $comment); mysql_query($query) or die(mysql_error()); $submissionid = mysql_real_escape_string($_POST['submissionid']); $submissionid = mysql_real_escape_string($_GET['submissionid']); $sqlStr = "SELECT comment.comment, comment.datecommented, login.username FROM comment LEFT JOIN login ON comment.loginid=login.loginid WHERE submissionid=$submissionid ORDER BY comment.datecommented ASC LIMIT 100"; $tzFrom1 = new DateTimeZone('America/New_York'); $tzTo1 = new DateTimeZone('America/Phoenix'); $result = mysql_query($sqlStr); $arr = array(); echo "<table class=\"commentecho\">"; $count = 1; while ($row = mysql_fetch_array($result)) { $dt1 = new DateTime($row["datecommented"], $tzFrom1); $dt1->setTimezone($tzTo1); echo '<tr>'; echo '<td rowspan="3" class="commentnamecount">'.$count++.'.</td>'; echo '<td class="commentname2"><a href="http://www...com/.../members/index.php?profile='.$row["username"].'">'.$row["username"].'</a></td>'; echo '<td rowspan="3" class="commentname1">'.stripslashes($row["comment"]).'</td>'; echo '</tr>'; echo '<tr>'; echo '<td class="commentname2">'.$dt1->format('F j, Y').'</td>'; echo '</tr>'; echo '<tr>'; echo '<td class="commentname2a">'.$dt1->format('g:i a').'</td>'; echo '</tr>'; } echo "</table>"; The fields in the MySQL table "comment": commentid loginid submissionid comment datecommented

    Read the article

  • Concat wchar_t Unicode strings in C?

    - by Doori Bar
    I'm a beginner, I play with FindFirstFileW() of the winapi - C. The unicoded path is: " \\?\c:\Français\", and I would like to concat "*" to this path of type wchar_t (then I will use it as an arg for FindFirstFileW()). I made two test cases of mine, the first is ansi_string() which seem to work fine, the second is unicode_string() - which I don't quite understand how should I concat the additional "*" char to the unicoded path. I write the strings to a file, because I'm not able to print Unicoded characters to stdout. Note: my goal is to learn, which means I'll appreciate guidance and references to the appropriate resources regards my scenario, I'm very much a beginner and this is my first attempt with Unicode. Thanks, Doori Bar #include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <string.h> #include <errno.h> void *error_malloc(int size); void ansi_string(char **str1, char **str2); void unicode_string(wchar_t **wstr1, wchar_t **wstr2); void unicode_string(wchar_t **wstr1, wchar_t **wstr2) { /* assign wstr1 with the path: \\?\c:\Français\ */ *wstr1 = error_malloc((wcslen(L"\\\\?\\c:\\Français\\")+1) *sizeof(**wstr1)); wcscpy(*wstr1,L"\\\\?\\c:\\Français\\"); /* concat wstr1+"*" , assign wstr2 with: \\?\c:\Français\* */ *wstr2 = error_malloc((wcslen(*wstr1) + 1 + 1) * sizeof(**wstr1)); /* swprintf(*wstr2,"%ls*",*wstr1); */ /* how should I concat wstr1+"*"? */ wcscpy(*wstr2,L"\\\\?\\c:\\Français\\"); } void ansi_string(char **str1, char **str2) { /* assign str1 with the path: c:\English\ */ *str1 = error_malloc(strlen("c:\\English\\") + 1); strcpy(*str1,"c:\\English\\"); /* concat str1+"*" , assign str2 with: c:\English\* */ *str2 = error_malloc(strlen(*str1) + 1 + 1); sprintf(*str2,"%s*",*str1); } void *error_malloc(int size) { void *ptr; int errornumber; if ((ptr = malloc(size)) == NULL) { errornumber = errno; fprintf(stderr,"Error: malloc(): %d; Error Message: %s;\n", errornumber,strerror(errornumber)); exit(1); } return ptr; } int main(void) { FILE *outfile; char *str1; char *str2; wchar_t *wstr1; wchar_t *wstr2; if ((outfile = fopen("out.bin","w")) == NULL) { printf("Error: fopen failed."); return 1; } ansi_string(&str1,&str2); fwrite(str2, sizeof(*str2), strlen(str2), outfile); printf("strlen: %d\n",strlen(str2)); printf("sizeof: %d\n",sizeof(*str2)); free(str1); free(str2); unicode_string(&wstr1,&wstr2); fwrite(wstr2, sizeof(*wstr2), wcslen(wstr2), outfile); printf("wcslen: %d\n",wcslen(wstr2)); printf("sizeof: %d\n",sizeof(*wstr2)); free(wstr1); free(wstr2); fclose(outfile); return 0; }

    Read the article

  • multiple valgrind errors: Conditional jump or move depends on uninitialised value(s)

    - by Hristo
    I'm running valgrind and I'm getting the following error (this is not the only one): ==21743== Conditional jump or move depends on uninitialised value(s) ==21743== at 0x4A06509: index (mc_replace_strmem.c:164) ==21743== by 0x33B7CBB3CD: gaih_inet (in /lib64/libc-2.5.so) ==21743== by 0x33B7CBD629: getaddrinfo (in /lib64/libc-2.5.so) ==21743== by 0x401A5F: tunnelURL (proxy.c:336) ==21743== by 0x40142A: client_thread (proxy.c:194) ==21743== by 0x33B8806616: start_thread (in /lib64/libpthread-2.5.so) ==21743== by 0x33B7CD3C2C: clone (in /lib64/libc-2.5.so) My tunnelURL() function looks like this: char * tunnelURL(char *url) { char * a = strstr(url, "//"); a += 2; char * path = strstr(a, "/"); char host[256]; strncpy (host, a, strlen(a)-strlen(path)); /* * The following is courtesy of Beej's Guide */ int status; int proxySocketFD; struct addrinfo hints; struct addrinfo *servinfo; // will point to the results memset(&hints, 0, sizeof(hints)); // make sure the struct is empty hints.ai_family = AF_INET; // don't care IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((status = getaddrinfo(host, "80", &hints, &servinfo)) != 0) { perror("getaddrinfo() fail"); exit(1); } // create socket if ((proxySocketFD = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1) { perror("proxy socket() fail"); exit(1); } // connect if (connect(proxySocketFD, servinfo->ai_addr, servinfo->ai_addrlen) != 0) { printf("connect() fail"); exit(1); } // construct request char request[strlen(path) + strlen(host) + 26]; sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", path, host); printf("%s", request); // send request send(proxySocketFD, request, strlen(request), 0); // receive response int i = 0; int amntRecvd = 0; char *pageContentBuffer = (char*) malloc(4096 * sizeof(char)); while ((amntRecvd = recv(proxySocketFD, pageContentBuffer + i, 4096, 0)) > 0) { i += amntRecvd; realloc(pageContentBuffer, i * 4096 * sizeof(char)); } // close proxy socket close(proxySocketFD); // deallocate memory freeaddrinfo(servinfo); return pageContentBuffer; } Line 336 corresponds to the if statement with the getaddrinfo() function call. I'm not really sure what I haven't initialized. The string I'm passing in "should" be already set... I'm printing it out just fine. I also get another error corresponding to the same line of code: ==21743== Use of uninitialised value of size 8 ==21743== at 0x33B7D05816: __nscd_cache_search (in /lib64/libc-2.5.so) ==21743== by 0x33B7D0438B: nscd_gethst_r (in /lib64/libc-2.5.so) ==21743== by 0x33B7D04B26: __nscd_gethostbyname2_r (in /lib64/libc-2.5.so) ==21743== by 0x33B7CE9F5E: gethostbyname2_r@@GLIBC_2.2.5 (in /lib64/libc-2.5.so) ==21743== by 0x33B7CBC522: gaih_inet (in /lib64/libc-2.5.so) ==21743== by 0x33B7CBD629: getaddrinfo (in /lib64/libc-2.5.so) ==21743== by 0x401A5F: tunnelURL (proxy.c:336) ==21743== by 0x40142A: client_thread (proxy.c:194) ==21743== by 0x33B8806616: start_thread (in /lib64/libpthread-2.5.so) ==21743== by 0x33B7CD3C2C: clone (in /lib64/libc-2.5.so) Any ideas as to what might becausing this? This is written in C btw... Thanks, Hristo

    Read the article

  • Binary data from a serial port in linux using c

    - by user1680393
    I am reading binary data from a serial port on Phidget sbc using Linux to get a command from an application running on a PC. I wrote a test program in VB to read the data into a byte array and convert it to decimal to use it but can’t figure out how to do it in c. I am unable to come up with anything with the research I have done on the internet. Command sent from PC is 0x0F. To check if I am getting correct data I read the data and send it back. Here is what I get back. Returned data has a carriage return added to it. Hex Display 0F00 0000 0D ‘\’ Display \0F\00\00\00\r Normal display just display a strange character. This tells me that the data is there that I can use, but can’t figure out to extract the value 0F or 15. How can I convert the incoming data to use it? I tried converting the received data using strtol, but it returns 0. I also tried setting the port to raw but it did not make any difference. unsigned char buffer1[1]; int ReadPort1() { int result; result = read(file1, &buffer1,1); if(result > 0) { WritePort1(buffer1); sprintf(tempstr, "Port1 data %s %d", buffer1, result); DisplayText(2,tempstr); } return result; } Port Open/Setup void OpenPort1() { //file1 = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NONBLOCK); file1 = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NODELAY); if(file1 < 0) printf("Error opening serial port1.\n"); else { SetPort(file1, 115200, 8, 1, 0, 1); port1open = 1; } } void SetPort(int fd, int Baud_Rate, int Data_Bits, int Stop_Bits, int Parity, int raw) { long BAUD; // derived baud rate from command line long DATABITS; long STOPBITS; long PARITYON; long PARITY; struct termios newtio; switch (Baud_Rate) { case 115200: BAUD = B115200; break; case 38400: BAUD = B38400; break; case 19200: BAUD = B19200; break; case 9600: BAUD = B9600; break; } //end of switch baud_rate switch (Data_Bits) { case 8: default: DATABITS = CS8; break; case 7: DATABITS = CS7; break; case 6: DATABITS = CS6; break; case 5: DATABITS = CS5; break; } //end of switch data_bits switch (Stop_Bits) { case 1: default: STOPBITS = 0; break; case 2: STOPBITS = CSTOPB; break; } //end of switch stop bits switch (Parity) { case 0: default: //none PARITYON = 0; PARITY = 0; break; case 1: //odd PARITYON = PARENB; PARITY = PARODD; break; case 2: //even PARITYON = PARENB; PARITY = 0; break; } //end of switch parity newtio.c_cflag = BAUD | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; if(raw == 1) { newtio.c_oflag &= ~OPOST; newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); } else { newtio.c_lflag = 0; //ICANON; newtio.c_oflag = 0; } newtio.c_cc[VMIN]=1; newtio.c_cc[VTIME]=0; tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); }

    Read the article

  • User Getting Logged Out After Making First Comment

    - by John
    Hello, I am using a login system that works well. I am also using a comment system. The comment function does not show up unless the user is logged in (as shown in commentformonoff.php below). When a user makes a comment, the info is passed from the function "show_commentbox" to the file comments2a.php. Then, the info is passed to the file comments2.php. When the site is first pulled up on a browser, after logging in and making a comment, the user is logged out. After logging in a second time during the same browser session, the user is no longer logged out after making a comment. How can I keep the user logged in after making the first comment? Thanks in advance, John Commentformonoff.php: <?php if (!isLoggedIn()) { if (isset($_POST['cmdlogin'])) { if (checkLogin($_POST['username'], $_POST['password'])) { show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl); } else { echo "<div class='logintocomment'>Login to comment</div>"; } } else { echo "<div class='logintocomment'>Login to comment</div>"; } } else { show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl); } ?> Function "show_commentbox": function show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl) { echo '<form action="http://www...com/.../comments/comments2a.php" method="post"> <input type="hidden" value="'.$_SESSION['loginid'].'" name="uid"> <input type="hidden" value="'.$_SESSION['username'].'" name="u"> <input type="hidden" value="'.$submissionid.'" name="submissionid"> <input type="hidden" value="'.stripslashes($submission).'" name="submission"> <input type="hidden" value="'.$url.'" name="url"> <input type="hidden" value="'.$submittor.'" name="submittor"> <input type="hidden" value="'.$submissiondate.'" name="submissiondate"> <input type="hidden" value="'.$countcomments.'" name="countcomments"> <input type="hidden" value="'.$dispurl.'" name="dispurl"> <label class="addacomment" for="title">Add a comment:</label> <textarea class="checkMax" name="comment" type="comment" id="comment" maxlength="1000"></textarea> <div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div> </form> '; } Included in comments2a.php: $uid = mysql_real_escape_string($_POST['uid']); $u = mysql_real_escape_string($_POST['u']); $query = sprintf("INSERT INTO comment VALUES (NULL, %d, %d, '%s', NULL)", $uid, $subid, $comment); mysql_query($query) or die(mysql_error()); $lastcommentid = mysql_insert_id(); header("Location: comments2.php?submission=".$submission."&submissionid=".$submissionid."&url=".$url."&submissiondate=".$submissiondate."&comment=".$comment."&subid=".$subid."&uid=".$uid."&u=".$u."&submittor=".$submittor."&countcomments=".$countcomments."&dispurl=".$dispurl."#comment-$lastcommentid"); exit(); Included in comments2.php: if($_SERVER['REQUEST_METHOD'] == "POST"){header('Location: http://www...com/.../comments/comments2.php?submission='.$submission.'&submissionid='.$submissionid.'&url='.$url.'&submissiondate='.$submissiondate.'&submittor='.$submittor.'&countcomments='.$countcomments.'&dispurl='.$dispurl.'');} $uid = mysql_real_escape_string($_GET['uid']); $u = mysql_real_escape_string($_GET['u']);

    Read the article

  • Test whether pixel is inside the blobs for ofxOpenCV

    - by mia
    I am doing an application of the concept of the dodgeball and need to test of the pixel of the ball is in the blobs capture(which is the image of the player) I am stucked and ran out of idea of how to implement it. I manage to do a little progress which have the blobs but I not sure how to test it. Please help. I am a newbie who in a desperate condition. Thank you. This is some of my code. void testApp::setup(){ #ifdef _USE_LIVE_VIDEO vidGrabber.setVerbose(true); vidGrabber.initGrabber(widthS,heightS); #else vidPlayer.loadMovie("fingers.mov"); vidPlayer.play(); #endif widthS = 320; heightS = 240; colorImg.allocate(widthS,heightS); grayImage.allocate(widthS,heightS); grayBg.allocate(widthS,heightS); grayDiff.allocate(widthS,heightS); ////<---what I want bLearnBakground = true; threshold = 80; //////////circle////////////// counter = 0; radius = 0; circlePosX = 100; circlePosY=200; } void testApp::update(){ ofBackground(100,100,100); bool bNewFrame = false; #ifdef _USE_LIVE_VIDEO vidGrabber.grabFrame(); bNewFrame = vidGrabber.isFrameNew(); #else vidPlayer.idleMovie(); bNewFrame = vidPlayer.isFrameNew(); #endif if (bNewFrame){ if (bLearnBakground == true){ grayBg = grayImage; // the = sign copys the pixels from grayImage into grayBg (operator overloading) bLearnBakground = false; } #ifdef _USE_LIVE_VIDEO colorImg.setFromPixels(vidGrabber.getPixels(),widthS,heightS); #else colorImg.setFromPixels(vidPlayer.getPixels(),widthS,heightS); #endif grayImage = colorImg; grayDiff.absDiff(grayBg, grayImage); grayDiff.threshold(threshold); contourFinder.findContours(grayDiff, 20, (340*240)/3, 10, true); // find holes } ////////////circle//////////////////// counter = counter + 0.05f; if(radius>=50){ circlePosX = ofRandom(10,300); circlePosY = ofRandom(10,230); } radius = 5 + 3*(counter); } void testApp::draw(){ // draw the incoming, the grayscale, the bg and the thresholded difference ofSetColor(0xffffff); //white colour grayDiff.draw(10,10);// draw start from point (0,0); // we could draw the whole contour finder // or, instead we can draw each blob individually, // this is how to get access to them: for (int i = 0; i < contourFinder.nBlobs; i++){ contourFinder.blobs[i].draw(10,10); } ///////////////circle////////////////////////// //let's draw a circle: ofSetColor(0,0,255); char buffer[255]; float a = radius; sprintf(buffer,"radius = %i",a); ofDrawBitmapString(buffer, 120, 300); if(radius>=50) { ofSetColor(255,255,255); counter = 0; } else{ ofSetColor(255,0,0); } ofFill(); ofCircle(circlePosX,circlePosY,radius); }

    Read the article

  • Create dropdown from multi array + PHP class

    - by chris
    Hi there, Well, I am writing class that creates a DOB selection dropdown. I am having figure out the dropdown(), it seems working but not exactly. Code just creates one drop down, and under this dropdown all day, month and year data are in one selection. like: <label> <sup>*</sup>DOB</label> <select name="form_bod_year"> <option value=""/> <option selected="" value="0">1</option> <option value="1">2</option> <option value="2">3</option> <option value="3">4</option> <option value="4">5</option> <option value="5">6</option> .. <option value="29">30</option> <option value="30">31</option> <option value="1">January</option> <option value="2">February</option> .. <option value="11">November</option> <option value="12">December</option> <option selected="" value="0">1910</option> <option value="1">1911</option> .. <option value="98">2008</option> <option value="99">2009</option> <option value="100">2010</option> </select> Here is my code, I wonder that why all datas are in one selection. It has to be tree selction - Day:Month:Year. //dropdown connector class DropDownConnector { var $dropDownsDatas; var $field_label; var $field_name; var $locale; function __construct($dropDownsDatas, $field_label, $field_name, $locale) { $this-dropDownsDatas = $dropDownsDatas; $this-field_label = $field_label; $this-field_name = $field_name; $this-locale = $locale; } function getValue(){ return $_POST[$this-field_name]; } function dropdown(){ $selectedVal = $this-getValue($this-field_name); foreach($this-dropDownsDatas as $keys=$values){ foreach ($values as $key=$value){ $selected = ($key == $selectedVal ? "selected" : "" ); $options .= sprintf('%s',$key,$value); }; }; return $select_start = "$this-field_desc".$options.""; } function getLabel(){ $non_req = $this-getNotRequiredData(); $req = in_array($this-field_name, $non_req) ? '' : '*'; return $this-field_label ? $req . $this-field_label : ''; } function __toString() { $id = $this-field_name; $label = $this-getLabel(); $field = $this-dropdown(); return 'field_name.'"'.$label.''.$field.''; } } function generateForm ($lang,$country_list,$states_list,$days_of_month,$month_list,$years){ $xx = array( 'form_bod_day' = $days_of_month, 'form_bod_month' = $month_list, 'form_bod_year' = $years); echo $dropDownConnector = new DropDownConnector($xx,'DOB','bod','en-US'); } // Call php class to use class on external functionss. $avInq = new formGenerator; $lang='en-US'; echo generateForm ($lang,$country_list,$states_list,$days_of_month,$month_list,$years);

    Read the article

  • Retreiving multiple rows from a loop-created form... Stuck.

    - by hangston
    Hi All, Let me start by saying that I'm new to PHP, but I'm here to learn and would really appreciate your help. I use the following code to pull in data and create a form. This creates up to 40 lines for a user to fill out. Each line consists of the same information: Description, Amount, and Frequency. The remainder of the information needed is generated by the database. (See hidden fields) <?php $row = 0; do { $optid = $row_options['option_id']; echo "<tr>\n\t<td>" . htmlentities($row_options['option']) . "</td>\n"; echo "\t<td>" . "<input name='description' type='text' size='40' maxlength='120'/>" . "</td>\n"; echo "\t<td>" . "<input name='option_id' type='hidden' value='$optid' />$<input name='amount' type='text' size='10' maxlength='7'/>" . "</td>\n"; echo "\t<td>" . "<select name='assisted_frequency'> <option value='Monthly'>Monthly</option> <option value='Weekly'>Weekly</option> <option value='Daily'>Daily</option> <option value='Hourly'>Hourly</option> <option value='One-Time'>One-Time</option> </select>" . "</td>\n</tr>\n"; $array[$row] = array( $arraydesc[$row] = $_POST['description'], $arrayamto[$row] = $_POST['amount'], $arrayoptid[$row] = $optid, $arrayfreq[$row] = $_POST['frequency'], ); $row ++; } while ($row_options = mysql_fetch_assoc($options)); $counter = $row - 1; ?> I'm having troubles retrieving the information that the user inputs. My intent is to loop through each row after the user has input their information, then upload the mix of my database information and the user's information into another database. For example, the user would see, albeit prettier: form1 Option 1: description [input box] amount [input box] frequency [option box] Option 2: description [input box] amount [input box] frequency [option box] Option 3: description [input box] amount [input box] frequency [option box] Option 4: description [input box] amount [input box] frequency [option box] submit Upon submitting the form above, I'm using a query similar to the following to input the data into the database: for($row=0; $row<=$counter; $row++){ $insertSQL2 = sprintf("INSERT INTO table (option_id, amount, description, frequency) VALUES (%s, %s, %s, %s)", GetSQLValueString($arrayoptid[$row], "int"), GetSQLValueString($arrayamto[$row], "int"), GetSQLValueString($arraydesc[$row], "text"), GetSQLValueString($arrayfreq[$row], "text")); // code to submit query } I've tried for, foreach, arrays (what feels like the everything I know) to post each row (row by row) into the database. I either get just the last row of data, or no data at all. I also worry that the [$row] technique is adding characters to my data. What is the best way to retrieve each row of the user's inputs, then upload this data (row by row) into the database? Also, I would really appreciate your suggestions for improving my coding technique and the approach I'm taking. Thank you, Hangston

    Read the article

  • How to force a page refresh or reload in jQuery?

    - by TimMac
    The code below displays a google map and search results when you enter an address and hit the submit button. I've been playing with it to try and force the page to completely refresh or reload once you hit the submit button. But I can't get it to work right. It loads the results "in page," but I'd like the page to completely refresh when the results load, like when you hit the back button on your browser. Hope that makes sense. I think the answer lies in this line of code but I don't know jquery very well. It's near the bottom of the full code below. <script type="text/javascript"> (function($) { $(document).ready(function() { load();'; Here's the full code below. Any help would be greatly appreciated! <?php /* SimpleMap Plugin display-map.php: Displays the Google Map and search results */ $to_display = ''; if ($options['display_search'] == 'show') { $to_display .= ' <div id="map_search" style="width: '.$options['map_width'].';"> <a name="map_top"></a> <form onsubmit="searchLocations(\''.$categories.'\'); return false;" name="searchForm" id="searchForm" action="http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].'"> <input type="text" id="addressInput" name="addressInput" class="address" />&nbsp; <select name="radiusSelect" id="radiusSelect">'; $default_radius = $options['default_radius']; unset($selected_radius); $selected_radius[$default_radius] = ' selected="selected"'; foreach ($search_radii as $value) { $r = (int)$value; $to_display .= '<option valu e="'.$value.'"'.$selected_radius[$r].'>'.$value.' '.$options['units']."</option>\n"; } $to_display .= ' </select>&nbsp; <input type="submit" value="'.__('Search', 'SimpleMap').'" id="addressSubmit" class="submit" /> <p>'.__('Please enter an address or search term in the box above.', 'SimpleMap').'</p> </form> </div>'; } if ($options['powered_by'] == 'show') { $to_display .= '<div id="powered_by_simplemap">'.sprintf(__('Powered by %s SimpleMap', 'SimpleMap'),'<a href="http://simplemap-plugin.com/" target="_blank">').'</a></div>'; } $to_display .= ' <div id="map" style="width: '.$options['map_width'].'; height: '.$options['map_height'].';"></div> <div id="results" style="width: '.$options['map_width'].';"></div> <script type="text/javascript"> (function($) { $(document).ready(function() { load();'; if ($options['autoload'] == 'some') { $to_display .= 'var autoLatLng = new GLatLng(default_lat, default_lng); searchLocationsNear(autoLatLng, autoLatLng.lat() + ", " + autoLatLng.lng(), "auto", "'.$options['lock_default_location'].'", "'.$categories.'");'; } else if ($options['autoload'] == 'all') { $to_display .= 'var autoLatLng = new GLatLng(default_lat, default_lng); searchLocationsNear(autoLatLng, autoLatLng.lat() + ", " + autoLatLng.lng(), "auto_all", "'.$options['lock_default_location'].'", "'.$categories.'");'; } $to_display .= ' }); })(jQuery); </script>'; ?>

    Read the article

  • Retrieving multiple rows from a loop-created form... Stuck.

    - by hangston
    Let me start by saying that I'm new to PHP, but I'm here to learn and would really appreciate your help. I use the following code to pull in data and create a form. This creates up to 40 lines for a user to fill out. Each line consists of the same information: Description, Amount, and Frequency. The remainder of the information needed is generated by the database. (See hidden fields) <?php $row = 0; do { $optid = $row_options['option_id']; echo "<tr>\n\t<td>" . htmlentities($row_options['option']) . "</td>\n"; echo "\t<td>" . "<input name='description' type='text' size='40' maxlength='120'/>" . "</td>\n"; echo "\t<td>" . "<input name='option_id' type='hidden' value='$optid' />$<input name='amount' type='text' size='10' maxlength='7'/>" . "</td>\n"; echo "\t<td>" . "<select name='assisted_frequency'> <option value='Monthly'>Monthly</option> <option value='Weekly'>Weekly</option> <option value='Daily'>Daily</option> <option value='Hourly'>Hourly</option> <option value='One-Time'>One-Time</option> </select>" . "</td>\n</tr>\n"; $array[$row] = array( $arraydesc[$row] = $_POST['description'], $arrayamto[$row] = $_POST['amount'], $arrayoptid[$row] = $optid, $arrayfreq[$row] = $_POST['frequency'], ); $row ++; } while ($row_options = mysql_fetch_assoc($options)); $counter = $row - 1; ?> I'm having troubles retrieving the information that the user inputs. My intent is to loop through each row after the user has input their information, then upload the mix of my database information and the user's information into another database. For example, the user would see, albeit prettier: form1 Option 1: description [input box] amount [input box] frequency [option box] Option 2: description [input box] amount [input box] frequency [option box] Option 3: description [input box] amount [input box] frequency [option box] Option 4: description [input box] amount [input box] frequency [option box] submit Upon submitting the form above, I'm using a query similar to the following to input the data into the database: for($row=0; $row<=$counter; $row++){ $insertSQL2 = sprintf("INSERT INTO table (option_id, amount, description, frequency) VALUES (%s, %s, %s, %s)", GetSQLValueString($arrayoptid[$row], "int"), GetSQLValueString($arrayamto[$row], "int"), GetSQLValueString($arraydesc[$row], "text"), GetSQLValueString($arrayfreq[$row], "text")); // code to submit query } I've tried for, foreach, arrays (what feels like the everything I know) to post each row (row by row) into the database. I either get just the last row of data, or no data at all. I also worry that the [$row] technique is adding characters to my data. What is the best way to retrieve each row of the user's inputs, then upload this data (row by row) into the database? Also, I would really appreciate your suggestions for improving my coding technique and the approach I'm taking.

    Read the article

< Previous Page | 6 7 8 9 10 11  | Next Page >