Posts

Showing posts from August, 2012

javascript - DOJO - Query XmlStore using XPath -

i have dojox.data.xmlstore , want query xml store using xpath. there way ? example below represent query attribute, want use xpath query provided item element. var store = new dojox.data.xmlstore({url: "books.xml", rootitem: "book"}); var gotbooks = function(items, request){ for(var = 0; < items.length; i++){ var item = items[i]; console.log("located book: " + store.getvalue(item, "title"); } } var request = store.fetch({query: {isbn:"a9b57*"}, oncomplete: gotbooks}); for example if have dojo dijit.tree element, support onclick event, want able fetch content of selected element. item element has field called "query" represent xpath query item itself. how can use xpath query fecth data store ? var tree = new tree({ model: mymodel, onclick: function(item){ //the item parameter has field called "query" represent xpath query item itself. } }); if i'm using "query

Moving second row after fourth using awk -

i have task output of: ps auxfwww | sort -k2n | head -n4 then have rearrange it, using awk, result 1st,3rd,11th column of rows 2,3,4. rows must in order 3,4,2. closest this: ps auxfwww | sort -k2n | head -n4 | awk 'nr>=3' | awk '{print $1, $3, $11}' but have no idea how row 2 after rows 3 , 4. it has done single line command. please shed light :) ps auxfwww | sort -k2n | head -n4 | awk '{ a[i++] = $1" "$3" "$11 } end { print a[2]; print a[3]; print a[1] }' this prints row 3, row 4, followed row 2.

html - How to bring an image appear on an image on-hover using sprites -

Image
i trying make line appear(say 10px) after hovering mouse on image @ bottom of image i saw on mtv's website in "you these" section below every post.they use css-background sprites that. i going mad after repeated failed attempts recreate.everythings works,except main onhover line coming up. code far css .yel_strip{background-position:-280px -495px; width:165px; margin:-8px 0 0 0; height:5px; position:absolute; display:none; z-index:1;} .yel_strip:hover{ background:url(http://mtv.in.com/images/sprite_v1.png) no-repeat;} html <div class="moviel hover_thumb"> <div><a href=""><img width="165" height="93" alt="" src=""/></a> <div class="yel_strip"></div> </div> </div> any appreciated.thanks i've made working fiddle no not needed markup in html: http://jsfiddle.net/pjmpw/3/ your html: <a href="#" class=&q

database - can't login to any account in mysql -

i installed mysql on mac , can't seem access accounts there. i used commands : shell> mysql -u root -p password: and since have not given 1 let go blank , error saying incorrect password. i can login using shell> mysql buy can't seem able change passwords or @ accounts in mysql.users. i following error: error 1142 (42000): select command denied user ''@'localhost' table 'users' what do resolve issue , how use software sequel pro database? your problem seems, dont have privileges localhost@root, privileges run below command. mysql> grant privileges on *.* root@localhost identified 'password' grant option in mysql command prompt , have previleges access localhost root. use command set password mysql mysqladmin -u root password “newpassword”; example mysqladmin -u root password adhfhuef34; you want restart database server after running command sudo /etc/init.d/mysql restart if dint work, tr

javascript - how to make a div appear on hover and disappear on hover out? -

hi first of code - <script> function slide() { if(document.getelementbyid('eiv').classname == 'deactive') { document.getelementbyid('eiv' ).classname = 'active'; document.getelementbyid('eiv').style.webkittransition ='all 0.5s'; } else { document.getelementbyid("eiv").classname = 'deactive'; document.getelementbyid('eiv').style.webkittransition ='all 0.5s'; } } function slideout() { if(document.getelementbyid('eiv').classname == 'active') { document.getelementbyid('eiv' ).classname = 'deactive'; document.getelementbyid('eiv').style.webkittransition ='all 0.5s'; } else { document.getelementbyid("eiv").classname = 'active'; document.getelementbyid('eiv').style.webkittransition ='all 0.5s'; } } </script> <body> <sp

javascript - Getting random number from php file using ajax wont update with new result -

i mucking around thought might simple thing do, generate random numbers using jquery ajax. have index.php polls generator.php random number , code follows index.php : <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript"> setinterval(function(){ $.ajax({ url:'./generator.php', cache : false, success: function(data){ document.write(data.foo); }, datatype: "json"}); }, 3000); </script> generator.php : <?php $x = rand(10,100); $array = array( 'foo' => $x ); echo json_encode($array); ?> so works fine on first load, gets random number generator.php after index.php continues load gets nothing @ , number displayed stays same. doing wrong here? i think problem document.write(data.foo); . replace with: document.getelementbyid('anid').innerhtml = data.foo; and add element id of "anid" in html

c# - implement draggable ui like blockly -

i'm developing application allow user program scripts. i've developed "compiler" analyse script made user, want create visual editor possibilities user have, similar this: blockly - visual programming editor . i using c# , wpf , have no idea how develop above. thought doing script editor in xna, since xna better graphics don't know how. thanks you can wpf. using drag , drop can real closer. watching this video sense hou mechanism works. try improving , playing it. 2nd step play lists , drag , drop like shown here . improve more using data mouse position, way demonstrated here .

c++ - How to calculate floating-point precision after round-off errors in +, -, *, and /? -

for purpose of verification, able calculate reasonably tight upper bound on accumulated error due rounding representable values during specific arithmetic computation. assume have function foo() claims perform specific arithmetic computation. assume there implied guarantee maximum error (due rounding) stemming involved type being either float or double , implied (or stated) way in foo() caries out computation. i able verify result foo() specific set of input values carrying out computation in fashion keeps tracks accumulated worst-case error, , check if 2 results close final worst-case error demands. i imagine possible introducing new arithmetic class track_prec<t> adds precision tracking 1 of fundamental floating-point types, , let implementation of arithmetic operators of class calculate worst-case errors of each subexpression. problem don't know how compute these worst-case errors in these general cases: // t = float or double template<class t> clas

haskell - Anonymous Type Functions -

this followup previous question: type-level map datakinds , starting 2 answers received. my goal take hlist of arbitrary types , turn list of related/derived types type family typemap (a :: * -> *) (xs :: [*]) :: [*] type instance typemap t '[] = '[] type instance typemap t (x ': xs) = t x ': typemap t xs data hlist :: [*] -> * hnil :: hlist '[] hcons :: -> hlist -> hlist (a ': as) when tried few types, ran problem. type-function " argument typemap has take hlist element type last argument , return new type. works okay sometimes: test :: hlist rqs -> hlist (typemap ((,) int) rqs) test hnil = hnil test (hcons x xs) = hcons (3,x) $ test xs but if wanted switch order of tuple in definition of test? first attempt define type synonym: type revinttup b = (b,int) test2 :: hlist rqs -> hlist (typemap revinttup rqs) test2 hnil = hnil test2 (hcons x xs) = hcons (x,3) $ test2 xs but of course, you can't

cakephp edit posts doesnt do what it should do -

i want edit posts, when acess http://... /posts/edit/2 shows flash message post has been updated, whats wrong ? doesnt show edit form... function edit($id = null) { $this->post->id = $id; if($this->request->is('post')){ $this->request->data = $this->post->read(); }else { if($this->post->save($this->request->data)){ $this->session->setflash('the post has been updated'); $this->redirect(array('action'=>'index')); } } } my edit page <h2>edit post</h2> <?php echo $this->form->create('post',array('action'=>'edit')); echo $this->form->input('title'); echo $this->form->input('body'); echo $this->form->input('id', array('type'=>'hidden')); echo $this->form->end('edit post'); ?> your if() condition wrong :

java - Get value from HashMap using JSTL and variable as an argument -

i have hashmap , trying value it, using variable argument. here code <c:foreach var="t" items="${usertasks}"> <tr> <td>${t.task}</td> <td><${t.deadline}</td> <td>${difficultymap[${t.difficulty}]}</td> <td>${t.done}</td> </tr> </c:foreach> difficultymap - hashmap, t.difficulty - integer value. error pwc6038: "${difficultymap[${t.difficulty}" contains invalid expression(s): javax.el.elexception: error parsing: ${difficultymap[${t.difficulty} ${difficultymap[1]} works ok, need use variable argument, possible? get rid of nested ${} . this: <td>${difficultymap[t.difficulty]}</td> el expressions delimited using leading dollar sign ( $ ) , both leading , trailing braces {} . since you're working within expression, don't have create el expression access variable.

c# - How do I Trim All incoming Json object fields in MVC WEB API? -

what i'm trying achieve trim incoming object properties of type string in mvc web api project. i thought model binder should solution, it's not being hit, if try set custom model binder instead of modelbinders.binders.defaultbinder .. the json example {"name": " test name ", "number": 15} for example - if specify modelbinder explicitly, works.. [modelbinder(typeof(mycustombinder))] public class testobject { public string name { get; set; } public int number { get; set; } } the controller ... public class testcontroller : apicontroller { // post api/test public void post([modelbinder(typeof(mycustombinder))]testobject value) { } and registration modelbinders.binders.add(new keyvaluepair<type, imodelbinder>(typeof(testobject), new mycustombinder())); but want find more generalized approach, wouldn't need decorate each , every model class in project i believ

EGL guide for beginners -

i'd egl. however, "only" i've been able find api reference. searching "egl guide", "egl tutorial" or "egl beginners" hasn't succeeded. know of resource? egl may not "library beginners". in case, guess should start beginning - but, what's beginning? read egl abstraction layer on system-dependent drawing apis, being "correct" way go. wayland uses it, , kmscon. looking source code, though, has given me headache. p.s.: side note, feel more comfortable c++ (although guess that, if works on c, should work on c++). also, i'm using latest kernel, latest mesa release, guess there's support available egl. to begin learning egl, recommend following resources. the opengl es 3.0 programming guide addison-wesley provides tutorial on using egl opengl es, complete example code on github. book's text provides introduction parts of egl independent of operating system. cover operating system spec

javascript - How to change href link of button used with dropdown menu? -

i trying create drop down menu button. my code - <div class="dropdown-plans"> <select id="basic_plan" name="bill_cycle"> <option value="tri"> 3 years - rs. 100/month </option> <option value="bi"> 2 years - rs. 200/month </option> <option value="ann"> 1 year - rs. 100/month </option> </select> </div> <div class="button-plans"> <a href="somelink"> order </a> </div> depending on option select dropdown, href value "somelink" should change. instance if select 1 year. href value should change "somelink" "google.com" update: i searched 2 things. 1) changing href using javascript , 2) using onchange select tag. lead me create following piece of code. <script> function getopt(period) { if (period.value = "tri") { document.getelementbyid("abc").href="t

java - BufferedReader readLine detect closed socket and use .ready() -

server snippet: reader = new bufferedreader(new inputstreamreader(new bufferedinputstream(connection.getinputstream()))); if (reader.ready()) { result = reader.readline(); if (result == null) { quit(); // handle closing socket } else { // process result } } client snippet: bufferedoutputstream os = new bufferedoutputstream(connection.getoutputstream()); outputstreamwriter osw = new outputstreamwriter(os, "us-ascii"); osw.write("hello\n"); osw.flush(); the problem: when client writes server gets read correctly when client closes it's socket (for example force quitting program), reader.readline() should output null , because of if (reader.ready()) { null result never reach quit() . if leave away if (reader.ready()) { , server can't read data. how fix this? edit: can't use while ((result = reader.readline()) != null) { because need run more code after this: while (running) { try { reader = new b

android - OpenGL crashes when linking program, LG Nexus 4 -

i'm having opengl es driver error. time i'm trying compile following lines: precision mediump float; varying highp vec2 texturecoordinate; void main() { highp vec4 color = texture2d(input0, texturecoordinate); vec3 color3 = color.rgb; vec2 tc = (2.0 * texturecoordinate) - 1.0; float d = dot(tc, tc); vec2 lookup = vec2(d, color3.r); .. .. } but i'm getting after line: gles20.gllinkprogram(program); native crash : "fatal signal 11(sigdev) @ 0x00000060(code = 1), thread 1231 " i'm guessing happens because lg nexus 4 uses gpu adreno, , crashes me error code 14 on different crash - using many macros. after compile shader, using glgetshaderiv status of shader compilation. like: glint compiled; glgetshaderiv(index, gl_compile_status, &compiled); //index shader value then, if compiled returned zero, info length first, , error message follows: glint infolen = 0; glgetshaderiv(index, gl_info_log_length, &infolen); if(i

Google Drive SDK Public Download Link -

i have xlsx file on google drive. link can found here: https://docs.google.com/spreadsheet/ccc?key=0aojyuivne85odedsdetvqvbuu254atbtekw3lvvoc0e&usp=drive_web#gid=0 i know how download link through google drive sdk, link works if user logged google account. see link below: https://docs.google.com/feeds/download/spreadsheets/export?key=0aojyuivne85odedsdetvqvbuu254atbtekw3lvvoc0e&exportformat=xlsx i have setup viewing options public. however, how can public download link file? way have found download file , copy download link. download link can seen below: https://docs.google.com/spreadsheet/fm?id=tgltkuapnsnxi0mzl7-unsa.pref_12709722546300286642.234580469124820854&fmcmd=420 there not seem correlation between id provided in url of document , id of download link of document. there no other way public download link? you can get https://googledrive.com/host/<file_id> download public files no auth. not going work files no downloadlink (such docs ,

Unexpected Behaviour with WPF Datagrid Grouping with DateTimePicker control -

inside window, have simple datagrid control datetimepicker column, , textbox column. group rows inside datagrid month-year string derived datetimepicker. here xaml columns , grouping..... <datagridtemplatecolumn header="date" width="100"> <datagridtemplatecolumn.celltemplate> <datatemplate> <xctk:datetimepicker isenabled="true" format="custom" formatstring="m/d/yyyy h:mm" value="{binding thedate, updatesourcetrigger=propertychanged, mode=twoway}"/> </datatemplate> </datagridtemplatecolumn.celltemplate> </datagridtemplatecolumn> <datagridtemplatecolumn header="text" width="150"> <datagridtemplatecolumn.celltemplate> <datatemplate> <textbox textwrap

php - User uploads folder structure -

can folder structure user uploads have impact on performance site grows? for instance, considered structure storing photos/albums: public folder - uploads -- users --- user id ---- album id - contains photos in album thanks in advance! can folder structure user uploads have impact on performance site grows? yes can. if store many files in single directory may slow down operations. posted structure good. edit maybe fast above answer , there's missing explanations, below extend it: if expect have tens of thousands images users, should consider solution: create table in database , put information every single photo in it. create photo filename record id md5 hash. database table example: +-----------------------------------------------------------------+ | id filename ext created_at user_id | +-----------------------------------------------------------------+ | 1 c4ca4238a0b923820dcc509a6f75849b jpg 1381127206 1

Android + mysql + node.js + html + javascript - is it possible? -

is possible have html + javascript web frontend, node.js + mysql backend, store images mysql database , have android application download images , save them phone? if possible, need tools listed before? yes, possible. these elements can communicate using http requests. example, node.js/mysql backend generate html/js frontend usable in web browsers, while android app utilize json api, published node.js/mysql backend. no additional tools (languages, libraries) should required, unless application requires specific libraries (voice recognition, example).

java - Persist data in local storage google app engine with Junit + eclipse -

my setup: win 7 , eclipse , gae sdk 1.8.5 ,objectify 4 , junit4 i trying write junit test cases save 2 car entities , retrieve them. using objectify , works fine. my problem need persist entities across many runs of test cases, means once save using dosavecar() in 1 run , in next run , should 2 entities when run dolistcar(). how persist local storage across various junit test runs in eclipse environment ? import org.junit.after; import org.junit.before; import org.junit.test; import com.google.appengine.tools.development.testing.localdatastoreservicetestconfig; import com.google.appengine.tools.development.testing.localmemcacheservicetestconfig; import com.google.appengine.tools.development.testing.localservicetesthelper; public class ofytest { private final localservicetesthelper helper = new localservicetesthelper( new localdatastoreservicetestconfig(), new localmemcacheservicetestconfig()); @before public void setup() {

facebook - How to get mutual groups of two users using FQL? -

i want that: select gid group_member uid=<uida> , gid in (select gid group_member uid=<uidb>) this should give me mutual groups uida , uidb. problem is, i'm using access_token of uida run query, therefore inner select empty. there's way provide 2 access tokens? there no such thing - 2 access tokens. can ask more permissions , access_token allow access more facebook data depends on permissions have. in case, need ask 2 permissions: user_groups friends_groups then, build access_token , fql query built work you. you can find needed permissions here: https://developers.facebook.com/docs/reference/fql/group_member

java - Check time every 5 minutes and compare it to button's time - Android -

i have class called eventbutton extends button. all of button's settings in class, onclick() etc. i have home activity has scrollview the eventbuttons added home activity's scroll view when user presses menu button. don't instantiate object call new eventbutton() when user clicks on button dialog displayed , user set's name of "event" , time of "event". the name , time displayed on button inside scollview on home activity. my question is, how go refreshing eventbutton every, say, 5 minutes check if time set on has passed. have tried timertask , timer , handler neither seem work. timertask kept crashing, found out it's better use handler in android. private void scheduledelay() { eventbutton.this.postdelayed(new runnable() { @override public void run() { // todo auto-generated method stub int mhour = calendar.get(calendar.hour_of_day); int mminute = calendar.get(calend

class - PHP difference when instantiating a new object? -

this question has answer here: php class instantiation. use or not use parentheses? 2 answers i have seen in many websites showing examples of instantiating objects. $obj = new foo; which straight forward, have seen this: $obj = new foo(); is there difference? far noticed both same. there no difference, matter of opinion. if foo had constructor parameters need use new foo($param);

Using "and" and "or" operator with Python strings -

i don't understand meaning of line: parameter , (" " + parameter) or "" where parameter string why 1 want use and , or operator, in general, python strings? suppose using value of parameter , if value none , rather have empty string "" instead of none . in general? if parameter: # use parameter (well expression using `" " + parameter` in case else: # use "" this expression doing. first should understand and , or operator does: a , b returns b if true , else returns a . a or b returns a if true , else returns b . so, expression: parameter , (" " + parameter) or "" which equivalent to: (parameter , (" " + parameter)) or "" # a1 a2 b # or b how expression evaluated if: parameter - a1 evaluated true : result = (true , " " + parameter) or "" result = (&q

Showing a man page in C++ -

i created man page c++ application , show user when particular flag specified in command line. system("man myapplication") way this, or there better options? i'd take nroff (text) output of man , stick either in code 1 huge string or in separate file depending on how many pieces program installs with. calling system("man") requires lot of dependencies last thing unfortunate user wants deal after typing my_program --long-help . work fine in many cases, when didn't you'd lose important feature of program , have report rather silly "sorry: no long available". this increase portability systems never had man program.

css3 - Is it possible to cut out a triangle section from a div using CSS? -

Image
is possible cut triangle <div> in picture below? the background not colour, in case blurred picture, can’t cover green <div> brown triangle image. there other css way achieve effect? thanks. the illusion of possible: http://jsfiddle.net/2hcrw/4/ tested with: ie 9, 10, firefox, chrome, safari on pc , ipad. ::before , ::after pseudo elements skewed provide side of triangle each. wrapper used clipping skewed pseudo elements. may able avoid using outer container wrapper. elements can still styled borders, shadows, etc. anything underneath show through properly. demo borders , drop shadow: http://jsfiddle.net/2hcrw/8/ this demo adds tweak ipad retina prevent gap between element , pseudo elements (either caused drop shadow bleed or sub-pixel rendering behavior). <div id="wrapper"> <div id="test">test</div> </div> #wrapper { overflow: hidden; height: 116px; } #test { height: 100px;

loops - Thread.sleep(); in Java -

whenever use thread.sleep(); in while loop, hints tell me, "invoking thread.sleep in loop can cause performance problems." have heard many other websites , books. can use instead? here's code: import javax.swing.*; public class delay { public static void main(string[] args) throws exception { int difficulty; difficulty = integer.parseint(joptionpane .showinputdialog("how you?\n" + "1 = evil genius...\n" + "10 = evil, not genius")); boolean cont; { cont = false; system.out.println("12"); thread.sleep(500); string again = joptionpane.showinputdialog("play again?"); if (again.equals("yes")) cont = true; } while (cont); } } try java.util.timer and/or javax.swing.timer. play them bit, set initial delay, repetition period, etc. see suits

Overloading addition operator with many objects c++ -

i need overload addition operator of multiple different objects , return 'cluster object: "overload addition operator(+) add combination of instances desktops, laptops, , clusters. operator should return object of type cluster" if had desktop1+laptop1+laptop2; need return cluster adds of ram, , other variables of each object. adding variables of objects inherit computer class. here code of rest of project. thanks! #include <iostream> using namespace std; class computer { public: double ram; double cpuspeed; int numberofcores; double hddsize; virtual void print(); }; class desktop : public computer { public: bool hasmonitor; double monitorsize; friend istream& operator>> (istream &in, desktop &mydesktop); }; class laptop : public computer { public: double screensize; }; class cluster : public computer { public: int numofcomp; }; desktop::deskt

email - Parsing "From:" field of an e-mail message in Python -

i trying parse rfc 5322 compliant "from: " field in e-mail message 2 parts: display-name, , e-mail address, in python 2.7 (the display-name empty). familiar example john smith <jsmith@example.org> in above, john smith display-name , jsmith@example.org email address. following valid "from: " field: "unusual" <"very.(),:;<>[]\".very.\"very@\\ \"very\".unusual"@strange.example.com> in example, return value display-name "unusual" and "very.(),:;<>[]\".very.\"very@\\ \"very\".unusual"@strange.example.com is email address. you can use grammars parse in perl (as explained in these questions: using regular expression validate email address , the recognizing power of “modern” regexes ), i'd in python 2.7. have tried using email.parser module in python, module seems able separate fields distinguished colon. so, if like from email.parser impor

html - CSS styling table of contents, annoying little details, avoiding kludge -

Image
i'm trying recreate table of contents in css. i've gotten here before, results still incorrect, , involve lot of kludging. here image comparing original table of contents attempt @ recreating it. as can see, there still problem: "a review of principal questions in morals" wraps after "in" instead of after "questions". here css: .list li { position:relative; overflow:hidden; width:360px; } .list li:after { font-size:120%; content:"..............."; text-indent:1px; display:block; letter-spacing:40px; position:absolute; left:1em; bottom:0px; z-index:-1; font-weight:bold; } .list li span { display:inline; max-width:100px; background-color:#fff; padding-right:12px; } .list li .number { float:right; font-weight:bold; padding-left:15px; } .two-lines { text-indent:-.9em; } .list .two-lines:after { text-indent: 1px; } .two-lines .number { botto

c++ - How do I read an array of structs from a file and sort it? -

preface: guidelines set professor, must use array, not other data structure. psuedo code (which isn't concise) of method should following: name , grade read temporary location loop end of filled part of array down beginning { if (new last name < current last name) { copy current name , grade down } else if (new/current last names equal , new first name < current first name) { copy/assign current name , grade down } else { found right place, break out of loop } } you've made room, insert (copy) new name correct sorted position i see i'm breaking array bounds attempting read array position [-1] can't think of way avoid since i'm counting backwards number of items have , have compare them. i'm reading lines text file , storing pieces of each line struct. i'm using insertion-sort-esque algorithm store structs in alphabetical order. however, array not seem populate past first couple lines new lines overwriting previous lines... it's i

php - input type="file" - temp files deleted with post-redirect-get -

i have form allow user upload files. changed post processing post-redirect-get since user enters other information well. noticed global $_file visible redirect.php lost after redirecting input form. attempted save $_file array, appears temp files removed post-redirect-get. there way tell server preserve temp files when leaving redirect.php can process them when see fit? in advance. user form: <input type="file" name="file[]" id="userfiles" size='1px' multiple onchange="makefilelist();" /> redirect file: if (isset($_files)){ $_session['post-files'] = $_files; } header("location: /back/to/input/form.php"); you might able pass encoded copy of file(s) session. something like... $tempimages = array(); foreach($_files $file) { $tempimages[] = base64_encode(file_get_contents($file['tmp_name'])); } $_session['post-files'] = serialize($tempimages);

c++ - Slight undesired transparency from FillRectangle -

i have window created ws_ex_layered window style. drawing onto memory bitmap using gdi+, , using updatelayeredwindow update graphical content of layered window. here's snippet of code: void redraw(hwnd hwnd, int width, int height) { static bool floppy = true; floppy = !floppy; hdc hscreendc = getdc(hwnd_desktop); hdc hmemdc = createcompatibledc(hscreendc); hbitmap hbmp = createcompatiblebitmap(hscreendc, width, height); hgdiobj hobj = selectobject(hmemdc, hbmp); graphics gfx(hmemdc); solidbrush b(color(254, (floppy ? 255 : 0), (floppy ? 0 : 255), 0)); gfx.fillrectangle(&b, rect(0, 0, width, height)); blendfunction blend; blend.blendop = ac_src_over; blend.blendflags = 0; blend.sourceconstantalpha = 255; blend.alphaformat = ac_src_alpha; point src = { 0, 0 }; size size; size.cx = width; size.cy = height; assert(updatelayeredwindow( hwnd, hscreendc, null,

python - sampling pandas dataframe by different frequencies -

i have multi-index series/dataframe id , timestamp key. data structure has daily data various ids. can use resample function @ end of month snapshot of data structure ? id ts value 1 2001-01-30 1 2001-01-31 2 2001-02-01 3 2 2001-01-30 3 2001-01-31 2 2001-02-01 4 i want output id ts value 1 2001-01-31 2 2 2001-01-31 2 can use resample function call me out? know can create end of month date list , loop through dates , find values. want use full functionality of pandas. why need resample? set index ts , slice, so: from cstringio import stringio raw = """id ts value 1 2001-01-30 1 1 2001-01-31 2 1 2001-02-01 3 2 2001-01-30 3 2 2001-01-31 2 2 2001-02-01 4""" sio = stringio(raw) df = read_csv(sio, sep=r'\s+', header=0, parse_dates=[1]) df.set_index('ts', inplace=true) slice , reset index: print df['2001-01-31'].reset_index().set_index(&

php - mySQL SELECT AS for multiple criteria -

i need combine these 2 queries 1: select user1id friendid friends user2id = '$userid' union select user2id friendid friends user1id = '$userid' then select firstname, lastname users id = friendid (that established) i guess mysql's union ( manual ) keyword looking for. edit due edited question: you need subquery trying (a join might work, more complicated): select firstname, lastname users id in ( select user1id friendid friends user2id = '$userid' union select user2id friendid friends user1id = '$userid' ) note subqueries can cause performance issues in large tables and/or complicated queries. may want refactor subquery join in case.

android - Unresolved dependency error when creating a new project -

Image
this error appears when creating new android application module in android studio using fixed tabs + swipes navigation. it says: the following dependencies not resolvable. see build.gradle file details. - com.android.support:appcompat-v7:18.0.0 i'm targeting android 4.0+ devices. why compatibility library involved? one workaround install library using android sdk manager, i'm concerned app use compatibility library when there no reason to. actionbar , fixed tab navigation should built-in android 4.0+ framework right? this happened me intellij idea 13 ultimate when creating new gradle module. working on app supports froyo. had manually add support libraries sdk. after able build fine. here screenshot of project structure settings sdk have: as can see, support v4, v7 , v13 added manually. associated android api 19 platform (in case). when create next new gradle module, still need go project structure select sdk under project, not need add support

delphi - Is this the correct way to return an empty generic value? -

i have hashtable , need way return not_found result. type tcell<t> = record ..... property key: cardinal read fkey write fkey; property data: t read fdata write fdata; end; thashtable<t> = class(tenumerable<t>) private fcells: array of tcell<t>; fempty: t; ... constructor create(initialsize: cardinal); overload; function lookup(key: cardinal): t; ... end; constructor thashtable<t>.create(initialsize: cardinal); begin inherited create; // initialize regular cells farraysize:= initialsize; assert((farraysize , (farraysize - 1)) = 0); // must power of 2 setlength(fcells, farraysize); fillchar(fempty, sizeof(fempty), #0); //superfluous know, there //demonstrate point. end; given above structure, how return not found result? if had pointers, return nil pointer t . pointers generic types not allowed. so i've come solution below: function thasht

objective c - Dynamically size uitableViewCell according to UILabel (With paragraph spacing) -

i have uitableview populated text , images json file. tableview cell sizing correctly "posts" not contain many line breaks in text cannot calculate correct height "posts" 4 or 5 line breaks. code getting height: -(float)height :(nsmutableattributedstring*)string { nsstring *stringtosize = [nsstring stringwithformat:@"%@", string]; cgsize constraint = cgsizemake(label_width - (label_margin *2), 2000.f); cgsize size = [stringtosize sizewithfont:[uifont systemfontofsize:font_size] constrainedtosize:contraint linebreakmode:nslinebreakbywordwrapping]; return size.height; } how calculate correct size while allowing line breaks , white space? edit the rest of method, inside of tableview cellforrow: -(uitableviewcell*)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { nsstring *row = [nsstring stringwithformat:@"%i", indexpath.row]; float posttextheight = [self height:posttext]; nsstring *he

GeoCoding and setting global variables iOS -

i pretty new ios development please bare me =] i have 2 global nsstring variables called mylocality , mycountry... i have set geocode below: - (void) locationmanager:(cllocationmanager *)manager didupdatetolocation:(cllocation *)newlocation fromlocation:(cllocation *)oldlocation { finishedgettinglocation = false; if (newlocation.horizontalaccuracy < 200.0f){ [locationmanager stopupdatinglocation]; clgeocoder * geocoder = [[clgeocoder alloc] init]; __block nsstring *locality; __block nsstring *country; [geocoder reversegeocodelocation:newlocation completionhandler:^(nsarray *placemarks, nserror *error) { (clplacemark * placemark in placemarks) { locality = placemark.locality; country = placemark.isocountrycode; } }]; { } while ([geocoder isgeocoding]); mylocality = locality; mycountry = country; finishedgettinglocatio

ruby on rails - Rails4 app not logging as expected on Heroku -

i have simple rails 4 app showing divergent behavior between running on localhost , heroku. trying debug behavior through logs finding calls puts or logger.info not propagating heroku logs . in view, however, puts calls working fine. i have config.log_level = :info set in /config/environments/production.rb , know relevant controller puts statements should being executed because statements placed after them in controller method being executed. i have gem 'rails_12factor', '0.0.2' in group :production , know affects logging don't understand how. would appreciate suggestions why happening or can fix. edit so had 2 calls in controller: logger.info "in load_messages, id: #{params[:cid]}" @current_conversation = conversation.find(params[:cid]) logger.info "in load_messages, current_conversation: #{@current_conversation}" # other code executing @current_conversation not being loaded, nor logs being executed. removed 2 logger.i

java - Convert a letter to the corresponding letter on the opposite counting direction in the alphabet -

i self-studying java , @ beginning learning basics. below code trying convert letter corresponding letter on opposite counting direction in alphabet(i.e z or z etc.). works single letter not series of letters. how can make work more 1 letter? if can use simplest way quite new in java. don't(know how to) export built in classes etc. thank you. class turner{ int find(int fin, int mi,int ma,char ch[]){ int mid = (ma+mi)/2; int x; if(ch[mid]==fin) return mid; else if(fin<ch[mid]) return(find(fin, mi,mid-1,ch)); else return x = find(fin,(mid+1),ma,ch); } } class turn { public static void main(string args[]) throws java.io.ioexception { turner try1 = new turner(); char arra[] = new char[26]; char arrb[] = new char[26]; int min = 0; int max = arra.length; char = 'a'; char b = 'z'; int i; char le

javascript - Reset pin graphic when infobox closes -

i have simple google maps (api v3) code changes icon orange when particular marker clicked , infobox opens. code notices if infobox open , if so, resets marker icon on old infobox. however, can't figure out how reset marker icon default if infobox closed. i use 1 infobox , fill details each time marker clicked: google.maps.event.addlistener(marker, 'click', (function(marker, i) { return function() { if(previousmarker) { // if marker icon changed before, change default previousmarker.seticon('/img/location_pin.png'); } ib.close(); // close infobox open ib.setoptions(opt[i]); // set new options infobox ib.open(map, this); // open on marker // , change marker color orange marker.seticon('/img/location_pin-orange.png'); previousmarker = marker; // remember marker next time map.panto(markerdata[i].latlng); } })(marker, i));

xaml - How to display from one model but save to another -

i have listview user can select multiple items chorelist . however, i'd items selected save model contains list of chores below attempt @ that, isn't working. personsingle object contains 0 assignedchores <listview x:name="chorelist" borderbrush="white" borderthickness="1" grid.row="1" displaymemberpath="summary" itemssource="{binding chorelist, mode=oneway}" selectedvalue="{binding personsingle.assignedchores, mode=twoway}" selectionmode="multiple"/> what need add chores select personsingle.assignedchores list? update answer: private void chorelist_selectionchanged(object sender, selectionchangedeventargs e) { if (e.removeditems.count > 0) { foreach(win8chores.model.databasetables.chore item in e.removeditems) { win8chores.model.databasetables.chore mychore = new mode