Posts

Showing posts from May, 2012

gwt - ui:with, style not showing up -

i share css across multiple widgets using . i can see css class name obfuscated class definition not showing when inspect element in firefox / chrome. here're codes. can suggest missing? thanks. style.css .namespan { color: #3e6d8e; background-color: #e0eaf1;} resources.java public interface resources extends clientbundle { @source("style.css") style style(); public interface style extends cssresource { string namespan(); } } uibinder.ui.xml <ui:uibinder xmlns:ui='urn:ui:com.google.gwt.uibinder' xmlns:g='urn:import:com.google.gwt.user.client.ui'> <ui:with field='res' type='com.my.app.widgets.logoname.resources'/> <g:htmlpanel> <div> hello there <g:inlinelabel ui:field='namespan' stylename="res.style.namespan">kevin</g:inlinelabel> </div> </g:htmlpanel> </ui:uibinder> uibinder.cla

Selenium - Troubles when trying to use javascript-xpath instead of ajaxslt -

i'm trying improve selenium tests on ie. use javascript-xpath instead of ajaxslt . my setup function : public void setup() throws exception { super.setup(host, browser); selenium.setspeed(constants.delay_between_actions); selenium.windowmaximize(); selenium.allownativexpath("false"); selenium.usexpathlibrary("javascript-xpath"); } when try find element xpath, instance : selenium.click("xpath=//a[@id='linklogin']"); i error (only when try use javascript-xpath ): com.thoughtworks.selenium.seleniumexception: error: invalid xpath [2]: //a[@id='linklogin'] what miss correctly use javascript-xpath ? thanks help. have considered changing locator strategy away xpath? i've been using form of css locators on average 5 times faster xpath.

jquery - Check for misspelt words using PHP -

i using code create instant search site... http://woorkup.com/2010/09/13/how-to-create-your-own-instant-search/ some of phrases in our database our complex , can misspelt on top of wanted use spelling suggestions. does know of ways offer correct spellings based on string provided? any appreciated. if searches phrase, doesn't click of results, , researches new similar phrase (check out levenshtein() ) , does click result, write database original phrase , new phrase. record each time happens. if phrase matched, increment counter phrase. then, if searches phrase matches 1 of possibly incorrect phrases (perhaps have threshold using counter), can display did mean search for...? results (if any) incorrect phrase. this isn't spell check per se, think useful pick on common mistakes. unfortunately though, don't have many people build index google's did mean?

c# - Getting all the object implementing an interface inside an application -

i need objects in application implement given interface. how can achieve this? thank you to clarify i'm looking instances not types. to clarify again, guess ill need evil threads associated appdomain , walk stacks. again- boss's idea... thought of doing using ioc or aop.... this cannot done. to find object, need reference it. if not have reference it, want "find" it, not possible.

linux - C++: how can I get the list of folders -

i not familiar c++ c# developer. in project, need delete folders of 1 week before. in c++, how can list of folders of 1 week before based on current system date time? i working on eclipse ide running on ubuntu 10.10. if provide sample of code, great. thanks in advance , appreciated! with boost: #include <boost/foreach.hpp> #include <boost/filesystem.hpp> int main(int, char**) { time_t one_week_ago = std::time(null) - (7 * 24 * 3600); boost::filesystem::directory_iterator dir("/tmp"), end; boost_foreach(const boost::filesystem::path& p, std::make_pair(dir, end)) if(boost::filesystem::is_directory(p)) if(boost::filesystem::last_write_time(p) < one_week_ago) boost::filesystem::remove_all(p); } or without using boost::foreach #include <boost/filesystem.hpp> int main(int, char**) { time_t one_week_ago = std::time(null) - (7 * 24 * 3600); boost::filesystem::directory_ite

ubuntu - How to merge many PDF files into a single one? -

this question has answer here: merge / convert multiple pdf files 1 pdf 12 answers i have 16 pdfs want convert single one... on ubuntu 10.10, how can it? you can use http://www.mergepdf.net/ example or: pdftk http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/ if not on ubuntu , have same problem (and wanted start new topic on , suggested have @ question) can this: things you'll need: * full version of adobe acrobat open .pdf files wish merge. these can minimized on desktop individual tabs. pull wish first page of merged document. click 'combine files' icon on top left portion of screen. the 'combine files' window pops divided 3 sections. first section titled, 'choose files wish combine'. select 'add open files' option. select other open .pdf documents on desktop when prompted. rearrange documents wish i

asp.net - T-Sql to linq conversion issues (order by) -

i'm having bit of issue converting following t-sql statement linq (using 4.0 entity framework) i'm getting unable cast type 'system.linq.iorderedqueryable 1' type 'system.linq.iqueryable 1'. linq entities supports casting entity data model primitive types. t-sql select i.id , i.name inventory i.id in ( select top 5 applicationid lastviewed group applicationid, someuserid having someuserid = @someuserid order max(id) desc ) this have right (with linqer) dim query iqueryable(of inventory) = d in ctx.inventories ((from e in ctx.lastvieweds _ group e _ e.applicationid, _ e.someuserid _ g = group _ dfaitedsid = user _ order g.max(function(p) p.id) descending _ select new { _ applicationid _ }).take(5)).contains(new {.applicationid = d.id}) _ se

unix - Are there standard Queue implementations for C? -

