Search Results

Search found 509 results on 21 pages for 'ret'.

Page 1/21 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Bash shell prompt: where is $RET?

    - by Evgeni Sergeev
    I was reading this https://wiki.archlinux.org/index.php/Color_Bash_Prompt and ended up with the following: # Stores the status of each command in $RET PROMPT_COMMAND='RET=$?;' # A colour. RED_SHELL='\e[0;36m' # Prints "Status 1" if RET is 1, for example. RET_VISUALISE='$(if [[ $RET != 0 ]]; then echo -ne "Status \[$RED_SHELL\]$RET\n" && RET=0; fi;)' # What to print for each prompt. PS1="$RET_VISUALISE\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \t \[\e[33m\]\w\[\e[0m\]\n\$ " This does almost what I want, except when I press Enter,Enter,Enter multiple times after a command that returned status != 0. In this case it prints "Status 1" every time I press Enter. This is what the && RET=0; part was supposed to get rid of. Also, I don't understand why env | grep RET only shows the PS1 contents. What is the scope of $RET ?

    Read the article

  • Using ret with FASM on Win32

    - by Jon Purdy
    I'm using SDL with FASM, and have code that's minimally like the following: format ELF extrn _SDL_Init extrn _SDL_SetVideoMode extrn _SDL_Quit extrn _exit SDL_INIT_VIDEO equ 0x00000020 section '.text' public _SDL_main _SDL_main: ccall _SDL_Init, SDL_INIT_VIDEO ccall _SDL_SetVideoMode, 640, 480, 32, 0 ccall _SDL_Quit ccall _exit, 0 ; Success, or ret ; failure. With the following quick-and-dirty makefile: SOURCES = main.asm OBJECTS = main.o TARGET = SDLASM.exe FASM = C:\fasm\fasm.exe release : $(OBJECTS) ld $(OBJECTS) -LC:/SDL/lib/ -lSDLmain -lSDL -LC:/MinGW/lib/ -lmingw32 -lcrtdll -o $(TARGET) --subsystem windows cleanrelease : del $(OBJECTS) %.o : %.asm $(FASM) $< $@ Using exit() (or Windows' ExitProcess()) seems to be the only way to get this program to exit cleanly, even though I feel like I should be able to use retn/retf. When I just ret without calling exit(), the application does not terminate and needs to be killed. Could anyone shed some light on this? It only happens when I make the call to SDL_SetVideoMode().

    Read the article

  • Ret Failure with SDL using FASM on Win32

    - by Jon Purdy
    I'm using SDL with FASM, and have code that's minimally like the following: format ELF extrn _SDL_Init extrn _SDL_SetVideoMode extrn _SDL_Quit extrn _exit SDL_INIT_VIDEO equ 0x00000020 section '.text' public _SDL_main _SDL_main: ccall _SDL_Init, SDL_INIT_VIDEO ccall _SDL_SetVideoMode, 640, 480, 32, 0 ccall _SDL_Quit ccall _exit, 0 ; Success, or ret ; failure. With the following quick-and-dirty makefile: SOURCES = main.asm OBJECTS = main.o TARGET = SDLASM.exe FASM = C:\fasm\fasm.exe release : $(OBJECTS) ld $(OBJECTS) -LC:/SDL/lib/ -lSDLmain -lSDL -LC:/MinGW/lib/ -lmingw32 -lcrtdll -o $(TARGET) --subsystem windows cleanrelease : del $(OBJECTS) %.o : %.asm $(FASM) $< $@ Using exit() (or Windows' ExitProcess()) seems to be the only way to get this program to exit cleanly, even though I feel like I should be able to use retn/retf. When I just ret without calling exit(), the application does not terminate and needs to be killed. Could anyone shed some light on this? It only happens when I make the call to SDL_SetVideoMode().

    Read the article

  • C++ boost::lambda::ret equivalent in phoenix

    - by aaa
    hello. Boost lambda allows to overwrite deduced return type using ret<T> template. I have tried searching for equivalent in phoenix but could not find one. Is there an equivalent in phoenix? I know how to make my own Replacement but I would rather not. thank you

    Read the article

  • Call/Ret in x86 assembly embedded in C++

    - by SP658
    This is probably trivial, but for some reason I can't it to work. Its supposed to be a simple function that changes the last byte of a dword to 'AA' (10101010), but nothing happens when I call the function. It just returns my original dword __declspec(naked) long function(unsigned long inputDWord, unsigned long *outputDWord) { _asm{ mov ebx, dword ptr[esp+4] push ebx call SET_AA pop ebx mov eax, dword ptr[esp+8] mov dword ptr[eax], ebx } } __declspec(naked) unsigned long SET_AA( unsigned long inputDWord ) { __asm{ mov eax, [esp+4] mov al, 0xAA ret } }

    Read the article

  • Generate a sequence of Fibonacci number in Scala

    - by qin
    def fibSeq(n: Int): List[Int] = { var ret = scala.collection.mutable.ListBuffer[Int](1, 2) while (ret(ret.length - 1) < n) { val temp = ret(ret.length - 1) + ret(ret.length - 2) if (temp >= n) { return ret.toList } ret += temp } ret.toList } So the above is my code to generate a Fibonacci sequence using Scala to a value n. I am wondering if there is a more elegant way to do this in Scala?

    Read the article

  • Is there any memory leak in the normal routine of sqlite3_*()?

    - by reer
    A normal routine of sqlite3_prepare_v2() + sqlite3_step() + sqlite3_finalize() could contain leak. It sound ridiculous. But the test code seems to say it. Or I used the sqlite3_*() wrongly. Appreciate for any reply. __code________________________ include include // for usleep() include int multi_write (int j); sqlite3 *db = NULL; int main (void) { int ret = -1; ret = sqlite3_open("test.db", &db); ret = sqlite3_exec(db,"CREATE TABLE data_his (id INTEGER PRIMARY KEY, d1 CHAR(16))", NULL,NULL,NULL); usleep (100000); int j=0; while (1) { multi_write (j++); usleep (2000000); printf (" ----------- %d\n", j); } ret = sqlite3_close (db); return 0; } int multi_write (int j) { int ret = -1; char *sql_f = "INSERT OR REPLACE INTO data_his VALUES (%d, %Q)"; char *sql = NULL; sqlite3_stmt *p_stmt = NULL; ret = sqlite3_prepare_v2 (db, "BEGIN TRANSACTION", -1, &p_stmt, NULL); ret = sqlite3_step ( p_stmt ); ret = sqlite3_finalize ( p_stmt ); int i=0; for (i=0; i<100; i++) { sql = sqlite3_mprintf ( sql_f, j*100000 + i, "00000000000068FD"); ret = sqlite3_prepare_v2 (db, sql, -1, &p_stmt, NULL ); sqlite3_free ( sql ); //printf ("sqlite3_prepare_v2(): %d, %s\n", ret, sqlite3_errmsg (db)); ret = sqlite3_step ( p_stmt ); //printf ("sqlite3_step(): %d, %s\n", ret, sqlite3_errmsg (db)); ret = sqlite3_finalize ( p_stmt ); //printf ("sqlite3_finalize(): %d, %s\n\n", ret, sqlite3_errmsg (db)); } ret = sqlite3_prepare_v2 (db, "COMMIT TRANSACTION", -1, &p_stmt, NULL ); ret = sqlite3_step ( p_stmt ); ret = sqlite3_finalize ( p_stmt ); return 0; } __result________________________ And I watch the the process's run by top. At first, the memory statistics is: PID PPID USER STAT VSZ %MEM %CPU COMMAND 17731 15488 root S 1104 5% 7% ./sqlite3multiwrite When the printf() in while(1){} of main() prints the 150, the memory statistics is: PID PPID USER STAT VSZ %MEM %CPU COMMAND 17731 15488 root S 1552 5% 7% ./sqlite3multiwrite It sounds that after 150 for-cycles, the memory used by sqlite3multiwrite increase from 1104KB to 1552KB. What does it mean? memory leak or other thing?

    Read the article

  • Can't send mail from Windows Phone (Postfix server)

    - by Dominic Williams
    Some background: I have a Dovecot/Postfix setup to handle email for a few domains. We have imap and smtp setup on various devices (Macs, iPhones, PCs, etc) and it works no problem. I've recently bought a Windows Phone and I'm trying to setup the mail account on there. I've got the imap part working great but for some reason it won't send mail. mail.log with debug_peer_list I've put this on pastebin because its quite long: http://pastebin.com/KdvMDxTL dovecot.log with verbose_ssl Apr 14 22:43:50 imap-login: Warning: SSL: where=0x10, ret=1: before/accept initialization [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: before/accept initialization [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 read client hello A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 write server hello A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 write certificate A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 write server done A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 flush data [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2002, ret=-1: SSLv3 read client certificate A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2002, ret=-1: SSLv3 read client certificate A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 read client key exchange A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 read finished A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 write change cipher spec A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 write finished A [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2001, ret=1: SSLv3 flush data [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x20, ret=1: SSL negotiation finished successfully [109.151.23.129] Apr 14 22:43:50 imap-login: Warning: SSL: where=0x2002, ret=1: SSL negotiation finished successfully [109.151.23.129] Apr 14 22:43:51 imap-login: Info: Login: user=<pixelfolio>, method=PLAIN, rip=109.151.23.129, lip=94.23.254.175, mpid=24390, TLS Apr 14 22:43:53 imap(pixelfolio): Info: Disconnected: Logged out bytes=9/331 Apr 14 22:43:53 imap-login: Warning: SSL alert: where=0x4008, ret=256: warning close notify [109.151.23.129] postconf -n alias_database = hash:/etc/aliases alias_maps = hash:/etc/aliases append_dot_mydomain = no biff = no broken_sasl_auth_clients = yes config_directory = /etc/postfix debug_peer_list = 109.151.23.129 inet_interfaces = all mailbox_command = procmail -a "$EXTENSION" mailbox_size_limit = 0 message_size_limit = 50240000 milter_default_action = accept milter_protocol = 2 mydestination = ks383809.kimsufi.com, localhost.kimsufi.com, localhost myhostname = ks383809.kimsufi.com mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 myorigin = /etc/mailname non_smtpd_milters = inet:127.0.0.1:8891,inet:localhost:8892 readme_directory = no recipient_delimiter = + smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu) smtpd_milters = inet:127.0.0.1:8891,inet:localhost:8892 smtpd_recipient_restrictions = permit_mynetworks permit_sasl_authenticated reject_unauth_destination smtpd_sasl_auth_enable = yes smtpd_sasl_path = private/auth smtpd_sasl_type = dovecot smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtpd_use_tls = yes virtual_alias_domains = domz.co.uk ruck.in vjgary.co.uk scriptees.co.uk pixelfolio.co.uk filmtees.co.uk nbsbar.co.uk virtual_alias_maps = hash:/etc/postfix/alias_maps doveconf -n # 2.0.13: /etc/dovecot/dovecot.conf # OS: Linux 2.6.38.2-grsec-xxxx-grs-ipv6-64 x86_64 Ubuntu 11.10 auth_mechanisms = plain login log_path = /var/log/dovecot.log mail_location = mbox:~/mail/:INBOX=/var/mail/%u passdb { driver = pam } protocols = imap service auth { unix_listener /var/spool/postfix/private/auth { group = postfix mode = 0660 user = postfix } } ssl_cert = </etc/ssl/certs/dovecot.pem ssl_key = </etc/ssl/private/dovecot.pem userdb { driver = passwd } verbose_ssl = yes Any suggestions or help greatly appreciated. I've been pulling my hair out with this for hours! EDIT This seems to be my exact problem, but I already have broken_sasl set to yes and the 'login' auth mechanism added? http://forums.gentoo.org/viewtopic-t-898610-start-0.html

    Read the article

  • Strange Map Reduce Behavior in CouchDB. Rereduce?

    - by Tony
    I have a mapreduce issue with couchdb (both functions shown below): when I run it with grouplevel = 2 (exact) I get accurate output: {"rows":[ {"key":["2011-01-11","staff-1"],"value":{"total":895.72,"count":2,"services":6,"services_ignored":6,"services_liked":0,"services_disliked":0,"services_disliked_avg":0,"Revise":{"total":275.72,"count":1},"Review":{"total":620,"count":1}}}, {"key":["2011-01-11","staff-2"],"value":{"total":8461.689999999999,"count":2,"services":41,"services_ignored":37,"services_liked":4,"services_disliked":0,"services_disliked_avg":0,"Revise":{"total":4432.4,"count":1},"Review":{"total":4029.29,"count":1}}}, {"key":["2011-01-11","staff-3"],"value":{"total":2100.72,"count":1,"services":10,"services_ignored":4,"services_liked":3,"services_disliked":3,"services_disliked_avg":2.3333333333333335,"Revise":{"total":2100.72,"count":1}}}, However, changing to grouplevel=1 so the values for all the different staff keys should be all grouped by date no longer gives accurate output (notice the total is currect but all others are wrong): {"rows":[ {"key":["2011-01-11"],"value":{"total":11458.130000000001,"count":2,"services":0,"services_ignored":0,"services_liked":0,"services_disliked":0,"services_disliked_avg":0,"None":{"total":11458.130000000001,"count":2}}}, My only theory is this has something to do with rereduce, which I have not yet learned. Should I explore that option or am I missing something else here? This is the Map function: function(doc) { if(doc.doc_type == 'Feedback') { emit([doc.date.split('T')[0], doc.staff_id], doc); } } And this is the Reduce: function(keys, vals) { // sum all key points by status: total, count, services (liked, rejected, ignored) var ret = { 'total':0, 'count':0, 'services': 0, 'services_ignored': 0, 'services_liked': 0, 'services_disliked': 0, 'services_disliked_avg': 0, }; var total_disliked_score = 0; // handle status function handle_status(doc) { if(!doc.status || doc.status == '' || doc.status == undefined) { status = 'None'; } else if (doc.status == 'Declined') { status = 'Rejected'; } else { status = doc.status; } if(!ret[status]) ret[status] = {'total':0, 'count':0}; ret[status]['total'] += doc.total; ret[status]['count'] += 1; }; // handle likes / dislikes function handle_services(services) { ret.services += services.length; for(var a in services) { if (services[a].user_likes == 10) { ret.services_liked += 1; } else if (services[a].user_likes >= 1) { ret.services_disliked += 1; total_disliked_score += services[a].user_likes; if (total_disliked_score >= ret.services_disliked) { ret.services_disliked_avg = total_disliked_score / ret.services_disliked; } } else { ret.services_ignored += 1; } } } // loop thru docs for(var i in vals) { // increment the total $ ret.total += vals[i].total; ret.count += 1; // update totals and sums for the status of this route handle_status(vals[i]); // do the likes / dislikes stats if(vals[i].groups) { for(var ii in vals[i].groups) { if(vals[i].groups[ii].services) { handle_services(vals[i].groups[ii].services); } } } // handle deleted services if(vals[i].hidden_services) { if (vals[i].hidden_services) { handle_services(vals[i].hidden_services); } } } return ret; }

    Read the article

  • php turn unicode http link into clickable

    - by newinjs
    Hello, i have unicode link needed to be turn into links. Is it possible to change unicode into clickable? Currently i'm using this piece of code to turn link into clickable function clickable_link($text) { $ret = ' ' . $text; $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a class=\"hrefLink\" href=\"\\2\" target=\"_blank\">\\2</a>", $ret); $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a class=\"hrefLink\" href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret); $ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret); $ret = substr($ret, 1); return $ret; } Any help would be deeply appreciated.

    Read the article

  • template class: ctor against function -> new C++ standard

    - by Oops
    Hi in this question: http://stackoverflow.com/questions/2779155/template-point2-double-point3-double Dennis and Michael noticed the unreasonable foolishly implemented constructor. They were right, I didn't consider this at that moment. But I found out that a constructor does not help very much for a template class like this one, instead a function is here much more convenient and safe namespace point { template < unsigned int dims, typename T > struct Point { T X[ dims ]; std::string str() { std::stringstream s; s << "{"; for ( int i = 0; i < dims; ++i ) { s << " X" << i << ": " << X[ i ] << (( i < dims -1 )? " |": " "); } s << "}"; return s.str(); } Point<dims, int> toint() { Point<dims, int> ret; std::copy( X, X+dims, ret.X ); return ret; } }; template < typename T > Point< 2, T > Create( T X0, T X1 ) { Point< 2, T > ret; ret.X[ 0 ] = X0; ret.X[ 1 ] = X1; return ret; } template < typename T > Point< 3, T > Create( T X0, T X1, T X2 ) { Point< 3, T > ret; ret.X[ 0 ] = X0; ret.X[ 1 ] = X1; ret.X[ 2 ] = X2; return ret; } template < typename T > Point< 4, T > Create( T X0, T X1, T X2, T X3 ) { Point< 4, T > ret; ret.X[ 0 ] = X0; ret.X[ 1 ] = X1; ret.X[ 2 ] = X2; ret.X[ 3 ] = X3; return ret; } }; int main( void ) { using namespace point; Point< 2, double > p2d = point::Create( 12.3, 34.5 ); Point< 3, double > p3d = point::Create( 12.3, 34.5, 56.7 ); Point< 4, double > p4d = point::Create( 12.3, 34.5, 56.7, 78.9 ); //Point< 3, double > p1d = point::Create( 12.3, 34.5 ); //no suitable user defined conversion exists //Point< 3, int > p1i = p4d.toint(); //no suitable user defined conversion exists Point< 2, int > p2i = p2d.toint(); Point< 3, int > p3i = p3d.toint(); Point< 4, int > p4i = p4d.toint(); std::cout << p2d.str() << std::endl; std::cout << p3d.str() << std::endl; std::cout << p4d.str() << std::endl; std::cout << p2i.str() << std::endl; std::cout << p3i.str() << std::endl; std::cout << p4i.str() << std::endl; char c; std::cin >> c; } has the new C++ standard any new improvements, language features or simplifications regarding this aspect of ctor of a template class? what do you think about the implementation of the combination of namespace, stuct and Create function? many thanks in advance Oops

    Read the article

  • Wrapping malloc - C

    - by Appu
    I am a beginner in C. While reading git's source code, I found this wrapper function around malloc. void *xmalloc(size_t size) { void *ret = malloc(size); if (!ret && !size) ret = malloc(1); if (!ret) { release_pack_memory(size, -1); ret = malloc(size); if (!ret && !size) ret = malloc(1); if (!ret) die("Out of memory, malloc failed"); } #ifdef XMALLOC_POISON memset(ret, 0xA5, size); #endif return ret; } Questions I couldn't understand why are they using malloc(1)? What does release_pack_memory does and I can't find this functions implementation in the whole source code. What does the #ifdef XMALLOC_POISON memset(ret, 0xA5, size); does? I am planning to reuse this function on my project. Is this a good wrapper around malloc? Any help would be great.

    Read the article

  • APS.NET MVC Ajax: Passing a IList from the View to the Controller

    - by Bpimenta
    I need to pass the grid rows from the view to the controller using POST. The idea is to pass an IList of objects (people) that have the following structure: String Name String Address String ID I want to read the data from the JQGrid and pass it to the controller to fill the IList. I'm trying to build the data object to pass through the Ajax data parameter. Here is the Javascript code: $("#saveButton").click( function() { var returnData = '{'; var existingIDs = $('#listPeople').getDataIDs(); if (idsPeople.length > 0) { for (i=0;i<idsPeople.length;i++) { //Trying to build the obejct data ret = ret + '"people['+ i +'].Name":' $('#listPeople').getRowData(idsPeople[i]).Name + ','; ret = ret + '"people['+ i +'].Address":' $('#listPeople').getRowData(idsPeople[i]).Address+ ','; ret = ret + '"people['+ i +'].Id":' $('#listPeople').getRowData(idsPeople[i]).Id+ ','; //If it has more than one element if (idsPeople.length>1 && (i+1)<idsPeople.length) { ret = ret + ','; } } } ret = ret + '}'; My Ajax function for sending: var url_all = '<%=Url.Action("SaveData") %>; $.ajax({ type: "POST", url: url_all, data: ret, dataType: "json", success: function(){ alert("OK"); }, error: function(){ alert("Error: check SaveData"); } }); My controller: public ActionResult SaveData(IList<PeopleHeader> people){ // using debug to know if "people" variable has any values return Json(true); } The problem I'm getting is an error: "System.NotSupportedException: Fixed size collection", and no data is being delivered. I think my problem relies on creating the object... is there any simpler way of doing this procedure? Thanks in advance,

    Read the article

  • template; operator (int)

    - by Oops
    Hi, regarding my Point struct already mentioned here: http://stackoverflow.com/questions/2794369/template-class-ctor-against-function-new-c-standard is there a chance to replace the function toint() with a cast-operator (int)? namespace point { template < unsigned int dims, typename T > struct Point { T X[ dims ]; //umm??? template < typename U > Point< dims, U > operator U() const { Point< dims, U > ret; std::copy( X, X + dims, ret.X ); return ret; } //umm??? Point< dims, int > operator int() const { Point<dims, int> ret; std::copy( X, X + dims, ret.X ); return ret; } //OK Point<dims, int> toint() { Point<dims, int> ret; std::copy( X, X + dims, ret.X ); return ret; } }; //struct Point template < typename T > Point< 2, T > Create( T X0, T X1 ) { Point< 2, T > ret; ret.X[ 0 ] = X0; ret.X[ 1 ] = X1; return ret; } }; //namespace point int main(void) { using namespace point; Point< 2, double > p2d = point::Create( 12.3, 34.5 ); Point< 2, int > p2i = (int)p2d; //äähhm??? std::cout << p2d.str() << std::endl; char c; std::cin >> c; return 0; } I think the problem is here that C++ cannot distinguish between different return types? many thanks in advance. regards Oops

    Read the article

  • Does this PHP function protect against SQL injection?

    - by George Edison
    I have this function I'm using and I want to be sure that it fully protects against SQL injection attacks: function MakeSafeForQuery($string) { // replace all of the quote // chars by their escape sequence $ret = str_replace("\\","\\\\",$string); $ret = str_replace("'","\\'",$ret); $ret = str_replace("\"","\\\"",$ret); return $ret; } Am I missing anything serious?

    Read the article

  • C++ best practice: Returning reference vs. object

    - by Mike Crowe
    Hi folks, I'm trying to learn C++, and trying to understand returning objects. I seem to see 2 ways of doing this, and need to understand what is the best practice. Option 1: QList<Weight *> ret; Weight *weight = new Weight(cname, "Weight"); ret.append(weight); ret.append(c); return &ret; Option 2: QList<Weight *> *ret = new QList(); Weight *weight = new Weight(cname, "Weight"); ret->append(weight); ret->append(c); return ret; (of course, I may not understand this yet either). Which way is considered best-practice, and should be followed? TIA Mike

    Read the article

  • link clickable and wordwrap

    - by newinjs
    hi, i'm using php wordwrap for my comment box. This is my clickable function, function clickable_link($text) { $ret = ' ' . $text; $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a class=\"hrefLink\" href=\"\\2\" target=\"_blank\">\\2</a>", $ret); $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a class=\"hrefLink\" href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret); $ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret); $ret = substr($ret, 1); return $ret; } and this is my wordwrap for comment $comment = clickable_link($comment); $comment = wordwrap($comment, 25, "\n", false); so, once the word limit for 25 is reached, my comment box break my link http://www.websitetitle.com/showthread.php?t=2000 link become like this http://www.websitetitle.com/showthread.php? <br> t=2000 The link is broken. so is it possible to fix the link or any other workaround? Thank you

    Read the article

  • Assembly: Why does jumping to a label that returns via ret cause a segmentation fault?

    - by Terribad
    Linux Assembly Tutorial states: there is one very important thing to remember: If you are planning to return from a procedure (with the RET instruction), don't jump to it! As in "never!" Doing that will cause a segmentation fault on Linux (which is OK – all your program does is terminate), but in DOS it may blow up in your face with various degrees of terribleness. But I cannot understand why does it causes a segmentation fault. it sounds just like returning from a function. I have a situation where I need to implement the logic "If X happens, call procedure A. Otherwise, call procedure B." Is there any other way than jumping around like a kangaroo weaving spaghetti code?

    Read the article

  • Getting to grips with the stack in nasm

    - by MarkPearl
    Today I spent a good part of my day getting to grips with the stack and nasm. After looking at my notes on nasm I think this is one area for the course I am doing they could focus more on… So here are some snippets I have put together that have helped me understand a little bit about the stack… Simplest example of the stack You will probably see examples like the following in circulation… these demonstrate the simplest use of the stack… org 0x100 bits 16 jmp main main: push 42h push 43h push 44h mov ah,2h ;set to display characters pop dx    ;get the first value int 21h   ;and display it pop dx    ;get 2nd value int 21h   ;and display it pop dx    ;get 3rd value int 21h   ;and display it int 20h The output from above code would be… DCB Decoupling code using “call” and “ret” This is great, but it oversimplifies what I want to use the stack for… I do not know if this goes against the grain of assembly programmers or not, but I want to write loosely coupled assembly code – and I want to use the stack as a mechanism for passing values into my decoupled code. In nasm we have the call and return instructions, which provides a mechanism for decoupling code, for example the following could be done… org 0x100 bits 16 jmp main ;---------------------------------------- displayChar: mov ah,2h mov dx,41h int 21h ret ;---------------------------------------- main: call displayChar int 20h   This would output the following to the console A So, it would seem that call and ret allow us to jump to segments of our code and then return back to the calling position – a form of segmenting the code into what we would called in higher order languages “functions” or “methods”. The only issue is, in higher order languages there is a way to pass parameters into the functions and return results. Because of the primitive nature of the call and ret instructions, this does not seem to be obvious. We could of course use the registers to pass values into the subroutine and set values coming out, but the problem with this is we… Have a limited number of registers Are threading our code with tight coupling (it would be hard to migrate methods outside of their intended use in a particular program to another one) With that in mind, I turn to the stack to provide a loosely coupled way of calling subroutines… First attempt with the Stack Initially I thought this would be simple… we could use code that looks as follows to achieve what I want… org 0x100 bits 16 jmp main ;---------------------------------------- displayChar: mov ah,2h pop dx int 21h ret ;---------------------------------------- main: push 41h call displayChar int 20h   However running this application does not give the desired result, I want an ‘A’ to be returned, and I am getting something totally different (you will to). Reading up on the call and ret instructions a discovery is made… they are pushing and popping things onto and off the stack as well… When the call instruction is executed, the current value of IP (the address of the instruction to follow) is pushed onto the stack, when ret is called, the last value on the stack is popped off into the IP register. In effect what the above code is doing is as follows with the stack… push 41h push current value of ip pop current value of ip to dx pop 41h to ip This is not what I want, I need to access the 41h that I pushed onto the stack, but the call value (which is necessary) is putting something in my way. So, what to do? Remember we have other registers we can use as well as a thing called indirect addressing… So, after some reading around, I came up with the following approach using indirect addressing… org 0x100 bits 16 jmp main ;---------------------------------------- displayChar: mov bp,sp mov ah,2h mov dx,[bp+2] int 21h ret ;---------------------------------------- main: push 41h call displayChar int 20h In essence, what I have done here is used a trick with the stack pointer… it goes as follows… Push 41 onto the stack Make the call to the function, which will push the IP register onto the stack and then jump to the displayChar label Move the value in the stack point to the bp register (sp currently points at IP register) Move the at the location of bp minus 2 bytes to dx (this is now the value 41h) display it, execute the ret instruction, which pops the ip value off the stack and goes back to the calling point This approach is still very raw, some further reading around shows that I should be pushing the value of bp onto the stack before replacing it with sp, but it is the starting thread to getting loosely coupled subroutines. Let’s see if you get what the following output would be? org 0x100 bits 16 jmp main ;---------------------------------------- displayChar: mov bp,sp mov ah,2h mov dx,[bp+4] int 21h mov dx,[bp+2] int 21h ret ;---------------------------------------- main: push 41h push 42h call displayChar int 20h The output is… AB Where to from here? If by any luck some assembly programmer comes along and see this code and notices that I have made some fundamental flaw in my logic… I would like to know, so please leave a comment… appreciate any feedback!

    Read the article

  • How to amend return value design in OO manner?

    - by FrontierPsycho
    Hello. I am no newb on OO programming, but I am faced with a puzzling situation. I have been given a program to work on and extend, but the previous developers didn't seem that comfortable with OO, it seems they either had a C background or an unclear understanding of OO. Now, I don't suggest I am a better developer, I just think that I can spot some common OO errors. The difficult task is how to amend them. In my case, I see a lot of this: if (ret == 1) { out.print("yadda yadda"); } else if (ret == 2) { out.print("yadda yadda"); } else if (ret == 3) { out.print("yadda yadda"); } else if (ret == 0) { out.print("yadda yadda"); } else if (ret == 5) { out.print("yadda yadda"); } else if (ret == 6) { out.print("yadda yadda"); } else if (ret == 7) { out.print("yadda yadda"); } ret is a value returned by a function, in which all Exceptions are swallowed, and in the catch blocks, the above values are returned explicitly. Oftentimes, the Exceptions are simply swallowed, with empty catch blocks. It's obvious that swalllowing exceptions is wrong OO design. My question concerns the use of return values. I believe that too is wrong, however I think that using Exceptions for control flow is equally wrong, and I can't think of anything to replace the above in a correct, OO manner. Your input, please?

    Read the article

  • calculater by using reverse polish notation and using a stack

    - by programmer
    hello everyone I have a segmentation fault ,can you help please? if i have this operater "3 5 +" that mean 3+5 and like "9 8 * 5 + 4 + sin", "sin(((9*8)+5)+4)" so my idea is check if the first and second are numbers and push theem in the stack then when i have operator i pop the numbers and make the calculation then push the answer again. ` typedef struct st_node { float val; struct st_node *next; } t_node; typedef t_node t_stack; // a function to allocate memory for a stack and returns the stack t_stack* fnewCell() { t_stack* ret; ret = (t_stack*) malloc(sizeof(t_stack)); return ret; } // a function to allocate memory for a stack, fills it with value v and pointer n , and returns the stack t_stack* fnewCellFilled(float v, t_stack* n) { t_stack* ret; ret = fnewCell(); ret->val = v; ret->next =n; return ret; } //function to initialize stack void initstack(t_stack** stack) { fnewCellFilled(0,NULL); } // add new cell void insrtHead(t_stack** head,float val) { *head = fnewCellFilled(val,*head); } //function to push the value v into the stack s void push(t_stack **s, float val) { insrtHead(s,val); } //function to pop a value from the stack and returns it int pop(t_stack **s) { t_stack* tmp; int ret; tmp = (*s)->next; ret = (*s)->val; free(*s); (*s) = tmp; return ret; } int isempty (t_stack *t) { return t == NULL; } //function to transfer a string(str) to int (value) //returns -1 when success , i otherwise int str2int(char *str,int *value) { int i; *value = 0; int sign=(str[0]=='-' ? -1 : 1); for(i=(str[0]=='-' ? 1 : 0);str[i]!=0;i++) { if(!(str[i]>=48 && str[i]<=57)) // Ascii char 0 to 9 return i; *value= *value*10+(str[i]-48); } *value = *value * sign; return -1; } //a function that takes a string, transfer it into integer and make operation using a stack void function(t_stack *stack, char *str) { char x[10]=" "; int y,j,i=0,z; printf("++\n"); if(str[i] != '\0') { strcpy(x, strtok(str, " ")); z= str2int(x, &y); if(z == -1) { push(&stack,y); i=i+2; } } while(str[i] != '\0') { strcpy(x, strtok(NULL, " ")); z= str2int(x, &y); if(z == -1) { printf("yes %d",y); push(&stack,y); i=i+2; } else { y=pop(&stack); j=pop(&stack); if(x[0] == '+' ) push(&stack,y+j); else if (x[0] == '-' ) push(&stack,j-y); else if(x[0] == '*' ) push(&stack,j*y); else if(x[0] == '/') push (&stack ,j/y); } } } int main() { t_stack *s; initstack(&s); char *str="3 5 +"; function(s,str); return 0; } `

    Read the article

  • COM port read - Thread remains alive after timeout occurs

    - by Sna
    Hello to all. I have a dll which includes a function called ReadPort that reads data from serial COM port, written in c/c++. This function is called within an extra thread from another WINAPI function using the _beginthreadex. When COM port has data to be read, the worker thread returns the data, ends normaly, the calling thread closes the worker's thread handle and the dll works fine. However, if ReadPort is called without data pending on the COM port, when timeout occurs then WaitForSingleObject returns WAIT_TIMEOUT but the worker thread never ends. As a result, virtual memory grows at about 1 MB every time, physical memory grows some KBs and the application that calls the dll becomes unstable. I also tryied to use TerminateThread() but i got the same results. I have to admit that although i have enough developing experience, i am not familiar with c/c++. I did a lot of research before posting but unfortunately i didn't manage to solve my problem. Does anyone have a clue on how could i solve this problem? However, I really want to stick to this kind of solution. Also, i want to mention that i think i can't use any global variables to use some kind of extra events, because each dll's functions may be called many times for every COM port. I post some parts of my code below: The Worker Thread: unsigned int __stdcall ReadPort(void* readstr){ DWORD dwError; int rres;DWORD dwCommModemStatus, dwBytesTransferred; int ret; char szBuff[64] = ""; ReadParams* params = (ReadParams*)readstr; ret = SetCommMask(params->param2, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING); if (ret == 0) { _endthreadex(0); return -1; } ret = WaitCommEvent(params->param2, &dwCommModemStatus, 0); if (ret == 0) { _endthreadex(0); return -2; } ret = SetCommMask(params->param2, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD| EV_RING); if (ret == 0) { _endthreadex(0); return -3; } if (dwCommModemStatus & EV_RXCHAR||dwCommModemStatus & EV_RLSD) { rres = ReadFile(params->param2, szBuff, 64, &dwBytesTransferred,NULL); if (rres == 0) { switch (dwError = GetLastError()) { case ERROR_HANDLE_EOF: _endthreadex(0); return -4; } _endthreadex(0); return -5; } else { strcpy(params->param1,szBuff); _endthreadex(0); return 0; } } else { _endthreadex(0); return 0; } _endthreadex(0); return 0;} The Calling Thread: int WINAPI StartReadThread(HANDLE porthandle, HWND windowhandle){ HANDLE hThread; unsigned threadID; ReadParams readstr; DWORD ret, ret2; readstr.param2 = porthandle; hThread = (HANDLE)_beginthreadex( NULL, 0, ReadPort, &readstr, 0, &threadID ); ret = WaitForSingleObject(hThread, 500); if (ret == WAIT_OBJECT_0) { CloseHandle(hThread); if (readstr.param1 != NULL) // Send message to GUI return 0; } else if (ret == WAIT_TIMEOUT) { ret2 = CloseHandle(hThread); return -1; } else { ret2 = CloseHandle(hThread); if (ret2 == 0) return -2; }} Thank you in advance, Sna.

    Read the article

  • C# animation - move object from A to B or by angle

    - by Nullstr1ng
    Hi am just doing a little animation which moves an object from point a to point b or by angle/radians. what I currently have is this Point CalcMove(Point pt, double angle, int speed) { Point ret = pt; ret.X = (int)(ret.X + speed * Math.Sin(DegToRad(angle))); ret.Y = (int)(ret.Y + speed * Math.Cos(DegToRad(angle))); return ret; } but it doesn't look what i expected. please help? update: oh and am using NETCF

    Read the article

  • Internet Explorer 8 + Deflate

    - by Andreas Bonini
    I have a very weird problem.. I really do hope someone has an answer because I wouldn't know where else to ask. I am writing a cgi application in C++ which is executed by Apache and outputs HTML code. I am compressing the HTML output myself - from within my C++ application - since my web host doesn't support mod_deflate for some reason. I tested this with Firefox 2, Firefox 3, Opera 9, Opera 10, Google Chrome, Safari, IE6, IE7, IE8, even wget.. It works with ANYTHING except IE8. IE8 just says "Internet Explorer cannot display the webpage", with no information whatsoever. I know it's because of the compression only because it works if I disable it. Do you know what I'm doing wrong? I use zlib to compress it, and the exact code is: /* Compress it */ int compressed_output_size = content.length() + (content.length() * 0.2) + 16; char *compressed_output = (char *)Alloc(compressed_output_size); int compressed_output_length; Compress(compressed_output, compressed_output_size, (void *)content.c_str(), content.length(), &compressed_output_length); /* Send the compressed header */ cout << "Content-Encoding: deflate\r\n"; cout << boost::format("Content-Length: %d\r\n") % compressed_output_length; cgiHeaderContentType("text/html"); cout.write(compressed_output, compressed_output_length); static void Compress(void *to, size_t to_size, void *from, size_t from_size, int *final_size) { int ret; z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; if ((ret = deflateInit(&stream, CompressionSpeed)) != Z_OK) COMPRESSION_ERROR("deflateInit() failed: %d", ret); stream.next_out = (Bytef *)to; stream.avail_out = (uInt)to_size; stream.next_in = (Bytef *)from; stream.avail_in = (uInt)from_size; if ((ret = deflate(&stream, Z_NO_FLUSH)) != Z_OK) COMPRESSION_ERROR("deflate() failed: %d", ret); if (stream.avail_in != 0) COMPRESSION_ERROR("stream.avail_in is not 0 (it's %d)", stream.avail_in); if ((ret = deflate(&stream, Z_FINISH)) != Z_STREAM_END) COMPRESSION_ERROR("deflate() failed: %d", ret); if ((ret = deflateEnd(&stream)) != Z_OK) COMPRESSION_ERROR("deflateEnd() failed: %d", ret); if (final_size) *final_size = stream.total_out; return; }

    Read the article

  • PHP - How can I check if return() was called from an include()'d file?

    - by John Himmelman
    How can I tell if return() was called from within the included file. The problem is that include() returns 'int 1', even if return() wasn't called. Here is an example... included_file_1.php <?php return 1; included_file_2.php <?php echo 'no return here, meep'; main.php <?php $ret = include('included_file_1.php'); // This file DID return a value, int 1, but include() returns this value even if return() wasn't called in the included file. if ($ret === 1) { echo 'file did not return anything'; } var_dump($ret); $ret = include('included_file_2.php'); // The included file DID NOT return a value, but include() returns 'int 1' if ($ret === 1) { echo 'file did not return anything'; } var_dump($ret);

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >