Posts

Showing posts from January, 2014

c++11 - Does the C++ standard guarantee that std::uintmax_t can hold all values of std::size_t? -

does c++ standard guarantee (either explicitly stating or implicitly logical deduction) std::uintmax_t can hold values of std::size_t ? or possible std::numeric_limits<std::size_t>::max() larger std::numeric_limits<std::uintmax_t>::max() ? yes. size_t defined unsigned integer type large enough contain size of object. uintmax_t defined able store value of unsigned integer type. if size_t can store it, uintmax_t can store it. definition of size_t c++11 §18.2: the type size_t implementation-defined unsigned integer type large enough contain size in bytes of object. definition of uintmax_t c99 §7.18.1.5 (it included in c++ normative reference): the following type designates unsigned integer type capable of representing value of unsigned integer type: uintmax_t

excel named range copy from sheet to sheet -

Image
i have excel question, wondering if there easy way set clone or copy of named range in 1 worksheet worksheet in same workbook. need done automatically data comes in through third party software tool. not advanced excel user , hoping there simple way without macros, vba code etc. thoughts? thanks! you can set scope of source named range sheet, copy sheet. named ranges copied well. to change scope, use name manager in data section of ribbon, or push ctrl + f3 . select range , click edit. to copy sheet, right click on sheet name , select "move or copy"

javascript - Stop page from scrolling when div is scrolled to the bottom -

basically, have scrolling div. want div scroll obviously, once scrolled way bottom, if user continues scroll, don't want page scroll. basically, when mouse in div, want scrolling within div, , when mouse outside of div want page scroll. there way of doing this? i'm using jquery other aspects of site have if helps. well, thing see happening focus not set div when move it, , loose focus when move out. example javascript: <div onmouseover="javascript:this.focus();" onmouseout="javascript:this.blur();"> also, sure css class div has following, in specific order: overflow: auto; overflow-y: scroll;

Android and Eclipse - java.lang.NoClassDefFoundError with project dependency -

i'm trying build abstract classes in 1 project template , implement them in another. when trying run activity implements template activity, noclassdeffounderror pops up. i've added template project java build path of other one, checked in "order , export", cleaned project, nothing helps. tried compile project 1.6 compiler. resulted same error. when trying add template project jar eclipse says there's duplicate of manifest files , won't allow it. does has idea else can fix problem? here's error log receive: 04-05 00:29:09.941: e/androidruntime(1348): fatal exception: main 04-05 00:29:09.941: e/androidruntime(1348): java.lang.illegalstateexception: not execute method of activity 04-05 00:29:09.941: e/androidruntime(1348): @ android.view.view$1.onclick(view.java:2144) 04-05 00:29:09.941: e/androidruntime(1348): @ android.view.view.performclick(view.java:2485) 04-05 00:29:09.941: e/androidruntime(1348): @ android.view.view$performclick.ru

File creation in Python -

i have been reviewing the tutorial file management in python 3 doesn't mention how create file if 1 doesn't exist. how can that? just open file in write mode: f = open('filetowrite.txt', 'w') note clobber existing file. safest approach use append mode: f = open('filetowrite.txt', 'a') as mentioned in this answer , it's better use with statement ensure file closed when have finished it.

IOS - remove ALL padding from UITextView -

Image
there many great examples on remove left padding of uitextview. how lose margin/padding in uitextview? however, need remove right padding too. i have tried... [tv setcontentinset: uiedgeinsetsmake(-4,-8,-8,-x)];//where x integer and every other permutation of last 2 values remove padding , nothing seems work. have tried [tv sizetofit]; [tv settextalignment:[nstextalignmentright]]; the following text in textview says "00" although ios 7 only, extremely clean solution set textview's textcontainerinsets such: [textview settextcontainerinset:uiedgeinsetszero]; textview.textcontainer.linefragmentpadding = 0; // remove left padding this remove padding (insets) around text inside text view. if deployment target ios 7+ best solution far.

objective c - mouseUp not firing in Cocoa? -

i'm trying implement drag&drop functionality in app , ran problem of mouseup event not firing. fires fine if click , release on view, if drag, mousedragged event fires , that's it. by trying different things figured out problem in dragimage call, don't know how solve now. here code: -(void) mousedragged:(nsevent *)theevent { isdragging = yes; if ([selectedcellrowindex longvalue] >= 0) { nsimage *im = [[nsimage alloc]initwithcontentsoffile:@"/users/username/desktop/drag.png"]; nssize dragoffset = nsmakesize(0.0, 0.0); nspasteboard *pboard = [nspasteboard pasteboardwithname:nsdragpboard]; [pboard declaretypes:[nsarray arraywithobject:nstiffpboardtype] owner:self]; [pboard setdata:[im tiffrepresentation] fortype:nstiffpboardtype]; [self dragimage:im at:downpointrelativetotable offset:dragoffset event:theevent pasteboard:pboard