is there queue data structure implementation "comes" c or have develop own (this school project, must use either exists in standard gcc installation or have implement 1 myself!) what other general data structures linked lists, stacks, etc? thanks you must implement own. c has little in terms of data structures , forces resort arguable tricks implement abstract data types: see article titled “incomplete types abstractions” if can find it, or see how principles applied in, say, polarssl's bignum.h file . c++ on other hand supposed allow pretty can in c , give ways implement abstract data structures.

c# - Problem in reading XML node with unknown root/parent nodes -

i have been trying read xml file. have extract value of nodes "date" , "name", problem is, might appear @ level in xml hierarchy. so when try code, xmldocument doc = new xmldocument(); doc.load("test1.xml"); xmlelement root = doc.documentelement; xmlnodelist nodes = root.selectnodes("//*"); string date; string name; foreach (xmlnode node in nodes) { date = node["date"].innertext; name = node["name"].innertext; } and xml file :: <?xml version="1.0" encoding="utf-8"?> <root> <child> <name>aravind</name> <date>12/03/2000</date> </child> </root> the above code errors out, <name> , <date> not immediate child elements of root . possible assume parent/root nodes unknown , name of nodes, copy values ?? dependi

Android Python Programming -

can program android using python? seem have stumbled upon many links while searching... neither of them concrete. any suggestions? want write apps android don't want java this. ps: question whether can write proper, full fledged apps android. checkout kivy . have done great job far, , big fan of work. still lacking providers, keep adding new stuff everyday. first thing need check requirement against can offer based on documentation. have create amazing framework input such multi-touch or pen handling. use opengl es internally, result complex graphics , visualizations can run fast when interacting the application. process creating apk straight forward.

jquery - ajax loading image with delay? -

i have ajax implemented refresh content want add delay - know how can add in code have? $.ajax({ url: "<?php echo site_url('apply/processpersonaldetails'); ?>", type: 'post', data: form_data, success: function(msg) { $('#content').empty().html('<img src="../images/ajaxloader.gif" />'); $('#content').html(msg); } }); ah sorry, mean delay before new content has loaded, want show loading image before new content displayed...does make sense? i don't quite understand mean delay in scenario use settimeout function schedule execution of callback @ later moment: window.settimeout(function() { alert('this executed 3 seconds later'); }, 3000);

.net - Can Generics be used with Silverlight? -

