Posts

Showing posts from February, 2015

c# - HttpClient does not see "Set-Cookie" header -

i have mvc login form: [httppost] public actionresult login(loginviewmodel viewmodel) { if (viewmodel.username == "alex" && viewmodel.password == "password") { formsauthentication.setauthcookie(viewmodel.username, false); return redirecttoaction("index", "home"); } return view(); } and console app client consumes mvc login action: private static void getperson() { console.writeline("username:"); string username = console.readline(); console.writeline("password:"); string password = console.readline(); using (httpclient httpclient = new httpclient()) { httprequestmessage authrequest = new httprequestmessage(); authrequest.method = httpmethod.post; authrequest.requesturi = new uri(@"http://localhost:4391/account/login"); authrequest.

asp.net - My system.webServer > staticContent > clientCache element obstructs serving CSS, JavaScript, and Images -

i have system.webserver section. when add clientcache line, web server stops serving javascript, css, , images. when remove clientcache line, again starts serving them. wrong clientcache element? this problem occurs both in visual studio development server , when push website azure. <system.webserver> <staticcontent> <clientcache cachecontrolmode="usemaxage" cachecontrolmaxage="86400"/> </staticcontent> <!--handlers removed clarity--> </system.webserver> in asp.net, clientcache > cachecontrolmaxage property timespan (though http specification makes max-age header seconds .) so, wrong : <clientcache cachecontrolmode="usemaxage" cachecontrolmaxage="86400"/> and right : <clientcache cachecontrolmode="usemaxage" cachecontrolmaxage="1.00:00:00"/> where iso on one?

php - How to upload a file from a page called already through Ajax? -

the form upload works if not called through ajax first, if tab/page loaded $.get(page+".php", {type: type}, function(d){ $('#maincontent').html(d); }); then malsup jquery plugin doesn't work , redirect url listed in forms action section. how work same way if directly on page? i believe on success of ajax request have re-bind malsup plugin dom gets updated. have add rebinding in success handler.this may solve problem.

php - PHPMailer populating emails from result of query -

i'm trying populate email addresses in phpmailer array returned query. $query = 'select u.id, u.first_name, u.last_name, u.email users u inner join locations l on (u.location_id = l.id) district_id = 8 group id order first_name, last_name asc'; $result = mysqli_query($connection, $query); if (!result) { die("database query failed: " . mysqli_error($result)); } $recipients = array(); while ($row = mysqli_fetch_assoc($result)) { $results[] = $row; } this gives me result such as: array ( [0] => array ( [id] => 1 [first_name] => jon [last_name] => smith [email] => jon@domain.com ) [1] => array ( [id] => 3 [first_name] => dave [last_name] => virk [email] => dave@domain.com ) [2] => array ( [id] => 2 [first_name] => chris [last_name] => west [email] => chris@domain.com ) ) but being new working arrays i'm not sure how extract name , email of each user phpmailer. i read example did this:

swing - In java socket programming, is it necessary to run server program first before client program? -

i building remote desktop viewer app using swing. when run server first , client, app working fine. but when run client first , server, client gives exceptions there no listening server. what should if run client first , server connection should successful , client should not give exceptions? thanks. connectexception thrown when client tries connect server not started. have retry logic using try{ socket.connect(..) }catch(connectexception ex) { } within loop. delay can added between retry free cpu.

html - Change image color on hover -

Image
i have image have used z-index place box , text on image: here's looks like: and that's done using code: #wrap { position:relative; width: 200px; height: 145px; border: 1px solid grey } #text { z-index: 100; position: absolute; color: white; font-size: 20px; font-weight: bold; padding: 10px; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,.7); } and calling function: <div id="wrap"> <img src="/wp-content/uploads/2014/03/brandslang.png"/> <div id="text">brand</div> </div> this image etc used link want give user sort of response when or hovers on image , want have box span on whole image when user hovers on this: i looked @ a:hover i'm not sure how implement affect image , not every single link have on page, , hoping guys me! :) what said correct hover level: http://jsfiddle.net/83n5x/1/ <div id="wrap&q

java BigInteger random number in a minimum and maximum range -

in java, it's easy find random number using random() in range. below method i've tried that. public int rand(int min, int max){ random rands = new random(); int numrand = rands.nextint(max-min) + min; return numrand; } but, it's in integer has 2,147,483,647 maximum values. then, need compute values has large number. let's large number 5234960860151076037807790832396537967963815240976924943830782457906435372625549206966897650382309539933354611312768681026528740101 it contains 130 characters of number. can't stored in integer, in double. but, need find large random number that. so, found way random large number using biginteger. at here , random number n-digit. at here , random number 0 n. it's similar this . at here , random number 1 8180385048 . so far, found them useful. i'm still confusing how know whether minimum number 0 or 1 or 123456712312 . i want generate random number using biginteger minimum maximum values

asp.net - WebForm_DoPostBackWithOptions is not defined using chrome -

on 1 of pages dynamic links work fine in ie10, not work in either chrome or via explorer on windows phone. in chrome "webform_dopostbackwithoptions not defined" when try click on of dynamic links. i've done lot of research, , have tried modify settings isapi filters in handler mappings in iis 8, didn't work. please help. i'm stumped. update: not work in firefox. seems dynamic links on page work in ie10. links being generated codebehind. strange on other pages links generated differently javascript on href being different, yet i'm creating anchors in codebehind same way. here's code "bad" anchor: dim anchname new htmlanchor anchname.id = "bcrasodiuhf" & foo addhandler anchname.serverclick, addressof handlenameclick anchname.attributes.add("style", "font-weight: bold; font-size: 14px;") anchname.attributes.add("for", foo) anchname.innertext = foo and "bad" result: <a id=&quo

java - JDK8 CompletableFuture.supplyAsync how to deal with interruptedException -

completablefuture.supplyasync( () -> { transporter.write(req); //here take value blocking queue,will throw interruptedexception return responsequeue.take(); }, executorservice); the common method deal interruptedexception either interrupt again or direct throw interruptedexception, both cannot work. have idea? i change code this. completablefuture<rep> result = new completablefuture<>(); completablefuture.runasync(() -> { transporter.write(req); try { rep rep = responsequeue.take(); result.complete(rep); } catch (interruptedexception e) { result.completeexceptionally(e); thread.currentthread().interrupt(); } catch (exception e) { result.completeexceptionally(e); } }, executorservice); return result;

java - Render PDF using JSP -

this code using in jsp render pdf file fileinputstream fis = new fileinputstream(path); int b = 0; while ((b = fis.read()) != -1) { out.write(b); } path contains location of pdf file stored on local disk. problem: rendering stupid text. not figure out is. any appreciated. code add/modify i think least going need set response type "application/pdf". out variable? if its' httpservletresponse, can like: response.setcontenttype("application/pdf"); many approaches doing outlined here: displaying pdf in jsp

c# - How to serialise Web API 2 HttpRequestMessage into my custom object -

i have following method in webapi 2 project. public class testcontroller : apicontroller { [httppost] public void test(httprequestmessage request) { var content = request.content; string jsoncontent = content.readasstringasync().result; } } my custom object looks this; public class test { public int id { get; set; } public string name { get; set; } } if post sample data like <test> <id>12345</id> <name>my name</name> </test> the resulting value in jsoncontent correct. question how best should serialise httprequestmessage (content) object test can perform additional validation / tasks etc. should pass httprequestmessage method or possible pass like public void test(test otest) you can use parameter in action method this. [httppost] public void test(test otest) asp.net web api deserialize request message body (json or xml) test . based on content type header in request,

ruby on rails - Devise Registration Form -

i have 2 devise forms used in ruby on rails site...how can set different route paths both devise form..i tried override after_sign_up_path..but both forms gets redirected same path... i want set different paths each form. registrations controller class registrations controller < devise::registrations controller protected def after_sign_up_path_for(resource) 'root_path' end end this method calls when signup success, set after signed path here def after_sign_up_path_for(resource) if resource.invitation_type == "first" (please replace actual invitation type here) user1_path(replace actual path) elsif resource.invitation_type == "second" (please replace actual invitation type here) user2_path(replace actual path) else root_path end end hope helps!

android - Set drawable image as background on custom view -

i'm creating map application , want know how add map-image background, able draw text on it. want create custom view class extends view, add background , override ondraw-method. my idea use constructor add background image, image deciding size of custom view. can use coordinates draw text @ positions on image. hank you can use property of extended view in constructor of custom class. can assign background in constructor. like way.. public class testview extends view{ public testview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); // todo auto-generated constructor stub setbackgroundresource(r.drawable.your_drawable); } }

reactjs - React-tools: app.jsx changed; rebuilding... never ends -

i'm learning react.js, , use npm have react-tools installed. after type command: jsx --watch src/ build/ , did changes jsx file. console logs: app.jsx changed; rebuilding... [] it never ends. did have same problem? yeah had same thing. managed working explicitly setting jsx file extension when resolving module identifiers jsx -w -x jsx src/ build/

air - flex app open in portrait in portrait instead I am forcing an app to open in landscape -

Image
i have <aspectratio>landscape</aspectratio> , <autoorients>false</autoorients> in app.xml file, , application supports landscape orientation. still apple has rejected it. i have used air sdk 13.0.0.** , flash builder 4.7 they have givebn rejection number 10.6: apple , our customers place high value on simple, refined, creative, thought through interfaces. take more work worth it. apple sets high bar. if user interface complex or less may rejected app made ipad only <iphone> <infoadditions><![cdata[ <key>uidevicefamily</key> <array> <string>2</string> </array> ]]></infoadditions> <requesteddisplayresolution>high</requesteddisplayresolution> </iphone> can tell me why have rejected it. they given me rejection screenshot: you need put autoorients on true. may ask why? app needs work either in landscape or port

expandablelistview - How to implement Expandable android navigation drawer with subitems? -

Image
how implement android navigation drawer this? toplevelview1 ~ toplevelview4 can select , no children topvevelview5 can collaspe my question if group structure example all stared category ----mp3 ----txt ----doc ----pdf when select show file. when select stared show stared file only. when select mp3 show mp3 files. and category can expand , collapse. for navigation: alternative 1: sliding menu, go with. used popular application linkedin , foursquare , easy implement , use. full explanation , example source codes: slidingmenu - github alternative 2: android navigation drawer. if want customise without using libraries, option. can check codes , how android developers website: creating navigation drawer view inside navigation drawer / sliding menu: alternative 1: android default expandablelistview. links: android developers , androidhive alternative 2: animatedexpandablelistview, implemented expandablelistview, when item clicked, expa

C++ http read special characters from my SQL DB -

when perform post call c++ client fetching mysql data (i use classical webservice), got troubles when special characters in http result, eg "è", "à", "ò"... in fact, store server answer (the http result) in char* variable can read "è" instead of "è". post: httpobject->setrequestheader("content-type", "application/x-www-form-urlencoded"); httpobject->setrequestheader("cache-control", "max-age=0"); httpobject->setrequestheader("accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); httpobject->setrequestheader("accept-encoding", "gzip,deflate,sdch"); httpobject->setrequestheader("accept-language", "it-it"); httpobject->setrequestheader("accept-charset", "iso-8859-1,utf-8;q=0.7,*;q=0.3"); httpobject->post(my_webservice, my_text, text_length, c

interceptor - Android VpnService: Reading from Tun device hangs -

my app using vpnservice traffic interception. what does: 1.reads tun device in loop: while (started && tundevice.valid()) { final byte[] bytes = tundevice.read(); ippacket packet = packetfactory.createpacket(bytes); if (packet == null) { thread.yield(); } else { proxyservice.handlepacket(packet); } } tundevice.read: @override public byte[] read() throws ioexception { if (!valid()) { log.warn("tun: file descriptor not valid more"); return null; } int length = tuninputstream.read(readbuffer); log.debug("tun: received packet length={}", length); if (length < 0) { throw new ioexception("tun device closed"); } if (length == 0) { return null; } return arrays.copyofrange(readbuffer, 0, length); } 2.proxifies data protected socket. the problem after time stops reading tun device. read method hangs , waits time (like 3-5 minutes). u

css - How to set a div size to its background image size -

<div class="newsblocks"></div> css: .newsblocks{ background: url(../img/news/1.png); } how set div size of 1.png? it's not possible auto-size div based on size of it's background image, (hacky) way, including img tag url image, setting img visibility:hidden; [used inline css brevity - don't kill me!]: <div style="background-image: url('img.jpg');"> <img src="img.jpg" style="visibility:hidden"/> </div

How to start python file as a service in OSX (I need both a start and a stop script) -

i want run python program/file service on osx. need start , stop script. i have tried multiple solutions know work in linux, none seem work in osx. remember trying 1 worked if code simple 'hello world', more complex , python crash. the code trying run works fine when 'execute' py script on terminal. i imagine rather easy can't seem work. ps: using % in terminal not work in situation, need start , stop script. cheers, in advance. i suggest use launchd this. write configuration files, place them in /system/library/launchdaemons , can start , stop them launchctl . it's not hard figure out. you should read manpages launchctl , program used start , stop launch agents, , launchd.plist , configuration format. it's long read, not difficult ot understand. there lots of options timing , responding events, you'll need simplest. you'll find plenty of example scripts in system @ above path.

ios - Delay start of a CATransition -

it's possible delay animation of catransition? tried startprogress but doesn't make difference. this how i'm making transition: catransition *animation = [catransition animation]; [animation settype:kcatransitionpush]; [animation setsubtype:kcatransitionfromleft]; [animation setduration:0.25]; [animation settimingfunction:[camediatimingfunction functionwithname: kcamediatimingfunctioneaseineaseout]]; [animation setremovedoncompletion:yes]; [self.tabbarcontroller.view.layer addanimation:animation forkey:@"pushanimation"]; please read this: http://wangling.me/2011/06/time-warp-in-animation.html it's article additional timing properties of animatios.

ios - How can I animate the height of a CALayer with the origin coming from the bottom instead of the top? -

i want animate simple calayer move , down in response incoming data (bars on graphic equaliser) the calayer should remain fixed along bottom , move , down height animated. can advise on best way achieve without having animate origin y coord height? if want layer grow , shrink bottom, should set own anchorpoint on layer bottom. anchor point specified in layers unit coordinate space both x , y range 0 1 inside of bounds, no matter size. yourlayer.anchorpoint = cgpointmake(0.5, 1.0); then animation, animate bounds (or better, can animate "bounds.size.height" , since height changing): // set new bounds of yourlayer here... cabasicanimation *grow = [cabasicanimation animationwithkeypath:@"bounds.size.height"]; grow.fromvalue = @0; // no height grow.tovalue = @200; // height of 200 grow.duration = 0.5; // add additional animation configuration here... [yourlayer addanimation:grow forkey:@"grow height of layer"]; you can read m

Copy constructor in polymorphism in C# -

please first take @ simple code; this base class: public class baseclass { public baseclass() { } public baseclass(baseclass b) { } public virtual string getmsg() { return "base"; } } and derived one: public class drivenclass : baseclass { public string msg { get; set; } public drivenclass(string msg) { msg = msg; } public drivenclass(drivenclass d) { msg = d.msg; } public override string getmsg() { return msg; } } and test: public partial class form1 : form { public form1() { initializecomponent(); } public baseclass b { get; set; } public drivenclass d { get; set; } private void button1_click(object sender, eventargs e) { d = new drivenclass("driven"); b = new baseclass(d); messagebox.show("b:" + b.getmsg() + "\nd:" + d.getmsg()); } } now question sh

html - Bootstrap form formatting not applying -

i trying add form subscription emails instance variable @premail in embedded ruby for reason form not have bootstrap styling when load on localhost. i've tried several things can't form bootstrap input form. here code form: <div class="container-form"> <%= form_for @premail, html: {class: "form-horizontal home-form", role: "form"} |f| %> <% if @premail.errors.any? %> <h2><%= pluralize(@premail.errors.count, "error") %> prohibited link being saved:</h2> <ul> <% @premail.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> <% end %> <div class="form-group"> <p> stay updated our launch! </p> &

c# - asp.net edit text and save it to database -

so got text in div box on page. want make editable , save changes button click. i know how make text in div box editable how save changes database? , put it? $("#bearbeiten").click(function() { $("#beschreibung").attr("contenteditable", "true");)} to data use ajax , tried data , post database either did wrong or not right way post data. var versionid = $(this).data("versionid"); $.ajax({ datatype: "json", url: "api/beschreibung/gettext?xversionid=" + versionid, type: "get" hope can me. summarized: how data , how change it? you should: create form ; post data webserver (you can use jquery that, suggest simple form submit button; handle post data on server. seems using mvc. there tutorials all on internet ; get posted data , send database. can use entity framework that, or ado.net.

java - What is difference between Collection.stream().forEach() and Collection.forEach()? -

i understand .stream() , can use chain operations .filter() or use parallel stream. difference between them if need execute small operations (for example, printing elements of list)? collection.stream().foreach(system.out::println); collection.foreach(system.out::println); for simple cases such 1 illustrated, same. however, there number of subtle differences might significant. one issue ordering. stream.foreach , order undefined . it's unlikely occur sequential streams, still, it's within specification stream.foreach execute in arbitrary order. occur in parallel streams. contrast, iterable.foreach executed in iteration order of iterable , if 1 specified. another issue side effects. action specified in stream.foreach required non-interfering . (see java.util.stream package doc .) iterable.foreach potentially has fewer restrictions. collections in java.util , iterable.foreach use collection's iterator , of designed fail-fast , throw concurrentmodific

php - how to add posts with image programmatically in wordpress -

this code add post programmatically in wordpress require(dirname(__file__) . '/wp-load.php'); global $user_id; $new_post = array( 'post_title' => 'table tennis', 'post_content' => 'table tennis or ping-pong sport in 2 or 4 players hit lightweight ball , forth using table tennis racket. game takes place on hard table divided net. except initial serve, players must allow ball played toward them 1 bounce on side of table , must return bounces on opposite side. points scored when player fails return ball within rules.', 'post_status' => 'publish', 'post_date' => date('y-m-d h:i:s'), 'post_author' => $user_id, 'post_type' => 'post', 'post_category' => array(2), ); $post_id = wp_insert_post($new_post); how add image post? i new wordpress,thanks in advance.. this upload file using wordpress , insert on post featured imag

java - @Transactional in the controller -

first of want mention agree make service layer transactional, world not perfect, , right i´m in middle of situation. have been assigned wonderful project legacy code of 4+ years. thing developers did not follow pattern introduce bussines logic can image multiples services call controller , after call private method controller. no budget refactor, , have many issues acid solution found make controllers transactional , @ least have full rollback if in middle of request/response go wrong. problem cannot make works. describe configuration see if can me out guys. have dispatcherservlet invoke webmvc-config.xml have declaration of controllers <context:component-scan base-package="com.greenvalley.etendering.web.controller**" use-default-filters="false"> <context:include-filter expression="org.springframework.stereotype.controller" type="annotation"/> </context:component-scan> then contextconfiguration invoke

json - Selecting specific class type from a hierarchy during jackson serialization -

if have class hierarchy -> b, base class, how can specify during jackson serialization include fields base class , exclude subclass? serializing b (the subclass) though. appreciate help!! you can use jackson json views mentioned in this similar question . also can write an annotation introspector or jackson json filter exclude subclass. i've written example demonstrating how exclude properties type in hierarchy has special annotation. public class jacksonexcludefromsubclass { @retention(retentionpolicy.runtime) public static @interface ignoretypeproperties {}; public static class superthing { public final string superfield; public superthing(string superfield) { this.superfield = superfield; } } @jsonfilter("filter") @ignoretypeproperties public static class thing extends superthing { public final string thingfield; public thing(string superfield, string thingfi

c++ - Advanced loading of obj-files -

i can't seem find tutorial on how advanced obj-loading (aka. wavefront) want load model assigned textures , not, , tutorials i've found don't explain @ (just show window working) or basic, vertices, normals , indices. so, first of all, suggestions tutorials? here code, there need make work different textures? data struct: struct objectdata { vector <glm::vec3> vertices, normals, colors; vector <glm::vec2> texcoords; vector <gluint> vindices, uindices, nindices; }; object loader h: class objectloader { private: struct material { string name; glm::vec3 color; }; vector <material*> materials; material *currentmaterial; objectdata *object; bool hasuv, hasnormals, isquads, indexchecked; string parsestring(string src, string code); glm::vec2 parsevec2(string src, string code); glm::vec3 parsevec3(string src, string code); void addindices(string str); void checkindices

java - calculate the modulus of a fraction with big numbers -

i have 2 big numbers (<10^9) n , m . have calculate [(n-1+m)!]/[(n-1)!*m!] if answer big have modulus (10^9+7) . (ex : n%mod if n large mod). int mod = 1000000000+7; i calculated below. (i calculated upper half , bottom half separately) long up=1; (long = a+b-1; i>=math.max(a, b); i--) { up*=i%mod; } up=up%mod; long down=1; (long = math.min(a, b); i>0; i--) { down*=i%mod; } then print answer system.out.println((up%mod/down%mod)%mod); is approach correct. gives correct out put. i know (a*b*c)%d == [(a%d)*(b%d)*(c%d)]%d (correct me if i'm wrong) so there way calculate [a/b]%d ? (a/b) % c != ((a%c) / (b%c) % c) instead use recursive formula of binomial coefficient calculate modulus (n, k) = (n - 1, k - 1) + (n - 1, k) in case be (n - 1 + m, m) % mod = ((n - 2 + m, m - 1) % mod + (n - 2 + m, m) % mod) % mod use above recursion result.

python - "if", and "elif" chain versus a plain "if" chain -

i wondering, why using elif necessary when this? if true: ... if false: ... ... you'd use elif when want ensure one branch picked: foo = 'bar' spam = 'eggs' if foo == 'bar': # elif spam == 'eggs': # won't this. compare with: foo = 'bar' spam = 'eggs' if foo == 'bar': # if spam == 'eggs': # *and* this. with if statements, options not exclusive. this applies when if branch changes program state such elif test might true too: foo = 'bar' if foo == 'bar': # foo = 'spam' elif foo == 'spam': # skipped, if foo == 'spam' true foo = 'ham' here foo set 'spam' . foo = 'bar' if foo == 'bar': # foo = 'spam' if foo == 'spam': # executed when foo == 'bar' well, # previous if statement changed 'spam'. foo = 'ham' now

How do you use the Confirm Email functionality in ASP.NET Identity 2.0 -

identity 2.0 boasts new functionality in area, there's no documentation. install microsoft.aspnet.identity.samples package on empty project , can find code implements functionality. sample application written in mvc

Using pointers to get value from multidimensional array - C -

i trying value "second row" in multidimensional array. have problems that. thought numbers stored sequentialy in memory tab[2][2] stored same tab[4] . seems wrong. this tried: int b[2][2] = {{111,222},{333,444}}; int = 0; for(;i < 100; i++) printf("%d \n", **(b+i)); the problem 111 , 333 result. there no 222 or 444 in other 98 results. why? the problem **(b+i) doesn't think does. evaluates to: b[i][0] as matt mcnabb noted , **(b+i) is equivalent to: *(*(b+i)+0) and since *(b+i) equivalent b[i] , expression whole can seen as: *(b[i]+0) and hence: b[i][0] since array has 2 rows, values of i 0 , 1 in bounds of array (that's 111 , 333). rest wildly out of bounds. what is: #include <stdio.h> int main(void) { int b[2][2] = { { 111, 222 }, { 333, 444 } }; int *base = &b[0][0]; (int = 0; < 4; i++) printf("%d: %d\n", i, base[i]); return 0; } output: 0: 11

bash - Adding XML element in XML file using sed command in shell script -

i using sed command insert xml element existing xml file. i have xml file <students> <student> <name>john</> <id>123</id> </student> <student> <name>mike</name> <id>234</id> </student> </students> i want add new elememt <student> <name>newname</name> <id>newid</id> </student> so new xml file be <students> <student> <name>john</> <id>123</id> </student> <student> <name>mike</name> <id>234</id> </student> <student> <name>newname</name> <id>newid</id> </student> </students> for have written shell script #! /bin/bash content="<student> <name>newname</name>

jquery - onBeforeUnload custom button messages -

i have following beforeunload function have stolen sonewhere else.... $().ready(function() { $("#posmanagerloginform").trigger("submit"); $(window).bind("beforeunload", function(){ window.settimeout(function () { window.location = "home.htm"; }, 0); window.onbeforeunload = null; // necessary prevent infinite loop kills browser return "press 'stay on page' go reporting manager home"; }); }); regardless of option select navigated home.htm. there way can make dialog box ok button instead of default "leave page" or "stay on page" options? or perhaps else make suggestion on hot better handle? thanks you cannot override styling of onbeforeunload dialog. believe me, tried before in earlier projects. reference: http://msdn.microsoft.com/en-us/library/ms536907%28vs.85%29.aspx it built browser object, , have no control on it. yo

Android: Start the circular progress bar from top (270°) -

Image
i have defined circular progress bar using following drawable " ciruclar_progress_bar.xml " <?xml version="1.0" encoding="utf-8"?> <item android:id="@android:id/progress"> <shape android:innerradiusratio="2.5" android:shape="ring" android:thicknessratio="25.0" > <gradient android:centercolor="@color/gray" android:endcolor="@color/gray" android:startcolor="@color/gray" android:type="sweep" /> </shape> </item> <item android:id="@android:id/secondaryprogress"> <shape android:innerradiusratio="2.5" android:shape="ring" android:thicknessratio="25.0" > <gradient android:centercolor="@color/green" android:endcolor="@color/gre

stellar.js - stellar js initialise with jquery only -

stellar js requires following data attribute element like: <div data-stellar-ratio="2"></div> however cannot use inline html on particular site i'd need use jquery. i tried add data attribute jquery not seem work. have idea why? $(window).stellar(); $('.gallery.home .image:nth-child(2)').data('stellar-ratio', '2'); you need order stellar() method : $('.gallery.home .image:nth-child(2)').data('stellar-ratio', '2'); $(window).stellar(); //after data-attribute set...

php - codeigniter and piwik with benedmunds authentication -

i have codeigniter application built using benedmunds authentication model. i'm setting piwik hoping create link in admin panel opens piwik. i'm not worried piwik getting login details codeigniter db. i'm happy add identical users piwik, when user logs codeigniter, needs automatically logged piwik. don't want user have login twice. any suggestions? thanks you can @ piwik source , see how authenticates. can replicate logic create needed session data. that can put ion auth hook called after successful login.

python - clang: error: unknown argument: '-mno-fused-madd' -

when installing reportlab 3.1.8, ran problem kept getting error , not find compiler option being set. the point in setup was: building 'reportlab.lib._rl_accel' extension clang: error: unknown argument: '-mno-fused-madd' [-wunused-command-line-argument-hard-error-in-future] clang: note: hard error (cannot downgraded warning) in future error: command 'cc' failed exit status 1 here solution. cause: keep mac date , result seems have newer (different) version of c compiler (clang) 1 allowed "-mno-fused-madd" command line switch. solution: did not find above switch in file in reportlab source. had on computer itself. culprit seemed in distutils, because setup.py uses module distutils. the problem in file /system/library/frameworks/python.framework/versions/2.7/lib/python2.7/_sysconfigdata.py . file contains definitions dictionary named build_time_vars. in right place have build time problem. first make copy safeguard. sudo <

xpages name picker in XPiNC -

<xe:namepicker id="namepicker1" for="djtextarea5"> <xe:this.dataprovider> <xe:dominonabnamepicker groups="false" namelist="peoplebylastname" addressbookdb="names.nsf"> </xe:dominonabnamepicker> </xe:this.dataprovider> </xe:namepicker> it works on browser without addressbookdb="names.nsf" , in client notes doesn't, when click name picker: list empty. i appreciate time! i saw can have extlib name picker running in xpinc lookup directory on server? explanation : adressbookdb="server!!names.nsf" doesn't works in client notes. you need addressbookdb="server!!names.nsf" addressbooksel="db-name". the hover on addressbookdb clarifies works if addressbooksel db-name

php - Best way to sort a big array by a key -

Image
i have big array lots of datas, here can have example : is example have 1 item [0] . i need sort array key date in last_message . (more in first) in date have format : "2014-04-23t14:59:53+0200" do have idea me ? don't want foreach think there better. thanks ! this code : uasort($arrayc, function ($a, $b) { if ($a == $b) { return 0; } return (strtotime($a['last_message']->date) < strtotime($b['last_message']->date)) ? -1 : 1; }); but there no effect on array.. you can use http://www.php.net/manual/en/function.uasort.php , provide custom function compares date. this this: function cmp($a, $b) { if ($a == $b) { return 0; } return (strtotime($a['last_message']['date']) < strtotime($b['last_message']['date'])) ? -1 : 1; } uasort($array, 'cmp');

sql - Query to Access Sharded Tables -

i querying vendors database has data sharded between multiple tables. tables named events_1 , events_2 , events_3 , events_4 etc. it appears new table automatically created when table hits 10,000 records. looking write query able union results tables (without having manually add tables created) query @ 2 newest tables. any suggestions on best way go this? the database microsoft sql server 2008 you can dynamic sql such query sysobjects table name events_* , build select union results. better, though perhaps more complicated, ddl trigger dynamically update union view append new table whenever table events_* created.

How to calculate byte size of file if I declared it indirectly(BufferedReader with pathname?) (Java 6) -

hypothetically have line bufferedreader instream = new bufferedreader(new filereader("src.txt")); at opening , closure of file how calculate size (for example length() ) instream.legth() ? @ system.out.println() ? use length method of file class: file f = new file(filename); system.out.println(f.length()) please note can use f in bufferreader object : bufferedreader br = new bufferedreader(new filereader(f));

database design - The number of categories must be greater than one but fewer than five -

i want create database application creating academic examination. database contains, sake of simplicity, 3 tables follows. problems: problemid (int, identity, primary key) problem (nvarchar) solution (nvarchar) categories: categoryid (int, identity, primary key) category (nvarchar) problemcategory: categoryid (int, composite primary key) problemid (int, composite primary key each problem linked @ least 1 category , @ 5 categories. question how make sure constraint hold in database level? bonus question: is following design recommended replacement design above? problems: problemid (int, identity, primary key) problem (nvarchar) solution (nvarchar) categoryid1 (int, not null) categoryid2 (int, null) categoryid3 (int, null) categoryid4 (int, null) categoryid5 (int, null) categories: categoryid (int, identity, primary key) category (nvarchar) question 1: each problem linked @ least 1 category. answer: declare foreign key constr

PHP Connection Error with localhost -

why this. warning: mysqli_connect(): (hy000/1045): access denied user 'root'@'localhost' (using password: yes) in /usr/local/zend/share/userserver/s/index.php on line 2 when $con = mysqli_connect("127.0.0.1","root","xxx","s"); ? i've tried localhost , didn't work either. i'm positive credentials correct. ideas?

python - How can I avoid value errors when using numpy.random.multinomial? -

when use random generator: numpy.random.multinomial , keep getting: valueerror: sum(pvals[:-1]) > 1.0 i passing output of softmax function: def softmax(w, t = 1.0): e = numpy.exp(numpy.array(w) / t) dist = e / np.sum(e) return dist except getting error, added parameter ( pvals ): while numpy.sum(pvals) > 1: pvals /= (1+1e-5) but didn't solve it. right way make sure avoid error? edit: here function includes code def get_mdn_prediction(vec): coeffs = vec[::3] means = vec[1::3] stds = np.log(1+np.exp(vec[2::3])) stds = np.maximum(stds, min_std) coe = softmax(coeffs) while np.sum(coe) > 1-1e-9: coe /= (1+1e-5) coeff = unhot(np.random.multinomial(1, coe)) return np.random.normal(means[coeff], stds[coeff]) something few people noticed: robust version of softmax can obtained removing logsumexp values: from scipy.misc import logsumexp def log_softmax(vec): return vec - logsumexp(vec) def

jquery css with dynamically created element not working -

i'm creating element using jquery appending one. i'm trying style header doesn't seem working reason. there doesn't seem syntax errors. it's appending div , text appearing, it's not being styled. jquery('<h3/>', { text: 'todays news', css: ('background-color', 'red'), id: 'tdn' }).appendto('#div1'); any appreciated try wrap css style inside { } instead of ( ) jquery('<h3/>', { text: 'todays news', id: 'tdn', css: {'background-color': 'red'}, }).appendto('#div1'); fiddle demo or can use .css() well: jquery('<h3/>', { text: 'todays news', id: 'tdn' }).css('background-color', 'red').appendto('#div1'); fiddle demo

ruby on rails - Trying to mock an API class with RSpec -

i'm trying learn how use rspec test create_price_type_cache method on setting class being called api class instance. i've tried number of approaches i've googled, figure out how this, or if should write api class differently. the test below gives me error: undefined method `api_endpoint' #<rails::application::configuration:0x00000107376420> # setting_spec.rb "should call get_price_type_list api" price_types = [build(:price_type)] api = mock_model(api.instance) api.stub!(:get_price_type_list).and_return(price_types) expect(api.instance.should_recieve(:get_price_type_list).and_return(api)).to eq [price_types] end # setting.rb class setting def self.create_price_type_cache array = api.instance.get_price_type_list activerecord::base.transaction cachepricetype.delete_all array.each |e| e.save! end end end end # api.rb class api def self.instance @instance ||= new end def get_price_type_

android - How to get the time for which screen is ON -

i working on android application warn user if screen been on long time. basic idea behind app warn user long exposure of eyes screen light. want time screen light turned on. if reaches limit then, user notified turn screen off time. how time screen turned on? reading documentation... public static final string action_screen_off added in api level 1 broadcast action: sent after screen turns off. protected intent can sent system. constant value: "android.intent.action.screen_off" public static final string action_screen_on added in api level 1 broadcast action: sent after screen turns on. protected intent can sent system. constant value: "android.intent.action.screen_on" when screen turned on keep track of current time , set alarm period of time , warn user.

python - Sentry AJAX requests get 302 with Nginx and uWSGI -

i have sentry setup described here . sentry available on www.sentry.mysite.com:9000 , , working fine, except ajax queries, example click on "resolve error" button. ajax queries uses url without port, , 302 status , have no effect. kindly help.

java - Struts 2 property tag can't access abstract parent class member -

i'm having problems accessing property via struts. wondering if who's more experienced struts able give me few pointers. the java classes set this: public abstract class parent{ protected integer id; public integer getid(){ return this.id; } } public class child extends parent{ // stuff } the child list in action class getter set up: private list<child> childlist; this code in front end, attempting grab id property: <s:iterator value="childlist" status="cstatus"> <s:property value='id' /> </s:iterator> however, nothing shows up. i've grabbed other members child class, i'm assuming there's issue parent member i'm grabbing being in abstract class? update i've attempted grab property in abstract class in jsp , works fine. other property grabbed creationdate . i've added breakpoints id getter , it's being accessed fine , returning non-null values. h

ios - Testing correct drag of UIView in Rubymotion -

i want write spec uiview use. uiview should dragged location test wether calls wright delegate methods. i'm using "drag" method. drag command not seem to dragging. perhaps i'm using in wrong way? used macbacon spec inspiration. here code: describe "draggableview" tests specdragviewcontroller before @drag = mydragableview.alloc.initwithframe [[10,200],[100,100]] @drag.backgroundcolor = uicolor.redcolor controller.view.addsubview @drag end "should not accept wrong drop" @drag.frame.should != nil @drag.accessibilitylabel = "drag view" delegate = object.new delegate.mock!(:draggableviewhasbeendroppedatwronglocation) {|view| view.should == @drag } p @drag.center drag "drag view", :from => cgpointmake(15,250), :to => cgpointmake(300,300) wait 10{} # long wait, play view in simulator p @drag.frame end end class specdragviewcontroller < uiv

java - JSONArray within JSONArray -

i'm confused why cannot pull jsonarray jsonarray in android application. example , snippet of source code given below. //the json { "currentpage":1, "data":[ { "id":"dimtrs", "name":"bud light", "breweries":[ { "id":"bznaha", "name":"anheuser-busch inbev", } ] } ], "status":"success" } now i'm trying retreive "breweries" array. //code snippet ... jsonobject jsonobject = new jsonobject(inputline); jsonarray jarray = jsonobject.getjsonarray("data"); jsonarray jsarray = jarray.getjsonarray("breweries"); ... i can pull objects out of data array fine, cannot "breweries" array "data" array using current code. the error jsarray is: the method .ge

javascript - method=flickr.photos.search not working -

i using flickr api photos relevant weather info, code works. background load suitable photos nothing load, when change method flickr.photos.getrecent loads images not suitable weather ones search method brings up, has happened anyone? this seems bug on side. search on flickr website doesn't return results when happens. https://www.flickr.com/help/forum/en-us/72157637322588906/ , https://www.flickr.com/help/forum/en-us/72157637221802585/ guess i'll have implement fallback other service image search.

php - Failed login in yii framewok because user id primary key has a foreign key to other table -

i have database table in postgresql , yii table table user , table request. attributes user.id_user primary key refer request table foreign key user.id_user pk refer request.id_user (fk) i submit request through form , save id_user in request. log out , can't login again username , password.. it said incorrect username or password. i have try other username , password , it's again.. there authenticate code ` please tell me problem , solution problem . thank you.. here login configuration examples http://www.yiiframework.com/forum/index.php/topic/45600-yii-autentication-with-mysql/ http://www.larryullman.com/2010/01/04/simple-authentication-with-the-yii-framework/

Excel VBA ComboBoxes to Omit Previously Selected Options -

i have several activex comboboxes predefined list of names: "variables!$b$1:$b$23" the comboboxes in cells a2 - a24. comboboxes omit selected options. example, if select "john doe" in a2 combobox, when open a3 combobox "john doe" not listed option. looking @ combobox_change option combobox code eludes me. i'm sure can see feeble attempt below: private sub combobox1_change() dim combovalue string combovalue = worksheets("roster").oleobjects("combobox1").object.value = 2 worksheets("variables").range("c1") listvariable = worksheets("variables").range("b" & i) if (listvariable = combovalue) 'change other comboboxes end if next end sub

php - The Chosen Plugin is not displaying properly -

i wrote simple codeigniter php app implement chosen. here's page: <!doctype html> <html> <head> <script src="<?php echo base_url();?>js/jquery-1.11.0.min.js"></script> <script src="<?php echo base_url();?>js/chosen.jquery.js"></script> <script> jquery(document).ready( function() { jquery(".chosen").chosen(); } ); </script> </head> <body> <h2>chosen plugin test</h2> <select class="chosen" style="width: 200px; display: none;"> <option>choose...</option> <option>jquery</option> <option selected="selected">mootools</option> <option>prototype</option> <option>dojo toolkit</option> </select> <select class="chosen" multip

javascript - html form two buttons with two actions -

hi there have got simple form work , both functionality update , delete working cannot seem figure out way make them work simultaneously in 1 form... here doing <form id ='udassignment' method ='get' name='udassignment'> <input id ='action' type ='hidden' name ='action' value ='updatemessagefromsimpleform' /> <label for='fid'> id </label> <input id ="fid" type='number' name ='fid' readonly/> <label for='ftitle'> title </label> <input id ="ftitle" type='text' name ='ftitle'/> <label for='fmodule'> module </label> <input id ="fmodule" type ='text' name ='fmodule'/> <label for='fdescription'> description </label> <textarea rows ='4' id ='fdescription' type ='text' name ='fdescription'> </textarea>