Posts

Showing posts from May, 2015

kindle - How interoperable are the EPUB and MOBI formats? -

i have bunch of epub books have convert mobi if kindle. know whether there loss of detail (e.g. meta-data, layout info) during conversion epub mobi , vice versa, analogous conversion between mp3 , wma? happens when multiple conversions applied consecutively, e.g. epub->mobi->epub->mobi->epub. how bad information loss get? yes, lossy. it's not possible express lossiness exactly, depends on input source. epub allows use of of xhtml1.1/css 2.1, whereas mobipocket "html 3" existed many years ago, plus proprietary tagging. if epub text, conversion acceptable. if highly designed, still readable, pretty terrible.

ios - Strange Crash on iPhone 3G/iPod 2G -

i banging head on strange issue. users of app reported app not start, crashes after showing startup screen 2 sec. occurs on older ipod 2g/iphone 3g. after getting hands on device occurs tried track down. the crash not occur debug code, release build. not of code executed @ until crash occurs. uiviewcontrollers initialized in appdelegate, , whatever sequence choose here, first of them fails after running through initwithnibname, same controllers , handles loading of correct xib universal app: - (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil { if (ui_user_interface_idiom() == uiuserinterfaceidiompad) { nsstring *ipadxib = [nsstring stringwithformat:@"%@-ipad", [[self class] description]]; return [super initwithnibname:ipadxib bundle:nibbundleornil]; } else { return [super initwithnibname:nibnameornil bundle:nibbundleornil]; } } this code runs through well, when returning here, end sigbus error somewhere in uikit (not c...

pipe - Different output with php client and with a browser -

maybe question simple, i'm not able answer it. i have little php code: <?php $line="echo 'hello' | lpr -pmyprinter"; $out=system($line,$output); ?> when execute code using command line (i use linux php 5.3.6 , apache 2.2.17) it's printed 'hello' in myprinter. if execute code using browser looks pipe ignored! i have tried exec(), passthru(), etc. , results same. thanks help. p.s: ran code php 5.1.¿¿?? try using following: echo `echo hello | lpr -pmyprinter`

c++ - Why does this private template function compile? -> Compiler Bug VS 2009 -

this compiles out problems in vs 2009? stupid? gcc gives warning, template private....? missing? #include <iostream> using namespace std; class { private: template<typename t> a& operator<<(const t & v) { cout << v << endl; return *this; } }; int main() { a; << 4; system("pause"); } microsoft acknowledges bug , claims fixed in next major release compiler (which read vc11/vs-whatever-is-after-2010 - not service pack vc10/vs2010): http://connect.microsoft.com/visualstudio/feedback/details/649496/visual-c-doesnt-respect-the-access-modifier-for-operator-member-function-templates from comments, fix appears made internal compiler build.

database - How would I design this schema in MongoDB? -

let's take example of chat room. should create 2 collections: room , messages , , store room details (title, description) separately messages (body/date/author)? messages collection have field called "room" links objectid of room. or should create 1 collection, called room. , inside room, there array of messages? what best practice? do? i lean toward first choice. aside fact 16mb may small (i've seen pretty busy chat rooms in days), storing messages separately allows greater flexibility on part. room doesn't need know messages associated - create once , query messages room id needed.

ruby - Nokogiri and finding element by name -

i parsing xml file using nokogiri following snippet: doc.xpath('//root').each |root| puts "# root found" root.xpath('//page').each |page| puts "## page found / #{page['id']} / #{page['name']} / #{page['width']} / #{page['height']}" page.children.each |content| ... end end end how can parse through elements in page element? there 3 different elements: image, text , video. how can make case statement each element? honestly, pretty close me.. doc.xpath('//root').each |root| puts "# root found" root.xpath('//page').each |page| puts "## page found / #{page['id']} / #{page['name']} / #{page['width']} / #{page['height']}" page.children.each |child| case child.name when 'image' do_image_stuff when 'text' do_text_stuff when 'video' ...

jQuery: Checking to see if list contains text, then redirect, else redirect here -

i'm complete novice when comes jquery, please bear me... i have html <ul class="zonesubscriptions"> <li> <ul> <li class="zonename"><a href="/default.aspx?pageid=8267303">my account</a></li> <li>never</li> </ul> </li> <li> <ul> <li class="zonename"><a href="/default.aspx?pageid=8269026">practitioners area</a></li> <li>never</li> </ul> </li> </ul> if link practitioners area present, redirect browser href, else, redirect account section. this jquery have... jquery.noconflict(); jquery(document).ready(function() { if(jquery(".zonename a").text() == 'practitioners area'){ document.location.href = $(this).attr('href'); }else{ document.location.href = jquery('.zonename:first a').attr('h...

python - Pipe raw OpenCV images to FFmpeg -

here's straightforward example of reading off web cam using opencv's python bindings: '''capture.py''' import cv, sys cap = cv.capturefromcam(0) # 0 /dev/video0 while true : if not cv.grabframe(cap) : break frame = cv.retrieveframe(cap) sys.stdout.write( frame.tostring() ) now want pipe output ffmpeg in: $ python capture.py | ffmpeg -f image2pipe -pix_fmt bgr8 -i - -s 640x480 foo.avi sadly, can't ffmpeg magic incantation quite right , fails with libavutil 50.15. 1 / 50.15. 1 libavcodec 52.72. 2 / 52.72. 2 libavformat 52.64. 2 / 52.64. 2 libavdevice 52. 2. 0 / 52. 2. 0 libavfilter 1.19. 0 / 1.19. 0 libswscale 0.11. 0 / 0.11. 0 libpostproc 51. 2. 0 / 51. 2. 0 output #0, avi, 'out.avi': stream #0.0: video: flv, yuv420p, 640x480, q=2-31, 19660 kb/s, 90k tbn, 30 tbc [image2pipe @ 0x1508640]max_analyze_duration reached [image2pipe @ 0x1508640]estimating duration b...

jquery - Backbone JS View Events not Firing? -

i'm trying play around backbone js , far seems making sense , working smoothly. however code below, custom events not seem firing. in below code stand out why might be? need "initialize" in view? other pointers on code/structure cool well. below full js/html. js var todo = backbone.model.extend({}); var todocollection = backbone.collection.extend({ model: todo, url: '/home/todos' }); var appview = backbone.view.extend({ // should listen, required? el: $(".content"), events: { "keypress #new-todo": "enter" }, initialize: function () { // _.bindall(this, "render", "createonenter"); // this.collection.bind("all", this.render); }, hi: function () { alert('ohai'); }, render: function () { var lis = ''; $.each(this.collection.models, function () { lis += '<li>...

html - Aligning 3 buttons in div horizontally -

how can align 3 buttons horizontally in xhtml? blogger way. here's xhtml buttons: <div class='fb-like'> <fb:like action='like' expr:href='data:post.url' font='arial' layout='button_count' send='true' show_faces='true' width='450'/> </div> <div><b:if cond='data:blog.pagetype != &quot;static_page&quot;'> <g:plusone annotation='inline' width='450' expr:href='data:post.url'></g:plusone> </b:if></div> <div><b:if cond='data:blog.pagetype != &quot;static_page&quot;'> <a class='twitter-share-button' data-count='none' data-via='marvinvista' expr:data-text='&quot;currently reading: &quot; + data:post.title' expr:data-url='data:post.url' href='http://twitter.com/share'>tweet</a> </b:if></div> html <div class...

How can I mask an HTML input using javascript? -

how can mask phone using javascript on html control. i input force text in following format: [(111)111-1111] here have currently: mask(str, textbox, loc, delim) { var locs = loc.split(','); (var = 0; <= locs.length; i++) { (var k = 0; k <= str.length; k++) { if (k == locs[i]) { if (str.substring(k, k + 1) != delim) { str = str.substring(0,k) + delim + str.substring(k,str.length) } } } } textbox.value = str } there 3 common ways handling phone number input of guaranteed format: 1. accept numerical input anyway the likelihood of users obscure numbers still living in higher ever. accepting kinds of numerical input alleviates concern number useless if gave either not enough numbers or wrong ones. 2. split 3 text boxes of fixed lengths a lot of financial software this. not sure why, specifically, seems rather frequent there. reco...

performance - Javascript program running for ever in all browser -

i have below code generate permutation of given number. problem if try generate permutation above 5 digit running ever. how optimize program result displayed in browser. <html> <script> function permute(level, permuted, used, original) { var length = original.length; if (level == length) { //system.out.println(permuted); document.getelementbyid("nmbrs").innerhtml = document.getelementbyid("nmbrs").innerhtml + "<br />" +permuted } else { (var = 0; < length; i++) { if (!used[i]) { used[i] = true; permute(level + 1, permuted + original[i], used, original); used[i] = false; } } } } function executep(){ var s = ['0','1','2','7']; document.getelementbyid("nmbrs").innerhtml = ""; var length...

indexing - where is placed the time configuration for --rotate in Sphinx? -

i want use --rotate in sphinx updating index every 5 minutes, number placed? i command example indexer --rotate --config /home/myuser/sphinx.conf --all i have searched here without luck, in advance the indexer program packaged sphinx not daemon, nor run regularly on own. instead, need use scheduling program that. for flavors of unix, can run indexer using cron. $ crontab -e */5 * * * * /path/to/sphinx/bin/indexer --rotate --config /home/myuser/sphinx.conf --all

objective c - How can I implement a text parsing/tokenising interface similar to the way Xcode highlights class names? -

i new cocoa , objective c please forgive me if dumb or obvious question. i'd grateful pointers right classes read documentation or existing web resources me figure out. willing hard work figuring out if can find suitable resources point me in right direction. i writing app that, essentially, contain text view user enter multi-line text. parsed (i'm thinking of using nsscanner or, maybe, ready-made stuff in parsekit) extract , tokenise words , numerical information stored in model object. i think can figure out parsing , data-storage stuff. however, tokenised words , numbers highlighted user can see them, change them , have contextual menu (with disclosure triangle) perform actions such ignoring them. ideally lot way xcode deals class names (underlining them dashed line, giving them menu etc). i've had @ nstokenfield seems suited single-line fields , big blue tokens bit visually disruptive want. also, docs seem suggest using plain text style allows 1 token per fiel...

uploading a file, renaming it and placing it in a particular location on server using Coldfusion -

a user submits file front end html form has fields division, department name, department number, section number, year, email, phone etc. file being submitted might have user given name. but, when uploaded want named departmentname_departmentnumber_sectionnumber . so, if department accounting , dept number 123 , section 1 , name of file accounting_123_1.doc . extension whatever type of file (text, ms-word's .doc or .docx, pdf or rtf) submitted , user can upload attachments of files extension .txt, .doc, .docx, pdf, rtf only. also, want stored on particular location on server. so, if division corporate finance , year 2011-2012 should stored on server @ "e:\files submitted\2011-2012\corporate finance\" . "e:\files submitted\" part remains same in directory name. <cfset submittedfilename = #form.departmentname#&"_"&#form.departmentnumber#&"_"&#form.section_number_1#&"."&#cffile.clientfileext#> ...

php - Reusing MYSQL queries on the same page -

i have header.php , footer.php file being included on same page, both return of same information. use query in each file. <?php $q3 = "select page_id, show_id, link_title pages p show_id = 1"; $r3 = @mysqli_query ($dbc, $q3); // run query. while ($nav = mysqli_fetch_array($r3, mysqli_assoc)) { echo"<li>{$nav['link_title']}</li>" } ?> this show pages in both header , footer. however second query in footer returns "couldn't fetch mysqli", works, doesn't. wondering should using mysqli_free_result() better practice? even more, practice free result after every query? there better way use same result different pages , <?php // ?> tags? also, error "too many mysql connections error" every , then? because not closing connections after queries ran? you begin removing @ code. error suppression slow , harmful practice. if inlcude's in same scope, can save value of...

SSL socket in Delphi -

i need communicate device uses ssl. used use socket communicate delphi app, i'd use security communication device. so, there tserversocket , tclientsocket equivalent component can use ssl? there's no built-in direct equivalent in delphi. can use indy either openssl or secureblackbox ssl classes indy not drop-in replacement tserversocket/tclientsocket, use different coding models. or can use telsecureclientsocket , telsecureserversocket classes of secureblackbox - descendants , direct replacements tclientsocket , tserversocket respectively. note: secureblackbox our product.

connection - wireless problem in android -

i have check wireless network enabled or disabled in android. how that? i have check one.(setting->location & security->use wireless networks) not in the(settings -> wireless & network settings -> wifi). tried second one. in coding though on air plane mode shown internet connection present. have check wireless in setting->location & security->use wireless networks. my code: private boolean checkinternetconnection() { connectivitymanager cm = (connectivitymanager) getsystemservice(context.connectivity_service); // test connection if (cm.getactivenetworkinfo() != null && cm.getactivenetworkinfo().isavailable() && cm.getactivenetworkinfo().isconnected()) { log.e("tag", "internet connection present"); return true; } else { log.e("tag", "internet connection not present"); return fal...

javascript - How do I use the Yahoo YUI to do inline cell editing that writes to a database? -

so have datatable setup using yui 2.0. , 1 of column definitions, i've set when click on cell, set of radio button options pops can modify cell content. i want whatever changes made reflected in database. subscribe radioclickevent. here code that: ex.mydatatable.subscribe("radioclickevent", function(oargs){ // hold change yahoo.util.event.preventdefault(oargs.event); // block user doing this.disable(); // read need var elcheckbox = oargs.target, newvalue = elcheckbox.checked, record = this.getrecord(elcheckbox), column = this.getcolumn(elcheckbox), oldvalue = record.getdata(column.key), recordindex = this.getrecordindex(record), session_code = record.getdata(\'session_code\'); ...

Netbeans +java.lang.OutOfMemoryError -

i m executing j2me project m getting error:- trace: , exception caught in display class java.lang.outofmemoryerror (stack trace incomplete) my .jar size 612kb , had search ane found this:- java heap space in netbeans.. i've increased heap size already! but shown in can't ablt find vmoption in properties-run. please can 1 me or can tell me can screenshow or exact file have increase heap size of netbeans. you can use obfuscator obfuscate code . , 612 kb considered large file java-me. you can increase memory , made working fail in real time env. suggest work in dev real time conf. right click project > properties > obfuscating > obfuscation level > high >build app

objective c - NSTextField waits until the end of a loop to update -

here's problem: have code goes this otherwincontroller = [[notificationwindowcontroller alloc] init]; (int = 0; < 10; i++) { [otherwincontroller showmessage:[nsstring stringwithformat:@"%d", i]]; nslog(@"%d", i); sleep(1); } where otherwincontroller subclass of nswindowcontroller using update window changes happen in code, , alloc init method opens nib , shows window. showmessage method changes nstextview display whatever text in parameter. in nslog, text changes every second , counts ten. showmessage method, text blank full ten seconds , displays number 10. thoughts?? ftr, showmessage method - (void)showmessage:(nsstring *)text { [[self message] setstringvalue:text]; } not should matter, that's pretty basic. you can achieve desired effect right inside loop, if explicitly give run loop time run: [[nsrunloop currentrunloop] rununtildate:[nsdate datewithtimeintervalsincenow: 0.1]];

Excel - compare two documents? -

i'm trying link 2 excel books together. exact copy of each other, if edit either one, other should updated too. know can using link function, that's unidirectional. need know how can in both directions. book1.xls sheet1 a1: hello! a2: goodbye! book2.xls sheet1 a1: hello! a2: goodbye! now if have link between book2 , book1, edited in book1 changed in book2, not vice versa! thank you!! one question - if files meant exact copies why have 2 copies? a possible example use workbook_sheetchange event changes workbook update other workbook. however, works when change values , not formats etc. eg 2 workbooks book1.xlsm & book2.xlsm, in book1.xlsm in thisworkbook object enter private sub workbook_sheetchange(byval sh object, byval target range) dim myobj object, strcopyto string strcopyto = "c:\users\osknows\desktop\book2.xlsm" set myobj = getobject(strcopyto) myobj.parent.windows(myobj.name).visible = true targe...

c# - Setting the Selected Value on DatagridView.ComboboxColumn -

i trying complete form grid loaded programmatically. the grid has 6 columns , last column combobox this part of code foreach(var persona in asistenciarepo.filterby(x => x.plaserv == planilla).orderby(x => x.orden)) { grilla_personal.rows.add(persona.personal.id, persona.personal.id_legajo, persona.jerarquia.descripcion, persona.personal.nomyape, persona.orden, persona.codificacion.descripcion); } basically i'm trying when grid loaded , displays selection combobox stored in entity the persona.codificacion.descripcion column of entity contains data wish link control. it necessary handle event selectedvaluechanged or way correctly. [update] column 6 loaded programmatically foreach (var c in codifrepo.getall()) { codificacion.items.add(c); } codificacion.valuemember = "id"; codificacion.displaymember = "descripcion"; codificacion name of comboboxcolumn your datagridviewcomboboxcolumn needs have datapropertyname property...

.net - stack memory location -

i know heap memory part of ram. stack memory part of ram or stack memory part of cpu registers. default size stack memory .net4.0 applications the stack memory part of ram. no different heap far computer conserned. it's used in different way.

asp.net mvc 3 - MVC 3 client side validation on textbox list -

if allow user add text boxes view how can still have model validation work correctly? want able send array of fanid's check (which have done successfully). problem remote validation on each text box sends value of first text box. model: [displayname("user id")] [remote("validateuser","template",errormessage = "invalid user id")] public string[] fanid { get; set; } currently hard coding inputs added.

adding items to Visual C# (Express 2010) project without copying them to project folder -

is possible? noticed every time add item (code or xaml file) gets copied project folder. way cannot keep reusable files separately. build dll out of them overkill , in general case it's inconvenient, each project i'm interested in subset of reusable classes. when add 'existing item' can choose 'add link' clicking triangle next add button in add existing item screen. maybe answers question?

Check my Ruby on Rails routes.rb file -

i started programming in ruby on rails, , wondering if of on routes.rb file using far , tell me if on thinking this. i aware of whole restful approach in ror , trying stick it, not sure if on track. far application has following functionality: user registration user activation (via email link) user can request activation resent user log in user log out user requests password reset (gets email) basic ucp (change email , password) i using lot of redirect_to *_url , *_path, want lot of named routes. trying explicitly declare routes allowed. input. myapp::application.routes.draw 'home' => 'pages#index', :as => 'home' 'testing' => 'pages#testing', :as => 'testing' 'register' => 'users#new', :as => 'register' post 'users/create' resources :users, :only => [ :new, :create ] 'activation' => 'activations#new', :as => 'activat...

C++ - ensuring full serial response -

i trying read serial response hardware device. string read long , need portion of it. portion of string want use std::string.substr(x,y); . problem run exception error because buffer reading doesn't have y characters. here code use read values: while(1) { char szbuff[50+1] = {0}; char wzbuff[14] = {"at+csq\r"}; dword dzbytesread = 0; dword dwbytesread = 0; if(!writefile(hserial, wzbuff, 7, &dzbytesread, null)) std::cout << "write error"; if(!readfile(hserial, szbuff, 50, &dwbytesread, null)) std::cout << "read error"; std:: cout << szbuff; std::string test = std::string(szbuff).substr(8,10); std::cout << test; sleep(500); i issuing command "at+csq". returns: n, n ok it returns 2 integer values seperated comma followed new line, followed "ok". my question is, how can make sure read values serial port before grabbing substring? understand, last character received ...

android - Change CheckBox state on List item click? -

i have list , checkbox in every row of it. want whenever click on row, checkbox changes state accordingly. checkbox.xml <checkbox android:id="@+id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="false" android:text="" /> click listener list protected void onlistitemclick(listview l, view v, int position, long id) { toast.maketext(getapplicationcontext(), "you have selected item no." + (position + 1) + "", toast.length_short).show(); super.onlistitemclick(l, v, position, id); selectedrow = position; if (v == null) { layoutinflater lif = (layoutinflater) getsystemservice(context.layout_inflater_service); v = lif.inflate(r.layout.posting_detail_question_row, null); } if (checkedtextview.ischecked()) { toast.maketext(getapplicationcontext(), "already voted",...

python - Check variable if it is in a list -

i new python, , wondering if there succinct way of testing value see if 1 of values in list, similar sql clause. sorry if basic question. msupdate.updateclassificationtitle in ( 'critical updates', 'feature packs', 'security updates', 'tools', 'update rollups', 'updates', ) i.e, want write: if msupdate.updateclassificationtitle in ( 'critical updates', 'feature packs', 'security updates', 'tools', 'update rollups', 'updates' ): then_do_something() seems succinct enough, if you're using more once should name tuple: titles = ('critical updates', 'feature packs', 'security updates', 'tools', 'update rollups', 'updates') if msupdate.updateclassificationtitle in titles: do_somethin...

javascript call php in backend -

i have facebook login button in index.php page. <fb:login-button onlogin="onlogin()"></fb:login-button> when user click on button, calls function onlogin() in javascript. <script type="text/javascript"> function onlogin() { if(fb.getsession()!=null){ //pass value save.php } } </script> what should let onlogin() call save.php page store data in database? you need use form of ajax make call server javascript. see jquery ajax libraries . however, want make sure call secured, i.e., cannot made manually malicious users want add data database.

php - Cron job won't process require_once -

i have cron job setup run every 5min. cron job follows: php /var/www/vhosts/default/htdocs/mail-test/index.php at end of index.php script following: $path = $base_path . trim($row['company']) . '/users/' . trim($row['name']) . '/upload/'; $zip_processing_file = $path . 'zip.php'; require_once "zip_processing_file"; however when cron job run, error stating following directory = $zip_processing_file not exist in /var/www/vhosts/default/htdocs/mail-test/ i can't seem figure out problem. have tried include gives same problem. way got work putting header("location: $zip_processing_file"); and hitting mail-test/index.php web browser, cycle through whole process, can't through web browser, need cron job work. thanks! the error message mentions /var/www/vhosts/default/htdocs/mail-test/ doesn't seem pertain path stored in $zip_processing_file (which contains users , upload ) may separat...

android - Inserting a table row inside a table row -

i want insert 2 table rows inside table row vertically. being done rows being added horizontally instead of vertically. how add vertical rows.. following xml. <tablelayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tablelayout1" > <tablerow android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <tablerow android:layout_column="0" android:layout_width="fill_parent" android:background="@drawable/eventbar" android:layout_height="wrap_content" ...

internet explorer - IE AJAX Cross-Browser Issue -

i have following ajax function: function ajaxdesignerbrandinfo() { var d = wrapformvalues('#designer-brand-form'); var recursiveencoded = $.param(d); /* $.post("/api/designer_brand/", { data : recursiveencoded }, function(data) { var results = $.parsejson(data); window.location = "/register/designer-product/"; });*/ $.ajax( { type: "post", url: "/api/designer_brand/", data : { data : recursiveencoded }, success: function(data) { console.log(data); settimeout(function() { window.location = "/register/designer-product/"; },0); }, error: function (xhr, ajaxoptions, thrownerror ){ alert(xhr.status); alert(thrownerror); } }); return false; } and corresponding form ...

How can I add a record to a table defined in a django model containing a content_object field using raw sql? -

i got model defined this: class logentry(models.model): text = models.charfield(max_length = 20) content_type = models.foreignkey(contenttype, null=true, blank=true) object_id = models.positiveintegerfield(null=true, blank=true) content_object = generic.genericforeignkey('content_type', 'object_id') django.contrib.auth.models import user usr = user.objects.all()[0] new_record = logentry.objects.create(text="foobar", content_object=usr) but how create same record using plain sql? problem of course how determine how insert values fields content_type , content_object. from django.db import connection, transaction cursor = connection.cursor() cursor.execute(""" insert appname_log_entry set (text, content_type, object_id) calues(%s, %s, %s)""", \ ['foobar', <how content type?>, modelinstance.id]) do have set content_objcet? if how? i don't understand...

How to integrate an old Struts application with Spring 3.x -

i wondering how , prefered way of integrating struts 1.x application spring 3.x can benefit ioc stuff. use contextloaderplugin , set struts controller processorclass " autowiringrequestprocessor " (in struts-config.xml): <controller> <set-property property="processorclass" value="org.springframework.web.struts.autowiringrequestprocessor" /> </controller> <plug-in classname="org.springframework.web.struts.contextloaderplugin"> <set-property property="contextconfiglocation" value="/web-inf/config/action-servlet.xml"/> </plug-in> action-servlet.xml has empty beans context file: <beans></beans> add following init parameter actionservlet in web.xml: <init-param> <param-name>autowire</param-name> <param-value>byname</param-value> </init-param> just write regular struts actions, , add annotation "@compon...

ruby on rails - How to setup multiple has_many through relationships in Rails3 dependent on field in joining table -

this simple, i'm still sorta beginning rails , can't seem figure out right phrase type google find answer. i've got pretty simple has_many through relationship described below: user -user_id -name article - article_id - title article_relationship - user_id - article_id - relationship_type on relationship type, string or int represent type of relations, favorite, recently_viewed, written_by, ect. how setup multiple has_many :articles, :through => :article_relationships can access articles of specific type of relationship through user.recently_viewed, user.favorite, ect? thanks bunch. you're on right track need make use of scopes: class article < activerecord::base # here recently_viewed_type refers type of relationship, whatever # constant defined as. scope :recently_viewed, where('article_relationships.relationship_type=?', recently_viewed_type) end then can access user directly: @user.articles.recently_view...

c++ - Thread safety for overloaded operator new -

though standard doesn't guarantee thread-safety new , of multi-threading operating systems support thread-safe operator new . i implementing own memory management dynamic allocation of class (say myclass ) in code. thread safety of myclass , may have use pthread or boost:: library. i thought if new already thread safe can overload myclass , leverage safety without worrying using libraries. class myclass { // data public: void* operator new (size_t); void operator delete (void*); }; is fair assumption c++03 systems/compilers? edit : since question not followed few users. detailing part: if have 2 threads new int() , new int() , 2 unique memory addresses returned. now, in overloaded myclass::new not using global ::new() or threading library; own memory manager (which doesn't know threads). pseudo code: char pool[big_size]; void* myclass::operator new (size_t size) { // memory 'pool' without using thread library return p; } my assumpti...

jquery - Add zebra striping but ignore hidden elements -

i have following code filters list according class added li element. zebra striping works fine when items showing when filter , lets 1 of list items hidden teh zebra stripe goes out of sync. there way around this? i have checked post ie did not work jquery table zebra striping hidden rows thanks. //filter $("#local-clubs-list li:visible:even").addclass("even"); $('ul#filter a').click(function() { $(this).css('outline','none'); $('ul#filter .current').removeclass('current'); $(this).parent().addclass('current'); var filterval = $(this).text().tolowercase().replace(' ','-'); $('ul#local-clubs-list li').each(function() { if(!$(this).hasclass(filterval)) { $(this).fadeout('normal').addclass('hidden'); } else { $(this).fadein('slow').removeclass('hidden...

security - Is posting SQL code in forums a bad idea? -

is there risk in posting sql code company in these forums, or in forums matter? specifically referring examples of sql queries. these queries show joins tables , different fields in database tables. the risk pretty low, if: you not publish company's name or web address there no sql injection waiting exploited in sql of yours server secure , pached you not publish connection credentials snippet

embedded - Any higher level protocol over serial port communication ? -

we running course in robotics , xbee favorite communication protocol student. in last 2 years helped them build around 62 various projects (40 more in pipeline). all projects involve sending different kind of data bot. 1 byte command long string interpreted. face issue of addressing bot when 1 xbee used in broadcast mode send messages particular bot among several. students use creativity address issue each time. i feel reinvesting wheel. wonder if higher level protocol proposals exist serial port communication , if there isn't specific protocol design wonder if if worth designing 1 student needs. you can implement modbus ascii if want go standard protocol that's open.

how can I make a list of callable commands python? -

i wondering how go making list of commands user can enter. example, user types in "who" list of on in mud. done using if, elif , else in pythons? i using python 3.1 btw. nope. dispatch dictionary. def who(*args, **kwargs): ... commands = { 'who': who, ... } ... if command in commands: commands[command](*args, **kwargs) else: print('bad command or file name')

cocoa - QTKit, capture video for live streaming -

i trying create application mac create live video streaming. know vlc , other solutions, still. to end trying record video isight using qtkit, , save continuously series of tiny video files. however, recording turns out not quite continuous, gaps between files. basically, setting timer, starts recording new file @ time intervals, stopping old recording. tried setting max recorded length, , using delegate method ...didfinishrecording... , ...willfinishrecording..., same result (i can't estimate difference between gaps in these cases). please, me, if know how these things should done. here current code: - (void)applicationdidfinishlaunching:(nsnotification *)anotification { qtcapturesession *session = [[qtcapturesession alloc] init]; qtcapturedevice *isight = [qtcapturedevice defaultinputdevicewithmediatype:qtmediatypevideo]; [isight open:nil]; qtcapturedeviceinput *myinput = [qtcapturedeviceinput deviceinputwithdevice:isight]; output = [[qtcapturem...

iphone - NSMutableArray of NSMutableDictionary with multiple keys, data structure -

i'm trying create data structure 3 fields. 1 method can grab 2 fields sqlite database. method grabs data using 2 fields sqlite database. way store data? 3 fields need of type: nsstring, key: @"name" nsinteger, key: @"id" nsarray, key: @"info" i thought array of dictionaries. in first method, nsstring , nsinteger, create dictionary, , create array of dictionaries out of it. got stuck thinking how print out data nsmutabledictionary 2 keys (question #1). then second thing thought was, can use name, id fields other piece of data table, , add new key/value pair dictionary. wasn't sure if done (question #2). and didn't know if there better way approach different data structure (question #3). thanks! create class data items, ivar each name, id, info. have lot of flexibility. while nsdictionary seems easy solution better create class rather easy , usability better.

centos - php's execution time and memory limit -

i using centos 5 server. got error while attempting download 1gb of file server server that maximum execution time exceeded. i opened php.ini file, written there max_execution_time = 30 ; maximum execution time of each script, in seconds max_input_time = 60 ; maximum amount of time each script may spend parsing request data memory_limit = 128m ; maximum amount of memory script may consume in last line written maximum amount of memory script may consume mean actually? not download more per script execution or memory taken script executed (sharing types) searched not got answer of this. please if 1 can tell me mean , how can able download approx 1gb of data through script other server using php. edit code using download file server using curl $username = "user"; $password = "pwd"; $url = "http://domain.com/feeds/"; global $ch; $ch = curl_init(); curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_returntransfer, 1);...

css - HTML page with embedded JWPlayers not working any more -

edit: problem solved. fitvids code causing jwp not display. help. i've been staring @ code long , can't figure out why it's not working after made couple of small mods. can 1 of clever folk check , let me know i've done wrong? the page supposed have 3 embedded jwplayer in random video. css file using should 1 desktop screens, have 1 there iphone. http://www.billarga.com/newsite/ the code below shows integration of 1 of 3 players. html <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <meta content="text/html; charset=iso-8859-1" http-equiv="content-type"> <title>new site</title> <script type="text/javascript" src="http://www.billarga.com/newsite/player/jwplayer.js"></script> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> ...

c - Weird behaviour of sigwait -

i using sigwait block thread signals. these signals have been added in sigs set. per doc sigwait supposed wait signals passed set in argument , not supposed change th signal mask of thread.. reason dont know, changing signal mask of thread. blocking signals other ones in sigs. dont wish happen. can me same. thanx in advance the code snippet: sigset_t sigs; int sig_recvd; sigset_t old_mask; sigemptyset(&sigs); sigaddset(&sigs, sigusr1); sigaddset(&sigs, sigterm); sigaddset(&sigs, sighup); sigaddset(&sigs, sigint); sigaddset(&sigs, sigpipe); sigaddset(&sigs, sigchld); sigprocmask(sig_block, &sigs, &old_mask); { sigwait(&sigs, &sig_recvd); //switch signal handling } while(1); sigblk before sigwait: 0000000080014203 sigblk during sigwait: fffffffefffabcfc i dont wrong sigwait function when did same sigwaitinfo, things worked out me. couldnt figure out made later work, problem solved. know if there differences in implem...

c# - RPC lib in multilanguage -

i search rpc lib support client or server in c++ , c#. can make client in c++ , talk server written in c#. not know if microsoft rpc allow this, protocol buffers or msgpack. apache thrift provides mechanism defining "services" in language , accessing service. there resources developing services in both c++ , c#: c++: http://wiki.apache.org/thrift/thriftusagec%2b%2b c#: http://www.markhneedham.com/blog/2008/08/29/c-thrift-examples/ alternatively, although it's not "cool", there xml-rpc clients both c# , c++ c#: http://www.xml-rpc.net/ c++: http://xmlrpc-c.sourceforge.net/ both mature , work well, should trivial , running. there are, obviously, more advanced protocols such aforementioned protocol buffers , msgpack neither seems have rpc capable clients target language. same goes bert (of github fame) , avro (the apache foundations attempt.)

linux - is it possible "transfer" a running application to another terminal/user? -

all, i sshed linux server run appliction in termial on pc, pc needs reboot reason. , application still in running status. may know possible open terminal ssh on pc "transparency transfer" running application new opened terminal? thanks! and know nohup cmd & , may not suit case. thanks hint. b. rgs give tmux try. similar screen added features vertical split without unofficial patches, etc. default better imo. i use instance run irssi , rtorrent etc dont have quit them when dropping console x or switching window manager. also, when used console (no x running), tmux (like screen) lets use multiple terminal instances in single vt/tty. hence particular scenario, install tmux in server, ssh, run tmux , app. when want reboot local pc, detach tmux session c-b d (default keybinding tmux) , reboot. once again, ssh , attach session tmux attach -d

Javascript jQuery strip leading and trailing spaces -

i want trim value (strip leading , trailing spaces) , make first letter in every word capital. when user leave element (blur event) html input follows <input id="iptfirstname" name="iptfirstname" type="text"/> js piece of code $(document).ready(function(){ var iptfirstname = $("#iptfirstname"); iptfirstname.blur(validateforename); }); function validateforename(){ var firstname= $("#iptfirstname").val; //strip leading , trailing spaces firstname= $.trim(firstname) //change first letter in every word uppercase firstname= capital(firstname); //update input field whit new value $("#iptfirstname").val(firstname); } function capital(elevalue) { var elevalue; if (elevalue != "") { var firstletter = elevalue.substring(0, 1).touppercase(); var restofword = elevalue.substring(1, elevalue.length).tolowercase(); elevalue = firstletter ...

java - Why are classLoader magic values in defineClass() throwing an exception? -

i want write classloader can me implement customized classes , whole component @ run time. right i'm in process of loading class. i'm trying load role.java file. when part of code: myclass = super.defineclass(classname, classdata, 0, classdata.length); i exception: exception in thread "main" java.lang.classformaterror: incompatible magic value 1885430635 in class file c:\users\arifah\downloads\compressed\euml2 free version\with classloader code\2\archetypedcomponentwithnull\src\ac\role/java at java.lang.classloader.defineclass1(native method) @ java.lang.classloader.defineclasscond(unknown source) @ java.lang.classloader.defineclass(unknown source) @ java.lang.classloader.defineclass(unknown source) @ customcl.customclassloader.loadclass(customclassloader.java:116) @ java.lang.classloader.loadclass(unknown source) @ customcl.customclassloader.main(customclassloader.java:145) i've read posts saying "you need osgi". similar working on ...

tags - Grails Validation : renderErrors not picking up after formRemote -

this in gsp <g:if test="${haserror}"> <div class="errors"> <g:rendererrors bean="${eventinstance}" /> </div> </g:if> <g:else > <div id="messagebox" class="message" style="display:none;"> <g:message code="legalevent.save.success" args="[entityname]" default="event saved successfully" /> </div> </g:else> <g:formremote name="eventform" id="eventform" url="[controller : 'search', action : 'savelegalevent']" update="eventformdiv" action="${createlink(controller: 'search', action: 'savelegalevent')}" method="post" onsuccess="jquery('#messagebox').show()"> i rendering page update : def savelegalevent = { def paramsview = params def eventpattern...

can php adodb do Common Table Expressions? -

i'm using adodb php library (http://phplens.com/adodb/) connect sql server 2005, can common table expressions used in execute method? as long sql passed through without modifications (which assume does) you'll able use ctes, yes. a simple test this: with cte ( select * mytable ) select * cte;

xcode - MonoTouch - simulator just quits -

this recent thing appears have happened after downloaded , installed latest xcode, went through steps acquire certificates/provisioning deploy apps iphone device (didn't finish that, went coding), either of things related, think updated monodevelop recently. the problem basically: run simulator, app loads short while exits. before app showing , when crashed instead of showing , how crashed (callstack, etc) exit app. any ideas causing this? have tried cleaning build? also, compiling againts lastest ios sdk? see project options :)

php - The best way to copy data from one table to other ones -

i have 1 main table, , need copy data others. whole idea name of tables have copy dynamic (it foo + 1 of columns of main table). for example, if have: insert maintable (id, addtoname, somedata) values (1, 234, 'foo data'); i need copy data to: othertable234 ( somename + addtoname column ) i tried mysql triggers, after research found out it's not allowed have dynamic table names. the other thing have in mind, build php daemon script, copy data every 1-10 minutes. concerned memory , performance issues. so, thing best solution deal kind of problem? you can use scripting language this, , use scheduler (cron, windows scheduler) run every 10 minutes. actual script needs issue a create table tablename select ... so complexity how tablename derived.

android - How much support is there for -webkit-overflow-scrolling:touch -

how many browsers support -webkit-overflow-scrolling:touch ios5 does, rest of them, , android etc.. as of writing, -webkit-overflow-scrolling exclusive mobile safari on ios 5 , later. as of mid-2012, latest android version (4.1 jelly bean) not support it, supported in chrome android, can downloaded google play (and supports android 4.0+). android 3.0+ supports overflow: scroll, it's not snappy.

Using Perl or Linux built-in command-line tools how quickly map one integer to another? -

i have text file mapping of 2 integers, separated commas: 123,456 789,555 ... it's 120megs... it's long file. i keep search first column , return second, e.g., 789 --returns--> 555 , need fast, using regular linux built-ins. i'm doing right , takes several seconds per look-up. if had database index it. guess need indexed text file! here i'm doing now: my $linefound=`awk -f, '/$column1/ { print $2 }' ../mybigmappingfile.csv`; is there easy way pull off performance improvement? the hash suggestions natural way experienced perler this, may suboptimal in case. scans entire file , builds large, flat datastructure in linear time. cruder methods can short circuit worst case linear time, less in practice. i first made big mapping file: my $len = shift; (1 .. $len) { $rnd = int rand( 999 ); print "$_,$rnd\n"; } with $len passed on command line 10000000, file came out 113mb. benchmarked 3 implemntations. first hash...

ruby - What is the best practice for testing Models in Rails? -

how or how little should 1 test models in rails? since framework doing you, i'm wondering if it's worth testing generated activerecord methods make sure work or not. do guys test them implicitly through controllers? in java world, if used hibernate, had write orm mapping stuff testing save/delete/find each entity important - if inherited these methods base class - because possible mapping information wrong, or make silly mistake. deletes important test make sure hibernate cascade properly. but since don't configure of stuff in rails @ all... it's simple... worth testing, or assume works? limit maybe making sure associations work expected? what best practice? testing examples? found page here: http://guides.rubyonrails.org/testing.html but didn't talk activerecord. focused more on controllers , other things. thanks! i don't try test methods introduced active record , such. tested rails team. , have written test cases. but test methods ,...