i have user control displays objects of client-declared type specialized behavior. use generics. however, i'm not sure how declare in xaml: <local:editablelistbox x:name="sectionlist" margin="56,8,15,0" fontsize="64" selectionchanged="sectionlist_selectionchanged" /> listbox uses object members, makes me think perhaps there's no way have type safety here. or there? (i'm building windows phone 7 app, if makes difference.) update : i'm totally fine not having generics in xaml, i'm still trying figure out how set in code-behind. parameterized everything, it's still complaining. code behind: public partial class editablelistbox<t> : usercontrol, inotifypropertychanged t : ieditablelistmember { public editablelistbox() { // error: name 'initializecomponent' not exist in current context initializecomponent(); loaded += new routedeventhandler(editablelistbox_l

swing - Which Java text component should I be using to get it to resize to fit the frame as it is resized? -

i have jtabbedpane , jtextarea, want textareas/panes resize fit window when window resized. how do this? i'm fuzzy on if it's right text component use. really muddled. edit: setting explicit size dumb dumb. i've got worked out. did set viewport of jscrollpane jtextarea , remove explicit sizing. thanks chaps! you can use whatever components like. jcomponents can resize resizing parent container. need choose correct layoutmanager . depending on how want set up, assume want add jtabbedpane jframe so: jtabbedpane jtp; jframe frame; // jframe's default layour border layout. frame.add(jtp, borderlayout.center); this cause jtabbed pane take of space of jframe . you need set jtabbedpane 's layout manager borderlayout , , tab add jtabbedpane need have borderlayout . to set layout of components, do: jcomponent anycomponent; anycomponent.setlayout(new borderlayout()); have @ java layoutmanager tutorials more information. i should ment

HTML - what does it mean when it says an attribute can have a string datatype as its value in laymans terms? -

i wondering string datatype value attribute mean. mean can use letters , number attributes value? restrictions? a string "string" of characters (numbers, letters, symbols, etc). in context of html , attributes specifically, recommend checking out w3c page: http://www.w3.org/tr/html-markup/datatypes.html note there different restrictions if attribute unquoted, single quoted, or double quoted.

JAXB generating wrong Namespace -

i have xsd (lets name afb) imports xsd (lets name kts). , refer element of kts.xsd in afb.xsd along correct namespaces. but when generate classes using jaxb, namespace refered element wrong. i mean, referred element should have kts namespace having afb namespace. because of validating xml against xsd failing not able bind xml data java models. ex: afb.xsd : <xs:import namespace="http://www.boschkts.com" schemalocation="kts.xsd"/> <xs:element name="vehicle"> <xs:complextype> <xs:sequence> <xs:element ref="vtype"/> <xs:element name="results" type="kts:results" > </xs:sequence> </xs:complextype> </xs:element> kts:xsd : <xs:schema xmlns:xs="http://www.w3.org/2001/xmlschema" xmlns="http://www.boschkts.com" targetnamespace="http://www.boschkts.com" elementformdefault="qualified"

sql - what is the meaning of underlying table in VIEW'S definition -

am not understand , what meaning of underlying table in view definition , a view created joining 1 or more tables. when update record(s) in view, updates records in underlying tables make view. so, yes, can update data in view providing have proper privileges underlying tables. think of view stored query, appears user regular table. in practical terms, there's little difference between view: select somefield, otherfield theview and what's happening @ database level: select somefield, otherfield ( select lots, of, useless,fields, somefield, otherfield underlying, tables join ... ) theview views save having write sub-query each time, they're time saver in regard. however, views have downside depending on underlying query, might not able run update/delete queries against view if directly accessing underlying tables.

css - on iPad background won't go completely across -

here code: #body_background { background:transparent url('../images/am_bg_header.jpg') repeat-x 0 0; display: block;} #header { height:107px; } on ipad reason background flows endless on right not on left... background_body tag outer tag (except body) still seems restricted on right , want go endless on right. and guess' why?? i know 6 months old, had same problem , figured out answer through safari web developer's guide here : default width of ipad (or iphone) viewport 980px, if design page bigger that, automatic content (anything not given width) seems cut off @ edge. to fix this, need set viewport width want page viewed @ adding meta tag head, so: <head> <meta name="viewport" content="width=1050" /> </head> if page less 980px wide, isn't problem having.

java - How to add multiple components to a JFrame? -

i have jframe . i have box class extends component . box class has paint method makes filled rectangle. when add multiple of these box components jframe, added 1 displayed when call repaint on jframe. i took @ layout managers, not sure that's want. want able make animation of whole bunch of rectangles wherever want on screen. (i tried creating panel, adding panel jframe, , adding box components panel. did not work either). thanks in advance! you have 2 choices. you can change layout of frame: jframe frame; frame.setlayout(new flowlayout()); now, if add more 1 box, show on frame. the other option said tried. (adding panel frame) jpanel pane = new jpanel(); frame.add(pane); (add boxes 'pane') also, should careful sizing of box . want call setpreferredsize() somewhere in creation of box . tell java size make box when added layout. you should take @ java layout manager tutorials . there lots of great info there. and, 1 more thing.

.net - ref vs out in C# -

possible duplicate: difference between ref , out parameters in .net when use ref , when use out ? difference between both ? how , used ? please share example showing difference between both ref , out . thanks. there's number of examples online. a quick google search found this: http://www.c-sharpcorner.com/uploadfile/mahesh/out_and_ref11112005002102am/out_and_ref.aspx

shell - Terminal scripting in OSX -

i've never created script before , looking tutorial on writing script osx 10.6. there terminal command can show hidden files. it's defaults write com.apple.finder appleshowallfiles true killall finder changing true false hide system files. want make script checks value of appleshowallfiles, , if true, writes false, , if false, writes true. is done in textedit , saved .sh file? can script double-click runs, or have start terminal , type command execute script? i'm newb, sorry thanks guys make file switchhideshow.command following content: #!/bin/sh show=`defaults read com.apple.finder appleshowallfiles 2>/dev/null` if [ "$show" == "true" ]; defaults write com.apple.finder appleshowallfiles false else # here come, if false or empty (the default) defaults write com.apple.finder appleshowallfiles true fi killall finder then: chmod a+x switchhideshow.command ready. unfortunately, should close terminal every time run it

Function and selection issue in C++ -

i revised post. new programming , not know if functions set correctly or how allow selection of packages. below objective. i have class assignment write c++ program calculate customers monthly internet bill. input customer name, package customer purchased, , how many hours used. the requirements are: input validation: sure user selects package b or c. display , error message if wrong package entered. calculation: packa 9.95 month 10 hours of acess. 2 bucks per additional hour. packb 14.95 month 20 hours of acess. 1 bucks per additional hour. packc 19.95 month unlimited acess. i have create output bill. the code wrote far is: /* james hayek cis 165 passaic county community college program 04 */ #include <iostream> #include <iomanip> using namespace std; double calcbill(double packagechoosen, double hours, double basepack, char name); // function prototype calcbill void dispbill(char packagechoosen, double hours, double basepack, char name, char bi

c# - How to make own event handler? -

i making windows forms project in c#, in made class labelx inherits system.windows.forms.label , added property mass of float type now, question how can handle, when value of mass changed. e.g.: when user enter value zero or less zero want fire message "mass can't 0 or negative" if interpreting correctly, there 2 parts this. first, need detect invalid values , throw exceptions. second, need raise event when property changes. can achieved follows. private float mass; public float mass { { return this.mass; } set { if (value <= 0.0f) { throw new argumentoutofrangeexception("mass cannot 0 or negative."); } if (this.mass != value) { this.mass = value; onmasschanged(eventargs.empty); } } } public event eventhandler masschanged; protected virtual void onmasschanged(eventargs args) { var handler = this.masschanged;

java - What "inconsistent synchronization" means? -

this java 1.6 class: public class foo { private arraylist<string> names; public void scan() { if (names == null) { synchronized (this) { this.names = new arraylist<string>(); // fill array data } } } } findbugs says: inconsistent synchronization of com.xxx.foo.names; locked 40% of time what mean , i'm doing wrong? i'm trying avoid problems when 2 or more clients call foo.scan() @ same time. it's beacuse synchronizing when set names variable , not when read it. between read , write thread execute , you'd create 2 arraylists , fill them data, first 1 created gc'ed. you need put synchronized block around read , write or add synchronized modifier method. public class foo { private arraylist<string> names; public void scan() { synchronized (this) if (names == null) { this.names = new arraylist<string>(); // fill array data }

php - Best way to store views / stats in MySQL -

i'm working no site stores individual page views in 'views' table: create table `views` ( `view_id` bigint(16) not null auto_increment, `user_id` int(10) not null, `user_ip` varchar(15) not null, `view_url` varchar(255) not null, `view_referrer` varchar(255) not null, `view_date` date not null, `view_created` int(10) not null, primary key (`view_id`), key `view_url` (`view_url`) ) engine=myisam default charset=utf8 auto_increment=1 ; it's pretty basic, stores user_id (the user's id on site), ip address, url (without domain reduce size of table little), referral url (not using right , might rid of it), date (yyyy-mm-dd format of course), , unix timestamp of when view occurred. the table, of course, getting rather big (4 million rows @ moment , it's rather young site) , running queries on slow. for basic optimization i've created 'views_archive' table: create table `views_archive` ( `archive_id` bigint(16) not null a

ruby on rails - Testing association methods with Mocha -

i have rails app order , refund model. order has_many :refunds. , good. i'm trying write functional test refund logic in controller. here's have right now: test "should not process partial paypal refund partially refunded order when refund total plus refund amount greater order total" set_super_admin_login_credentials o = order.new o.stubs({:id => 1234567, :source => "paypal", :total => 39.95, :user => users(:dave)}) order.stubs(:find).with(1234567).returns(o) :refund, {:order_id => 1234567} assert_equal o, assigns(:order) o.refunds.build.stubs({:amount => 1.0}) o.refunds.build.stubs({:amount => 30.00}) assert_raise post :refund, {:order_id => 1234567, :refund_amount => 10.00} end end and in controller, refund method looks this: def refund @order = order.find(params[:order_id]) return if request.get? amount = params[:refund_amount].to_f raise "canno

visual studio 2010 - Step into .net framework System.Web, 4.0 -

is able load symbols 4.0 version of system.web in visual studio 2010? have seen many tutorials on not able find symbols work. symbols microsoft symbol servers not work , stripped down (very small size). symbols http://referencesource.microsoft.com/netframework.aspx seem right size not seem match. make sure have full version of .net framework installed on machine, , not client profile. application developers require features not included in client profile should target full .net framework 4 instead of client profile .

mod rewrite - cakephp acl redirecting denied user to index.php/index.php -

i'm getting grips cakephp (1.3), , hitting problem can't figure out, , google has failed me. because i'm in stupid intranet has ancient version of iis server, can't use mod_rewrite. when authenticated user (using auth) attempts visit action of controller denied, acl redirects them page they're on - adds "index.php" in url. breaks next link user clicks - e.g i'm at /myapp/index.php/teams/ and visit /myapp/index.php/teams/add but i'm not allowed in there acl, redirected to /myapp/index.php/index.php/teams which works fine, unless try access forbidden page again (or links on page), , wind at /myapp/index.php/index.php/index.php/teams i guess acl redirection doesn't lack of mod_rewrite, have override - how? i'd happily have redirect failed attempts access forbidden pages root - how do without totally overriding acl (and having add in manually suggested in question , defaults point of using in first place). any ideas (o

c# - Objects Retrieved from List<T> Appear to Be Copies, Not References -

in code, have class maintains number of lists. we'll focus on 1 of them moment, since it's 1 highlighted problem. internal list<badge> badges { get; private set; } in code, add badge instances list when xml document parsed. later, want update individual instances in list can have data written out xml. because of way data's xml structure differs original file structure, there's hocus-pocus involved, that's largely mapped out. surprise came when attempted update item in list<badge> . specifically, problematic code here: // current badge loaded xml data, can update it. var currentbadge = this.gamedata.getcurrentbadge(); i valid badge back. surprise, i've come find out, simple test fails: var result = this.gamedata.badges.indexof(currentbadge); result evaluates -1, indicating object doesn't exist in collection. (edit: updating properties on currentbadge has no effect whatsoever on contents of matching item in this.gamedata.badges

c# - What would be a good approach to create this application? -

i'd create simple application lists computers on given computers network. i'd them able send messages , each other. pretty simple. :) what simplest approach be? that's not automatically doable. on windows network can try equivalent of "net view", gives list of clients. in general, though, there's no guarantee computers discoverable. there approaches sort-of work doing nslookup on addresses in local network that's brute force , if computer doesn't register name in dns won't work either. assuming you've seolved problem of finding out ip address want talk need socket (udp packets or tcp streams) , can start chatting (or sending messages app app. introduction tcp/ip have examples that. in c# it's easy using socket or udpclient classes

ASP.NET MVC3 razor problem with international characters in custom html helpers -

i trying convert asp.net mvc2 application asp.net mvc3 razor. have lot custom html helper methods, render html output, 1 below, renders button markup : stringbuilder sb = new stringbuilder("<input type='submit' id='") .append(buttonid) .append("' name='" ) .append(buttonid) .append("' value='") .append(buttonvalue) .appendline("' class='myclass1 myclass2' />"); return mvchtmlstring.create(sb.tostring()); when buttonvalue contains international characters é or ë, text of button gets rendered wrong, guess kind of encoding occurs... eg. ë changed ë i know, mvc3 uses kind of templating system html helpers, have lot of own helpers take time know , change current custom helpers. problem solved, apparently had encoding of cshtml files, generated small c# program tries convert webform syntax razor syntax. when writin

php - Assigning values to a multi-dimensional array for checkers -

my question instead of using coordinates move can assign numbers , letters can move values edit: outputting board html 8x8 table $square = array( // b c d e f g h 0 array(0,0,0,0,0,0,0,0), 1 array(0,0,0,0,0,0,0,0), 2 array(0,0,0,0,0,0,0,0), 3 array(0,0,0,0,0,0,0,0), 4 array(0,0,0,0,0,0,0,0), 5 array(0,0,0,0,0,0,0,0), 6 array(0,0,0,0,0,0,0,0), 7 array(0,0,0,0,0,0,0,0), ); so when user inputs : from: f1 to: g2 pieces move wouldn't better this array ( 'a' => array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 ) 'b' => array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 ) 'c' => array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 ) &#

python - Parsing HTML Tables with BeautifulSoup -

i have used beautifulsoup in past against new; incredibly generic/minimal html table markup... goal grab each value , it's label (each in there own td) , print them out... can merged, don't care, want make sure each label applied correct value. here example table: <tbody><tr> <td class="labels">dawn:</td> <td class="site_data" style="text-align: left;">07:01</td> <td class="labels">sunrise:</td> <td class="site_data" style="text-align: left;">07:26</td> <td class="labels">moonrise:</td> <td class="site_data" style="text-align: left;">14:29</td> <td rowspan="3"><img src="images/moon.bmp" alt="moon" width="64" align="left" border="0" height="64" style="margin: 0px 10px" /></td> </tr> <tr> <td

flash - Create dynamic PDF in Flex -

trying understand high-level how accomplished. use case: flash application embedded in html used create certificates (just example). user enters bunch of data form (name, address, certificate for, etc.). user clicks button causes application create certificate in pdf form, form data displayed in format define bunch of different images). ideally, flex use browsers functionality prompt user "what document, 'download', 'open'. function clicking on link pdf document inside of web page. i have form , everything, matter of how create pdf data. there function can take current screen , create pdf image of it? or there library creating pdfs? if can point me in right direction appreciated. there as3 pdf generator library called alivepdf , can found here .

jsf - How do I design an application to manage translatable entity fields? -

when designing application support internationalization, not @ level of labels , calculated values, in fields (e.g. entity name & description), how should model designed? there libraries or frameworks can make things easier? (but not limited to) in jpa / jsf / seam? we use seam , i18n @ least "name" properties. store message key in db , resolve translation via messages_*.properties , seamresourcebundle.getbundle().getstring(entity.getname()) .

ti basic - How do I iterate through a list in a TI-83 calculator program -

i created set of programs calculate area under graph using various methods of approximation (midpoint, trapezoidal, simpson) calculus class. here example of 1 of programs (midpoint): prompt a,b,n (a-b)/n->d input "y1=", y1 0->x 0->e for(x,a+d/2,b-d/2,d) y1(x)+e->e end disp e*d instead of applying these approximation rules function (y1), apply them list of data (l1). how iterate through list? need able last index in list in order "for loop" good. can't l1.length in java. you can obtain length of list using dim() . can found in 2nd->list->ops->dim( . make sure use list variable otherwise dim() complain type. index list subscript. e.g., {1, 2, 3, 4} -> l1 (x, 1, dim(l1), 1) disp l1(x) end

C file read by line up to a custom delimiter -

is there function in c read file custom delimiter '\n'? for example: have: i did write \n exemplify in file lf (line feed, '\n', 0x0a) this firstline\n second line\n i'd file read part , split in 2 strings: this firstline\n second line\n i know fgets can read num of characters not pattern. in c++ know there method in c how it? i'll show example: i'm reading file abc.txt abc\n def\n ghi\n with following code: file* fp = fopen("abc.txt", "rt"); const int linesz = 300; char line[linesz]; char* res = fgets(line, linesz, fp); // res filled abc\ndef\nghi\n fclose(fp); i excpected fgets had stop on abc\n but res filled with: abc\ndef\nghi\n solved: problem using notepad++ in windowsxp (the 1 used don't know happens on other windows) saved file different encoding. the newline on fgets needs crlf not cr when type enter in notepad++ i opened windows notepad , worked fgets reads string abc\

Jquery Templates plugIn -

hey guys, i'm trying example dave ward blog about jquery templates , i'm doing wrong. appreciated. here's code: data: var invoice = { invoiceitems: [ { type: 'item', part: '99designs', description: '99 designs logo', price: 450.00, qty: 1 }, { type: 'service', service: 'web development , testing', price: 25000.00 }, { type: 'item', part: 'linodemonthly', description: 'monthly site hosting', price: 40.00, qty: 12 } ] }; client: <script id="invoicetemplate" type="x-jquery-tmpl"> <table class="invoice"> {{each lineitems}} {{tmpl($value) get_invoicerowtemplatename(type)}} {{/each}} </table> </script> js: $(function () { $('#invoicetemplate').tmpl(invoice).appendto('body'); }); function get_invoicerowtemplatename(type) { // return t

javascript - Markup for tabbed interfaces -

i checked out couple solutions tabbed interfaces (including jquery ui), , markup follows same ul-li-a pattern: <ul class="tabs"> <li><a href="#tab1">title 1</a></li> <li><a href="#tab2">title 2</a></li> </ul> is considered best practice, , why? far have used span or div tags, , worked fine. also, why "a" tags? here trigger hover , active states on older browsers? it's semantic markup several reasons: it unordered list of stuff, namely title 1, title 2 etc. if javascript disabled, have div elements ids of tab1 , tab2 in markup, links behave correctly , send right div . it makes tabs accessible. and there lot of reasons using semantic html .

ruby - Why don't I see more constructors in rails models -

it seems rarely, if ever, see or use ruby constructor in rails model. my assumption because rails sets stuff need initialization code lower. aren't there use cases constructor in model though? there's nothing wrong constructor, they're hardly ever needed. main reason constructor setting default values. setting default attributes, done @ database level add_column :users, :admin, :boolean, :default => false the main other thing might needed existence/creation of association model, can done either in constructor/initializer, what's more common use rails hooks set before_create :populate_children, :ensure_parent_exists (where populate_children, , ensure_parent_exists private model methods) or that. approach means initialization logic can divided logical methods (e.g. separate methods each bit of initialization), , can additionally called @ other times after_save :ensure_parent_exists , , allows more flexibility

How to get width of a truetype font character in 1200ths of an inch with Python? -

i can height , width of character in pixels pil (see below), (unless i'm mistaken) pixel size depends on screen's dpi, can vary. instead i'd calculate width of character in absolute units inches, or 1200ths of inch ("wordperfect units"). >>> # getting pixels width pil >>> font = imagefont.truetype('/blah/fonts/times.ttf' , 12) >>> font.getsize('a') (5, 14) my reason wanting create word-wrapping function writing binary word perfect documents. word perfect requires soft linebreak codes inserted @ valid points throughout text, or file corrupt , unopenable. question add them variable width fonts. i realize don't understand relationship between pixels , screen resolution , font sizes. going wrong?

jquery - Can slickgrid page and display json -

we want load several thousand records client when page requested , have first 25 records displayed. user should able page through records or resort list column or filter data in various columns. we're opting load data client in 1 lump sum because we'd rather have heavier load in page request , faster performance when viewing or editing data after. can't see example paging on slickgrid site. slickgrid have paging baked in or lightweight i'd have implement myself? have links or examples share give me headstart? the data we'll using json data. i've been coding slickgrid week , found had write sort , filter code myself. looking through source, don't see indicates paging built in. you'll spend amount of time writing code it, seems worth it. i loaded 30,000 rows of data using ajax/json , loads , sorts in less 1 second. don't know if help, method call load grid. sorts on client , filters on server: $.getjson(baseurl + '/_getnewhir

Cross-platform means of getting user's home directory in Ruby? -

java has convienient system.getproperty("user.home") user's "home" directory in platform-independent way. what's equivalent in ruby? don't have windows box play around with, , feel relying on tildes in filenames isn't cleanest way. there alternatives? the file.expand_path method uses unix convention of treating tilde ( ~ ) specially, ~ refers current user's home directory , ~foo refers foo 's home directory. i don't know if there's better or more idiomatic way, file.expand_path('~') should going.

rtf - C# Detect Key Press, avoid non-typing keys -

is there way proceed method if key being pressed not result in typing. i.e. shift key, control key etc without having specify of them. ideally, detect combinations of keys, example control+v = paste. code similar below working with; if( (e.keydata == keys.left) || (e.keydata == keys.right) || (e.keydata == keys.home) || (e.keydata == keys.end) || (e.keydata == keys.up) || (e.keydata == keys.down) || (e.keydata == keys.shiftkey) || (e.keydata == keys.controlkey) ) return; but don't want add every single combination of keypresses. any ideas? protected override bool processcmdkey( ref message msg, keys keydata ) { if ( keydata == (keys.control | keys.v) ) return true; else return base.processcmdkey( ref msg, keydata ); } that takes care of copy+paste. can override onkeypress , use char.isdigit and/or char.isletter (or char.isletterordigit) if needed. idea, don't think regu

sqlite / python - named parameters without enclosing quotes? -

when using prepared statements named parameters in sqlite (specifically python sqlite3 module http://docs.python.org/library/sqlite3.html ) there anyway include string values without getting quotes put around them ? i've got : columnname = '''c1''' cur = cur.execute('''select distinct(:colname) t1''', {'colname': columnname}) and seems sql end : select distinct('c1') t1 which isn't use of course, want : select distinct(c1) t1 . is there way prompt execute method interpret supplied arguments in such way doesn't wrap quotes around them ? i've written little test program explore it's worth here : import sys import sqlite3 def getdatabaseconnection(): defaultdbpath = ':memory:' conn = sqlite3.connect(defaultdbpath, detect_types=sqlite3.parse_decltypes|sqlite3.parse_colnames) conn.text_factory = str return conn def initializedbtables(conn): conn.execute(&

Printing in icefaces -

i print reports in icefaces, got find proper method it. please guide me implementation of same in project. i've used ice:outputresource tag let user download pdf report file. resource attribute of tag should point managed bean property implements com.icesoft.faces.context.resource.

database - Is there such thing as a "asynchronous trigger" in DB2? -

what want know whether possible program insert staging table, , have trigger run asynchronously on piece of data. procedure trigger running time consuming process, that's why wanted run asynchronously. for kind of operation, program cron, , @ specific times. can use taskcenter (which deprecated since version 9.x) , can trigger process whenever want, or when condition has been reached. anyway, have more clear necessity of begin asynchronous. table acquire many locks? process use lot of cpu? table used in parallel other processes?

Coldfusion 9 + SQL server 2008 datetime returns binary -

i have simple query written in coldfusion 9. have datetime field selecting, odd reason query returns binary instead of date. is there work around not require me cast date char. you try using tostring(), creating date/time object using createodbcdatetime() function...

C++ Initialize class static data member -

i have class has number of static function perform calculation. however, before calculation, need pass in data initialize of static data members. have init(data) function , clearresource() function should called before , after use of class. there better way of doing that? for example: classa(){ static int a; static init(int b) { = b; } static functiona(){ //perform based on value of a; switch(a){ } } } int main(){ classa::init(5); classa::functiona(); } thanks avoid using static member functions : have constructor initialize data , destructor clear resources (see raii ). if existing class cannot changed, implement helper class calls init constructor , clearresource destructor.

ruby on rails - Why I can not get the facebook connect button with facebooker? -

my rails version 2.3.4. at first install gem gem install facebooker and add these code login page <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/featureloader.js.php" type="text/javascript"></script> <%= fb_connect_javascript_tag %> <%= init_fb_connect "xfbml" %> <%= fb_login_and_redirect(facebook_login_users_path) %> and add code application_controller before_filter :set_facebook_session helper_method :facebook_session but cannot see blue connect button! i think miss something, can give me advice? thanks! i found problem. if using jquery code need be: <%= fb_connect_javascript_tag :js => :jquery %>

asp.net - MapPageRoute on iis7 not working (but works in iis6) -

my website runs fine on iis6, can see here: http://93.115.250.xxx/ i tried migrate iis7, , after lot of hussle can see starting page, urls rewritten through mappageroute give 404 can see here: 94.75.xxx.xxx any ideas why iis7 trying access physical file , ignores pageroute? i programming in mixed environment. alpha server server2008, beta , production still 2003. need modify config file have system.webserver node following entry: <system.webserver> <modules runallmanagedmodulesforallrequests="true"/> </system.webserver> i not sure if applicable in instance, application required log-in accept publicly available image files available re-written directory. don't forget add except route mapped: <location path="{target path}"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </locati

iphone - is Gesture Recognization working on buttons or not? -

in app, wrote these lines of code : - (void)viewdidload { [super viewdidload]; uitapgesturerecognizer *tapper = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(tapped:)]; [mybutton1 addgesturerecognizer:tapper]; [mybutton2 addgesturerecognizer:tapper]; [mybutton3 addgesturerecognizer:tapper]; [tapper release]; } -(void)tapped:(uigesturerecognizer *)sender{ nslog(@"i'am in tapped"); } but nothing happened. why ? , if need button's currenttitle inside tapped, can ? thanks you're missing recognizer delegate. implement that. should add uigesturerecognizerdelegate protocol header file , make recognizer.delegate = self . re: getting title - can title. in tap event handler can extract information sender object. i'll post code later...

java - Progress bar for File Uploading? -

i using servlets upload files in web application. want show progress bar while uploading. have went through ajax+progresslistener examples, 1 here . in dopost() method creates session object , sets new attribute listener. apart previous code , tutorials code dopost() method same. my question setting listener attribute 1 time, @ beginning. how update bytesread frequently (i new this, so, questions maybe unreasonable) in doget() method retrieve listener attribute , extracts needed information it. this part also, not able understand. not implementing progresslistener class(searches, led me class). i know dwr. so, can use data transfer information server, if understood server side process update data transfer. shall 1 explain me server side process? or links or suggestions appreciative @ moment!!! thanks! similar thread, file upload java progress bar .

c# - Using string as a lock to do thread synchronization -

while looking @ legacy application code noticed using string object thread synchronization. i'm trying resolve thread contention issues in program , wondering if lead strange situations. thoughts ? private static string mutex= "abc"; internal static void foo(rpc rpc) { lock (mutex) { //do } } strings (from code) " interned ". means instances of "abc" point same object. across appdomain s can point same object (thx steven tip). if have lot of string-mutexes, different locations, same text, lock on same object. the intern pool conserves string storage. if assign literal string constant several variables, each variable set reference same constant in intern pool instead of referencing several different instances of string have identical values. it's better use: private static readonly object mutex = new object(); also, since string not const or readonly , can change it. (in theory) possible lock on mu

Django not like statement -

how use not in django queries model.objects.filter(keywords not "null" or "undefined") select * model keywords not "%undefined%" or keywords not "%null%"; use exclude function , q objects model.objects.exclude(q(keyword__contains='undefined') | q(keyword__contains='null'))

javascript - Continuous movement when a key is held down -

is possible in jquery have element continuously move when key held down? i've tried few ways have break in between animation calls. code have: $(document).keydown(function (e) { if (e.which == 37) { $('#you').stop().animate({ left: '-=16px' }, 10); } }); $(document).keyup(function (e) { $('#you').stop(); }); .animate() isn't best way. // cache jquery objects performance var = $( "#you" ) , doc = $( document ) // variable hold motion state , activemotion // godown motion, adjust numbers taste , godown = function(){ you.css( "left" , you.css( "left" ) - 16 ); if ( activemotion === godown ) { settimeout( godown , 10 ); } } doc.keydown( function( e ) { if ( e.which === 37 && activemotion !== godown ) { activemotion = godown; godown(); } // directions can go here in seperate if/else statements // sure include "active

performance - Nhibernate Nunit - clear database between testcases -

we have rather extensive test suite takes forever execute. after each test has completed, database (mssql) needs emptied fresh next testcase. way temporarily removing foreign keys, truncate'ing tables, , re-adding fks. this step takes somewhere between 2-3 seconds, according nhprofiler. time seemingly spent fk operations. our current method not optimal, way should go improve performance ? number of elements deleted db insignificant compared number of operations fk removal/additions. using in-memory sqlite database not option, code under test uses mssql specific operations. you wrap in transaction , in end rollback everything. that's how it. allows run tests in parallel.

javascript - how to set textbox value in jquery -

how load value textbox using jquery?tried 1 below [object object] output. please enlighten me on this, i'm new jquery. proc = function(x,y) { var str1 = $('#pid').value; var str2 = $('#qtytobuy').value; var str3= $('#subtotal').load('compz.php?prodid=' + x + '&qbuys=' + y); $('#subtotal').val(str3); } and here's html form: <form name="yoh" method="get"> product id: <input type="text" name="pid" value=""><br/> quantity buy:<input type="text" name="qtytobuy" value="" onkeyup="proc(document.yoh.pid.value, this.value);"></br> subtotal:<input type="text" name="subtotal" id="subtotal" value=""></br> <div id="compz"></div> </form> i think want set response of call url 'compz.ph

Best way to input data into multiple sheets in Excel? -

basically need able have few tables sales of specific categories e.g. pc , laptop. need have main table displays sales. for input i'm using input boxes , dropdown select category (pc or laptop), input put in 1 large table along sale information. i'm wondering best method having data put in separate worksheet category is? i'm @ bit of loose end start. thought possibly using if statement in vb if input e.g. pc insert worksheet pc seems quite inefficient way of doing this. your ideas appreciated. if unsure place vb code, it's best add code not behind 1 of sheets, in separate module. on other hand, need entry point code called @ specific event. might worksheet event (for example, change event) or button or menu user has activate when wants main table updated. call module code there. if provide specific example, give better answer. using worksheet change event: add code each of input sheets: private sub worksheet_change(byval target range) updatema

javascript - Noob question: How to get information if google map is loaded (initialized) -

i new google maps api. took sample manual , trying change way need, here trying do: example google maps manual var geocoder; var map; function initialize() { geocoder = new google.maps.geocoder(); var latlng = new google.maps.latlng( 40.714353, -74.005973); var myoptions = { zoom: 10, center: latlng, maptypeid: google.maps.maptypeid.roadmap } map = new google.maps.map(document.getelementbyid("map_canvas"), myoptions); } function codeaddress() { var address = document.getelementbyid("address").value; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.geocoderstatus.ok) { map.setcenter(results[0].geometry.location); var marker = new google.maps.marker({ map: map, position: results[0].geometry.location }); } else { alert("geocode not successful following reason: " + status);

objective c - Fetch from Core Data sorted by formatted date -

i having trouble fetching results core data sorted date. i have db table contains football matches. each match has hometeam, awayteam , kickofftime. kickofftime nsdate stores date , time match start. i want display results of query in tableview divided sections kickoff date. date section heading. this little more complex might first appear. due differing time zones match starting on 1 date in 1 part of world starting on different date in part of world. can't ignore times , store kickoff dates in column. what i'm trying create custom accessor returns formatted date, in whatever time zone user in, , use sort , section results. here's code in match.h: @dynamic kickofftime; @dynamic formattedkickofftime; @dynamic dateformatter; - (nsstring *)formattedkickofftime { [self willaccessvalueforkey:@"kickofftime"]; // set date formatter format want display date [dateformatter setdateformat:@"ccc, d mmm"]; // format date nsst

C++: Boost local time is one hour behind -

i living in netherlands, when run code: boost::local_time::local_date_time t = boost::local_time::local_sec_clock::local_time(boost::local_time::time_zone_ptr()); std::cout << "\ndate time: " << t.to_string() ; the "date time" returned 1 hour behind. utc should gmt+1 or utc+1 current system date time! what should change boost::local_time system date time. thanks in advance. boost::local_time::time_zone_ptr zone_gmt1(new boost::local_time::posix_time_zone("gmt+1")); boost::local_time::local_date_time t = boost::local_time::local_sec_clock::local_time(zone_gmt1); i found out use timezone. it works fine me thanks!

events - Iphone tab bar control -

i have tab bar control , need method in view controller of each tab called once tab bar item selected. does know method gets called? thanks you can implement uitabbarcontrollerdelegate , have: - (void)tabbarcontroller:(uitabbarcontroller *)tabbarcontroller didselectviewcontroller:(uiviewcontroller *)viewcontroller where retrieve viewcontroller on can call whatever method. you tabbarcontroller contains viewcontrollers on iterate call method

Java, runtime class reloading -

i looking way reload class java @ runtime. motivation make debugging more efficient. application typical client/server design synchronously processes requests. "handler" object instantiated each request. class intend dynamically replace. since each request deals fresh instance, reloading class won't have side-effects. in short, not want restart entire application every time there change module. in design, java process becomes aware .class file has been updated in classpath in between requests. when happens, "handler" class unloaded , new 1 loaded. i know can use classloader interface load in new class. seem having trouble finding proper way of "unloading". classes unloaded , garbage collected other object, if there no remaining reference them. means there must no reachable instance of class (as loaded particular classloader instance) , classloader instance must eligible garbage collection well. so basically, have create new classload