c# - How to add a json array into a property of a JObject with json.net -

i having difficulty figuring out how add array of json objects existing jobject . have jobject "modified" property, , want add property "intersectgroups" contains array of json objects, how can this? have jobject[] when serialize in format require, looking this: mainjobject.add("intersectgroups", myjobjectarray) here example of final json want when serialize it. ... "modified": "2012-11-26t10:21:04.693", "intersectgroups": [ { "id": 1004, "userid": 20003, "groupid": 1001, "admin": false, "expires": "1900-01-01t00:00:00" }, { "id": 1003, "userid": 20003, "groupid": 1000, "admin": false, "expires": "1900-01-01t00:00:00" } ] ... update my final solution use jarray object. jarray jcontainer, jtoken, can add jobject. problem was trying use jobject[], no

java - ActionListener - Tracing if actionPerformed is called inside actionPerformed method? -

say have 'select' jbutton selectpiecelistener. want check if action(clicking select button) performed again or not. however, actionperformed void, cannot use boolean expression. is there way that? or better use jbutton handle this? thank you. public class selectpiecelistener implements actionlistener { @override public void actionperformed(actionevent e) { if(c == _st.checkmoveimpossible()) { system.out.println("no possible move "+nextplayer+": click select skip turn, " + "or click right move " + t + " pieces."); if(**the action performed**){_board.setcmi(1);} _board.update(); } do want know if select button has been clicked once (1) ? or want make sure actionperformed method isn't called recursively (2)? (1) add boolean field selectpiecelistener called 'selectpressed' (or whatever), , set true when actionperformed called. (

Can you use google app engine as the serverside solution for an android mobile app -

i have android app want connect server (and database) store persistent data. can use google app engine provide functionality including account verification? might have guessed - i'm not web programmer, want choose right direction. to clearer - want use server proivde set of web services read/write access data stored in datastore cheers, anton definitely yes. here links started: creating app engine connected android project . google i/o 2011: android + app engine: developer's dream combination - youtube video.

jpa 2.0 - Exception [EclipseLink-4002] while using native query for joining two tables -

i have 2 tables sponsors , study. columns in sponsor , study tables are: sponsors table structure: sponsorid: int primary key auto_increment, sponsorname: varchar(30) unique not null, address: varchar(255) study table structure: studyid int primary key auto_increment, studyname varchar(30) unique not null, sponsorid int not null foreign key sponsors table. study sponsor has manytoone relationship. i trying display fields in sponsors , study in datatable , perform create, update , delete operations on it. this method have used populating datatable. public list retrievestudy() { query query=getentitymanager().createnativequery("select"+ "s.studyid,s.studyname,s.sponsorid ,sp.sponsorname as"+ "sponsorname,sp.address study s left join sponsors sp", study.class); return query.getresultlist(); } while displaying datatable study want display sponsorname instead of sponsorid so, have

javascript - Get last word js -

this removes last word. how last word (stripe)? var baseshirturl = "base shirt draped fabric stripe"; baseshirturl = baseshirturl.substring(0, baseshirturl.lastindexof(" ")); alert(baseshirturl); to last word: baseshirturl.split(' ').pop(); and remove last word can this: baseshirturl = baseshirturl.replace(/\w+$/,'');

shell - Sort ignores an apostrophe - sometimes (except when it is the only column used); WHY? -

this happens me both on linux , on cygwin, suspect not bug. still, don't understand it. can explain? consider following file (tab-delimited, , that's regular apostrophe) (i create cat ensure wasn't non-printing characters source of problem) $cat > temp cat 1389 cat' 1747 ca't 3175 cat 46848484 ca't 720 $sort temp <gives exact same output cat temp> $sort -k1,1 temp cat 1389 cat 46848484 cat' 1747 ca't 3456 ca't 720 why have ignore second column in order sort correctly? i pulled manual sort , noticed following: * warning * locale specified environment affects sort order. set lc_all=c traditional sort order uses native byte values. as turns out, locales specify how lexicographic ordering works given locale. makes lot of sense, reason trips on multi field files... (see also:) unusual behaviour of linux's sort command why sort command sort differently

php - Congratulation page not showing the variable from the number-guessing game -

i have php script number-guessing game , html script congratulation page. if guess correct, game end , congratulation page open. in php, have variable $prize=1000-100 * $_post['tries'], such if first guess right, player win $1000; if player has second guess, prize $100 less, , on. variable saved in hidden field in php $_post['prize']. hope final prize can printed in congratulation page, didn’t work expected. did wrong in html? guys, maria. guess.php: <?php if(isset($_post['number'])) { $num = $_post['number']; } else { $num = rand(1,10); } if(isset($_post['prize'])) { $prize =1000-100 * $_post['tries']; } else { $prize = 900; } $tries=(isset($_post['guess'])) ? $_post['tries']+1: 0; if (!isset($_post['guess'])) { $message="welcome guessing game!"; } elseif (!is_numeric($_post['guess'])) { $message="you need type in number."; } elseif ($_post['gues

what is use cases of F# explicit type parameters? -

as know, explicit type parameters in value definitions 1 way overcome "value restriction" problem. there cases when need use them? upd : mean "explicitly generic constructs", type parameter enclosed in angle brackets, i.e. let f<'t> x = x this rare, when want prevent further generalization (§14.6.7): explicit type parameter definitions on value , member definitions can affect process of type inference , generalization. in particular, declaration includes explicit generic parameters not generalized beyond generic parameters. example, consider function: let f<'t> (x : 't) y = x during type inference, result in function of following type, '_b type inference variable yet resolved. f<'t> : 't -> '_b -> '_b to permit generalization @ these definitions, either remove explicit generic parameters (if can inferred), or use required number of parameters, following example shows: l

preg replace - PHP preg_replace error wordpress -

i have following wordpress code function shortcode_parse_atts($text) { $atts = array(); $pattern = '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\s+)(?:\s|$)/'; $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text); if ( preg_match_all($pattern, $text, $match, preg_set_order) ) { foreach ($match $m) { if (!empty($m[1])) $atts[strtolower($m[1])] = stripcslashes($m[2]); elseif (!empty($m[3])) $atts[strtolower($m[3])] = stripcslashes($m[4]); elseif (!empty($m[5])) $atts[strtolower($m[5])] = stripcslashes($m[6]); elseif (isset($m[7]) , strlen($m[7])) $atts[] = stripcslashes($m[7]); elseif (isset($m[8])) $atts[] = stripcslashes($m[8]); } } else { $atts

How to use same sql query for multiple where clause in a procedure -

query #1 select @in_empcount = count (a.ch_empcode) bsc_review_emp_master inner join dbo.cmn_authorization b on (case b.vc_bu when '%' a.busscd else b.vc_bu end) = a.busscd in_review_no = @in_review_no , b.ch_empcode = @ch_empcode , b.in_rolecode in (136, 137, 138) query #2 select @in_empcount1 = count (a.ch_empcode) bsc_review_emp_master inner join dbo.cmn_authorization b on (case b.vc_bu when '%' a.busscd else b.vc_bu end) = a.busscd in_review_no = @in_review_no , b.ch_empcode = @ch_empcode , b.in_rolecode in (138, 139, 140) query #3 select @in_empcount2 = count (a.ch_empcode) bsc_review_emp_master inner join dbo.cmn_authorization b on (case b.vc_bu when '%' a.busscd else b.vc_bu end) = a.busscd in_review_no = @in_review_no , b.ch_empcode = @ch_empcode , b.in_rolecode in (141, 142, 145) result: select @in_empcoun

Mysql inner join twice and use WHERE on both joins -

in mysql, want select a.* a inner join condition satisfied whether directly (joining table b ) or through join table ( c ), where b.field = myvalue . can point out proper way results? i have following tables: a, b, c, associated follows (a joins b, b joins c, joins c): b / \ --- c it looks pretty straightforward, empty set when run following code, though results when restrict search joining b through c: select a.* inner join c on c.id = a.c_id inner join b b_thru_c on b_thru_c.id = c.b_id inner join b b_from_a on b_from_a.id = a.b_id b_thru_c.field = 'myvalue' or b_from_a.field = 'myvalue'; # yields empty set select a.* inner join c on c.id = a.c_id inner join b b_thru_c on b_thru_c.id = c.b_id b_thru_c.field = 'myvalue'; # yields results how this? select a.* left outer join c on c.id = a.c_id inner join b on b.id = a.b_id or b.id = c.b_id b.field = 'myvalue';

Panda3D: How to configure mouse buttons for camera control? -

by default, mouse buttons assigned camera control as: left: translate right: zoom scroll/middle: rotate how change these mouse button bindings want this?: scroll/middle: zoom left: rotate right: translate i can see default mouse bindings camera control set in directcameracontrol.py . but, how can change them main class derived showbase ? the camera controls in directcameracontrol separate default controls, , changing these settings not affect default camera. default controls hardcoded in panda/src/tform/trackball.cxx ; presently not possible change these. the default camera controls intended development , debugging. purposes, you'll want use base.disablemouse() disable default camera controls , develop own camera control code.

r - fuzzy matching with multiple words -

i'm trying fuzzy matching in r, have multiple fields of data match against. for example: try_to_match <- c('seoul korea', 'bisbane', 'korea', 'australia brisbane') locations <- data.frame(name=c('seoul', 'brisbane'), country=c('south korea', 'australia')) i want match user-entered locations in try_to_match locations dataframe. now, there similar questions fuzzy matching r on so, , cover agrep . however, can't find cover fuzzy matching when there multiple words match over. for example, if match against locations$name , match "bisbane" "brisbane", expect. also, no matches various searches country in them, locations$name has no country in it. sapply(try_to_match, agrep, locations$name, value=t) # $`seoul korea` # character(0) # $bisbane # [1] "brisbane" # $korea # character(0) # $`australia brisbane` # character(0) so, guess shoul

send a html link in a email sent by php -

This summary is not available. Please click here to view the post.

Use PHP to find text within an HTML Page -

i write php code parse html return href , title of of images in "image_url" class. using substr find location of strings, webpage changes content , can't rely on substr. there dom way or other regular expression way can find these elements within html? <a class="image_url" href="/123.jpg" target="_blank"><img src="/123.jpg" border="0" title="some dynamic length image title making difficult me"></a> you can use 3 things far know php simple xml parsing php domdoucment. simplehtmldom parser

android - AsyncTask calling main class method, did it work fully in background? -

this problem..i calling method in doinbackground of asynctask class, method declared in main activity class. work in background thread? or need write whole method inside doinbackground ?? protected string doinbackground(string... params) { getallusersfromserver(); return null; } this getallusersfromserver(); declared in main class. method download data server using rest.. i need run whole process in background thread. works? does work in background thread? afaik, yes works in background thread. do need write whole method inside doinbackground ?? no need that. onpostexecute works next moment.. users information still loading this main point, working line line, when goes execute getallusersfromserver(); control goes execute method gets executed in background thread. [to understand add 1 log print line below method call in doinbackground , 1 in method's loop , see if loop doesn't complete doinbg log printed] th

Search for Google Drive files based on new properties resource -

google introduced new feature in google drive sdk ability set properties files, key/value pairs. according blog post on google developers blog can use these properties searchable fields. cannot see in documentation how search files using these properties. for example: retrieve files property has value x. i know feature brand new make use of in current project. have missed ? well find, possible search on drive based on properties param. check doc. https://developers.google.com/drive/web/search-parameters code snippet : resp = newdriveservice.files().list(q="properties has { key='customkeya' , value='customkeyavalue2' , visibility='public' }").execute() note : have specify 3 params viz. key, value , visibility while searching. if don't use throw invalid params exception.

serialization - Protobuf-net serializer for NEventStore 3+ -

can point me protobuf-net serializer neventstore 3.0? i'm having trouble think due serialization in event store 3 wrapping event body , headers in eventmessage. i'm not sure how setup custom serializer correctly. this entirely untested guesswork based on brief glance @ github, looks want use wire-up api specify custom serializer, example: var store = wireup.init() .usingsqlpersistence("name of eventstore connectionstring in config file") .initializestorageengine() .usingcustomserialization(myserializer) ... etc where myserializer instance of type implements iserialize interface. looks should work: class protobufserializer : eventstore.serialization.iserialize { public void serialize<t>(stream output, t graph) { protobuf.serializer.serialize<t>(output, graph); } public t deserialize<t>(stream input) { return protobuf.serializer.deserialize<t>(input); } }

ios - How to size UIWebView in a UIModalPresentationFormSheet? -

Image
i tried every permutation known mankind , cannot uiwebview size in modal form view ipad. web page still displays full ipad portrait width of 768 points. where , how tell uiwebview display width 540 points? i thought 'scalespagetofit' supposed not work. i tried setting web view size of form view 540 x 576 navigation , status bar. height irrelevant though. i tried adding uiwebview uiview in storyboard resizing set. removed uiwebview , added programmatically. - (void)viewdidload { [super viewdidload]; cgrect aframe = self.view.frame; if (is_ipad) { aframe = cgrectmake(0, 0, form_view_width, form_view_height); } _webview = [[uiwebview alloc] initwithframe:aframe]; [_webview setopaque:no]; [_webview setdelegate:self]; [_webview setscalespagetofit:yes]; self.view = _webview; ... } i tried loading in viewdidappear (in addition viewdidload, viewwillappear, etc.) - (void)viewdidappear:(bool)animated { [super

android - Activities and fragments -

here's deal, have simple application in u user log in , view reports. basic architecture of these reports consists of header fragment display user login info, table layout hold report content , footer fragment in have created option menu report providing. now, have different activities each report , start/launch these activites onoptionsitemselected() follows: getactivity().startactivity(intent); the first report, menu , items load perfectly. when select menu item menu app stops giving following exception: 04-04 18:29:49.670: e/androidruntime(1123): java.lang.runtimeexception: unable start activity componentinfo{com.example/com.example.report2}: android.view.inflateexception: binary xml file line #10: error inflating class fragment i guessing happening because next activity contains fragments(header , footer). approach wrong? looking on net, loads of info leaves me confused @ end. appreciated! * edit : * layout xml report 1 <?xml version="1.0" enco

sql - how to query the count of records from first day to last day of the month -

i count of every day records table. example have table “employee” following fields id, empno, datehired. , have following records id empno datehired 1 000001 3/2/2013 12:00:00 2 000002 3/14/2013 12:00:00 3 000003 3/14/2013 12:00:00 4 000004 3/21/2013 12:00:00 5 000005 4/2/2013 12:00:00 6 000006 4/3/2013 12:00:00 7 000007 4/3/2013 12:00:00 8 000008 4/3/2013 12:00:00 9 000009 4/3/2013 12:00:00 10 000010 4/4/2013 12:00:00 11 000011 4/5/2013 12:00:00 12 000012 5/1/2013 12:00:00 and current month april, how can value: count day 0 4/1/2013 12:00:00 1 4/2/2013 12:00:00 4 4/3/2013 12:00:00 1 4/4/2013 12:00:00 1 4/5/2013 12:00:00 0 4/6/2013 12:00:00 0 4/7/2013 12:00:00 0 4/8/2013 12:00:00 0 4/30/2013 12:00:00 you need create calendar whole month of april in order whole dates of month. aid of using common table expression , can want. after creating calendar, join table

Autocomplete textview just show the last value which I submitted into database in Android -

i using textfield submiting names database pressing button in main activity.in activity use autocomplete textview showing names.but problem shows last name submitted.here code showing names in autocomplete textview: for (contact cn : contact) { string[] s1=new string[]{(cn.getname())}; arrayadapter<string> adapter = new arrayadapter<string>(this, android.r.layout.simple_list_item_multiple_choice,s1); a1.setthreshold(1); a1.setadapter(adapter); } try this.. arraylist<string> s1 = new arraylist<string>(); (contact cn : contact) { s1.add(cn.getname()); } arrayadapter<string> adapter = new arrayadapter<string>(this, android.r.layout.simple_list_item_multiple_choice,s1); a1.setthreshold(1); a1.setadapter(adapter);

Should I update to ruby 2 with rails 3.2.12 on heroku? -

i running rails 3.2.12 application heroku , ruby 1.9.3. should update ruby? or not ready production? latest greatest or sticking ruby 1.9.3 makes more sense. please advice. ps: using unicorn server , running approx 6-8 dynos. have done other things advised heroku' recent blog post ruby 2 current stable version of ruby. remember, can fork application (assuming toolbelt date) , test things out if you're not sure. heroku fork -a your_app new_app

c# 4.0 - Unable to print a panel in c# windows application -

hi printing panel in windows application. when click print panel opening print dialog after click print in print dailog is throwing exception. system.compoentmodel.win32exception{"access denied"} here code using. bitmap memoryimage; private void btnprint_click(object sender, eventargs e) { panel1.backcolor = color.white; printdialog1.document = printdocument1; if (printdialog1.showdialog() == dialogresult.ok) { printdocument1.print(); } } private void printdocument1_printpage(object sender, printpageeventargs e) { rectangle pagearea = e.pagebounds; e.graphics.drawimage(memoryimage, (panel1.width / 2) - (this.panel1.width / 2), this.panel1.location.y); } please let me know how solve this thanks in advance try it private void printdocument1_printpage(object sender, system.drawing.printing.printpageeventargs e) { system.drawing.bitmap memo

android - Insert imagepath dynamically -

i'm trying images in grid view using universalimageloader github . instead of loading static final image constant, want load image path dynamically server. made jsonparser load information server , parse it. i'm struggling assign images string array. please suggest me how assign. i'm newbie android. imageconstants.java import java.util.arraylist; import java.util.hashmap; import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject; import android.app.progressdialog; import android.os.asynctask; import android.util.log; public class imageconstant { public static string[] image1; private static string[] constants; public static string url = "http://ensign119.com/assets/image11.php"; // json node names protected static final string tag_products = "image_path"; protected static final string tag_cid = "file_id"; public static final string tag_name = "file_name&quo

python - Assign a dictionary value to a variable where key == list[element] -

c = d[s[0]] c new variable, d dictionary, , s list. what i'm attempting assign value of key same first element list c . know key in dictionary, , first element of list same key. how assign value of key variable? code wrote gives me out of index error. however, code: a = s[0] c = d[a] works. why doesn't first attempt work? python 2.7 on windows i have no idea why not working you. maybe list not populated after all. should work - >>> d={'world':'hunger'} >>> s=['world'] >>> d[s[0]] 'hunger' >>> c = d[s[0]] >>> c 'hunger' >>> also python dictionaries have nifty feature called has_key . checks if key present in dict or not. use prevent keyerror exceptions... consider using prevent untoward crashes.

Java comparing strings -

this question has answer here: how compare strings in java? 23 answers i have small of problem. have string lists same size , string compare. meaning want compare string first list index of compared string in list , string other list on index. private string getstringonindex(list<string> list1, list<string> list2,string elem) { string elem2; (int = 0; i<list1.size();i++) { if(list1.get(i).equals(elem)){ elem2 = list2.get(i); return elem2; } else { return "nope"; } } } is wrong compare 2 strings that. or should use operator ==. know style string lists not nice temporary solution. thx :) to answer specific question on "string comparison", doing correct. string content comparison should done using equal

java - ActionBarSherlock fragment showing different data than passed -

Image
hello , thank trying help! i'm trying build app actionbarsherlcok. when click tabs, same fragment instantiate dynamic data based on tab clicked. reason it keeps showing me wrong data , though correct parameter value passed (i verified using breakpoints , watches). i've read simpleonpagechangelistener, getcurrentitem , of course fragments tutorial . relied on swipeytabs example create this, , built short demo show problem here: this mainactivity.java package il.co.gilead.testdynamicfragments; import com.actionbarsherlock.app.actionbar; import com.actionbarsherlock.app.sherlockfragmentactivity; import android.os.bundle; import android.support.v4.view.viewpager; public class mainactivity extends sherlockfragmentactivity { public static viewpager mviewpager; private tabsadapter mtabsadapter; integer intnumofpages = 3; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mviewpager =

ocaml - stop reading file when marker is reached -

i have following code, basics of i'm trying do: let ic = open_in "file.txt" in try while true let line = input_line ic in print_endline line done end_of_file -> close_in ic what want read file in string appending each line until reach word "stop_here" tried few ways of own , got totally messed up.. on windows os. thanks help inside while loop, add test if line = "stop_here" raise end_of_file ? refine if want stop on line contains marker.

jsf 2 - EL evaluation in a JSF page is not sequential -

i have xhtml ui:composition tag loading on ajax. using jquery ajax load url of xhtml. in loaded page, have el expression , after including source has few more el expressions. invariably, el expressions of included source being evaluated earlier 1 appearing before it. some.xhtml <ui:composition ... #{relationshipaction.followmember(param['relatetoprofile'])} <ui:include src="someother.xhtml"> <ui:param name="profileuri" value="#{param['relatetoprofile']}" /> <ui:param name="qualifier" value="#{param['qualifier']}" /> <ui:param name="cellstyleclass" value="#{param['cellstyle']}" /> </ui:include> here, expect #{relationshipaction.followmember(param['relatetoprofile'])} evaluated before el in included someother.xhtml. it's els in someother.xhtml evaluated first. any idea going wrong? th

javascript - canvas todataurl corrupted images -

i have app allow users sign document, drawing sign in canvas. function initialize(xsize, ysize) { // references canvas element 2d drawing context sigcanvas = document.getelementbyid("canvassignature"); sigcanvas.width = xsize; sigcanvas.height = ysize; var context = sigcanvas.getcontext("2d"); context.strokestyle = 'black'; // defined on touch device such ipad or android, etc. var is_touch_device = 'ontouchstart' in document.documentelement; if (is_touch_device) { // create drawer tracks touch movements var drawer = { isdrawing: false, touchstart: function (coors) { context.beginpath(); context.moveto(coors.x, coors.y); this.isdrawing = true; }, touchmove: function (coors) { if (this.isdrawing) {

windows - Can I mix C and C++ exports in a single DLL header? -

help me out here, because i'm half convinced can't want , half convinced there should suitable workaround. i have dll that's implemented in c++ , exports classes other c++ modules link it. that's fine. want link dll c module (another dll), provide "flattened" c interface , handle c++ stuff internally. that's fine. the problem want supply c or c++ clients single .h , associated .lib. have similar following in dll: #ifdef dll_exports #define dll_api __declspec(dllexport) #else #define dll_api __declspec(dllimport) #endif // export class c++ clients class dll_api cexportedclass { public: cexportedclass(); // etc. etc. }; // export flattened c interface non-c++ clients #ifdef __cplusplus extern "c" { #endif dll_api void dosomethinginternally(); // i.e. implementation uses cexportedclass #ifdef __cplusplus } #endif of course, works fine when imported c++ module, fails compile when imported c module because doesn't recogni

ios - Horizontal expandable uiscrollview or uitableview? -

Image
i want create expandable uiscrollview images shown above. i've tried search keywords cannot find example similar want achieve. i wonder if should use uiscrollview or uitableview ? any advice appreciated. thank in advance. you can create uitableview rotate 90 degrees counter clock wise , work charm. just create uitableview subclass (i.r. horizontaluitableview) , in initwithframe, rotate view 90 degrees: - (id)initwithframe:(cgrect)frame { self = [super initwithframe:frame]; if (self) { // initialization code self.transform = cgaffinetransformmakerotation(-m_pi/2.0); self.showsverticalscrollindicator = no; } return self; } you need subclass uitableviewcell's , rotate them 90 degrees too

WCF - call method from service implementation -

what i'm trying following: 1) have following wcf service contract: [servicecontract] public interface iuploadservice { [operationcontract] servicedata upload(request request); } [datacontract] public class request { [datamember] public long abnnumber; [datamember] public string email; } 2) contract implemented this. public class uploadservice : iuploadservice { public bool upload(request request) { // code } } in "some code" section call validation class validate clients request, this: var result = validation.validaterequest(request); so question is: bad idea create instance of validation class inside upload method? this: public class uploadservice : iuploadservice { public bool upload(request request) { var validation = new validation(); var result = validation.validaterequest(request); } } i know can around creating constructor far know can't create constructor inside wcf

ruby on rails - How to get the value of include with conditions? -

i have 3 table shop, item , item_type the shop contains names of shops , item contains items of each shop , item_type contains different types of items along status such available or not available. now want render format.json { render json: {:shop => @shops.as_json(:include => :items)}} but based on condition, items item_type_id='1' , status of item_type_status='available' try this: @shops = shop.includes(:items).where("items.itemp_type = ?", 'accesories') format.json { render json: { :shop => @shops.as_json(:include => :items) } } edited: one way create hash objects want render, , pass render method. so: respond_to |format| format.json { render :json => {:shops => @shops, :items => @items }} end if models aren't associated through active record, that's best solution. if association exist, can pass :include argument render call, so: respond_to |format|

ant - echoproperties task depending on log level -

is there chance make echoproperties task depend on log level (something similar level parameter in echo task)? helpful have echoproperties outputs when ant runs in debug mode (-debug). alternative: how can detect in ant current log level? there e property contains log level? thx! frank consider using ant record task use case. see how capture output of antcall inside of ant? .

Can't run MSTest unit tests via Resharper after upgrading to VS 2012 Update 2 -

all tests in pending state. can not run or debug them. see others experienced same issue: http://youtrack.jetbrains.com/issue/rsrp-339546 jetbrains on case already: we releasing update resharper 7 fix issue test runner , visual studio update pack 2. — jetbrains resharper (@resharper) april 5, 2013

PHP list to an Array to a foreach Joomla Module -

i have following php, needs take list of article ids , run through function them database. i beginner in php far have: list($slide1, $slide2, $slide3, $slide4, $slide5) = explode(" ", $params->get('id')); $a = array( $item => $slide1, "two" => $slide2, // "three" => $slide3, // "four" => $slide4, // "five" => $slide5 ); foreach ($a $k) { $args['id'] = $k; $item = modarticleslider::getarticles($args); } and class: class modarticleslider { public function getarticles($args){ $db = &jfactory::getdbo(); $item = ""; $id = $args['id']; if($id > 0){ $query = "select * "; $query .= "from #__content id =".$id." , state=1 " ; //echo $query; $db->setquery($query); $item = $db->loadobject(); } return $

java - Selenium takes lots of time to get dynamic page of given URL -

i doing project in java . in project have work dom. first load dynamic page of given url, using selenium. parse them using jsoup. i want dynamic page source code of given url code snapshot: public static void main(string[] args) throws ioexception { // selenium webdriver driver = new firefoxdriver(); driver.get("any url here"); string html_content = driver.getpagesource(); driver.close(); // jsoup makes dom here parsing html content document doc = jsoup.parse(html_content); // operations using dom tree } but problem is, selenium takes around 95% of whole processing time, undesirable. selenium first opens firefox, loads given page, gets dynamic page source code. can tell me how can reduce time taken selenium, replacing tool efficient tool. other advice welcome. edit no. 1 there code given on link . firefoxprofile profile = new firefoxprofile(); profile.setpreference("general.useragent.override", "

jquery - HTML5 Canvas add id or class -

i'm drawing on canvas. example: '1.01': { color: 'pink', points: [563,69,630,69,630,149,563,149] }, where 1.01 text displayed in tooltip when hover on it. points x , y coordinates create block on canvas. possible give drawn block id or class can handle in jquery? how store in own object , hold collection of these objects later use? although i'm not sure mean "handle in jquery" because on canvas, you're simple filling pixel areas, different when working dom. var block = function (color, points) { return { color: color, points: points }; }; var b1 = block('pink', [563,69,630,69,630,149,563,149]); // whatever need it... and replace code following keep same reference: '1.01': b1,

vb.net - How to hide vb form on startup? -

i trying hide main form on startup, reason failed that. in following code have created button hides form, want hide form on load. please me out. in advance. option strict on public class form1 private declare function getasynckeystate lib "user32" (byval vkey long) integer private sub timerkeys_tick(byval sender system.object, byval e system.eventargs) handles timerkeys.tick dim result integer dim key string dim integer = 2 90 result = 0 result = getasynckeystate(i) if result = -32767 tblog.text = tblog.text + chr(i) if = 13 key = vbnewline exit end if next if key <> nothing if my.computer.keyboard.shiftkeydown orelse my.computer.keyboard.capslock tblog.text = key else tblog.text = key.tolower end if end if if my.computer.keyb

mongodb - Can we move the document dynamically across shards in mongo db? -

i building tracking platform has following use cases. need track 50,000 vehicles each vehicle relays location every 60 secs. get api returns vehicles in x km range. so, need scale writes , achieve query isolation. can create shard cluster geographical region shard key(geohash). me balance writes , achieve query isolation. happens when vehicle moves across regions mangodb automatically move document new shard in case? you cannot change shard key fields record once written. using region shard key prevent moving across regions unless delete record in original region , insert using new one. on choosing shard key, 1 matches common query pattern. querying on shard key allow retrieve record directly shard. queries don't use shard key have perform scatter gather query against shards. if on or can use mongodb 2.4, , don't need perform range based queries, may want consider using hashed shard key allow distribution, if shard key monotonically increasing. see th

c++ - How to check/detect an 'if' clause without curly braces? -

in c/c++ code project, find if/else sentences not using curly braces. there compiler check or utility find them? the main problem want redefine debug macros avoid traces evaluation in conditions (does know other solution?). , need find them avoid “dangling-else problem” , pointed out in "if" block without curly braces makes subsequent "else if" nested code pieces: before modification: debug get_debug_dst(debug_level_debug).nospace() << debug_prefix << __pretty_function__ now use if without braces inside: debug if (getdebugmode(debug_level_debug)) get_debug_dst(debug_level_debug).nospace() << debug_prefix << __pretty_function__ example of problematic code: if (my condition) debug << "hi there"; else {some more code;} just invert logic, , put active part in else branch: #define debug if( !getdebugmode( debug_level_debug ) ) \ ;