Posts

Showing posts from June, 2010

tel - iOS: How to launch call applications like native phone app, skype, lin phone etc from my application -

i have explored tel:// pattern establish call. in ipad mini have wi-fi support. uri fails. want know if there nay way write code such application ask user choose among calling feature supporting application. i tried callto: pattern no luck. on this? to make calls via skype can use url scheme, source skype docs bool installed = [[uiapplication sharedapplication] canopenurl:[nsurl urlwithstring:@"skype:"]]; if(installed) { [[uiapplication sharedapplication] openurl:[nsurl urlwithstring:@"skype:echo123?call"]]; } else { [[uiapplication sharedapplication] openurl:[nsurl urlwithstring:@"http://itunes.com/apps/skype/skype"]]; } to make calls via facetime can use use similar url scheme nsurl *url = [nsurl urlwithstring:@"facetime://+123456789"]; [[uiapplication sharedapplication] openurl:url]; hope helps , there no such feature aware of give list of calling apps , can manually show selection option , let user select of

how to cin to int _value:1; C++ -

i have try code, wanna use 1 byte of integer save number, how can value cin , out value cout struct songuyen{ int _value:1; void input(){ // how can cin value _value; } void output(){ // how can cout value of _value; } } thks got tip.!! struct songuyen{ int _value:1; void input(){ int value; std::cin >> value; _value = value; } void output(){ std::cout << _value; } }; the integer way not 1 byte 1 bit wide (think why called feature bit fields ). bit fields bad programming practice , should avoided possible. if need member width of 1 byte, rather use std::int8_t or signed char . if need 1 with width of 1 bit, use bool (even though waste 7 bits, doesn't matter on modern platforms). a more c++ approach implement input / output of class contain operators: struct songuyen{ int _value:1; }; template<typename chart, typename chartraits> std::basic_istream&

javascript - Why doesn't ajax load() work after second and third call? -

i've been trying 3 update same time when click button update count new feeds, notifications , messages. i've tried using setinterval( "getupdate()", 10000 ) too, update automatically every 10 seconds doesn't work second , third divs. or because ajax doesn't support many load() call? now, have no idea how should , need helps. thanks. javascript </script> function getupdate(){ $('#newsfeed').load('getnewsfeed.php'); $('#notify').load('getnewnoti.php'); $('#message').load('getnewmessage.php'); } </script> html <button type="button" onclick="getupdate()" class="btn btn-primary">get update</button> <div id="newsfeed"></div> <div id="notify"></div> <div id="message"></div> if problem concurrent ajax calls, can load them in sequence: function getupdate(){

java - Does IntelliJ IDEA Have Built-In Reverse Debugging Feature? -

i guess header obvious , undo debug process save lots time. 1 of coworker said me did once couldn't remember again how it. it's not undo operation in usual sense, can drop stack frame , re-enter same method again calling run -> drop frame menu item.

linux - how to run .run file in fedora through terminal command? -

i new user of fedora linux , trying install xampp server , have .run file have tried alien command unfortunately command not working step 1: delete .run file, don't need it. step 2: install apache (the in xampp), mysql (the m in xampp), php (the 1st p in xampp) , perl (the 2nd p in xampp) through package manager. have x (linux <- x). yum install apache mysql php perl

ruby on rails - What should be a simple render takes almost a minute -

i'm using passenger start in development environment, yet thin , webbrick , puma have same results. problem seems consistent across development machines running ubuntu 14.04. in production, not have issue @ all. ruby version 2.1.3 , 2.1.2 (tried both). using rails 4.1.6 (and tried 4.1.5 ). the login page being rendered simple , small. form posts devise session controller log in. ran strace passenger start see taking forever. thoughts on causing this? slow request started "/users/sign_in" 10.0.2.2 @ 2014-09-19 11:26:24 -0400 processing devise::sessionscontroller#new html "", 8192) = 0 sched_yield() = 0 close(9) = 0 socket(pf_inet, sock_stream|sock_cloexec, ipproto_tcp) = 9 fcntl(9, f_getfd) = 0x1 (flags fd_cloexec) fstat(9, {st_mode=s_ifsock|0777, st_size=0, ...}) = 0 fstat(9, {st_mode=s_ifsock|0777, st_size=0, ...}) = 0 connect(9, {sa_family=af_i

mysql - How to add primary key in SQL? -

this question has answer here: how add primary key mysql table? 8 answers i created table(let's contact info), forgot create primary key. since entered values in table want keep table , want add primary key column. how add primary key column on left side of table incremental numbers? you can add auto-incrementing column: alter table contact_info add column id int primary key auto_increment;

asynchronous - How do I properly download and save a list of images? -

i have list of image of urls , download , save each image. unfortunately, keep receiving out of memory exception due exhausted heap space. last attempt saved 2 images , threw "exhausted heap space, trying allocate 33554464 bytes". my code shown below. logic seems correct believe asynchronous calls may @ fault. there adjustment should make cause downloading sequential? or there method should utilizing? import 'package:http/http.dart' http; import 'dart:io'; main() { // loc set of valid urls // ... loc.foreach(retrieveimage) } void retrieveimage(string location) { uri uri = uri.parse(location); string name = uri.pathsegments.last; print("reading $location"); http.readbytes(location).then((image) => saveimage(name, image)); } void saveimage(string name, var data) { new file("${name}") ..writeasbytessync(data); print(name); } if want download them sequentially, can switch future.foreach . enumera

javascript - Overlay div over an image -

i trying overlay div on image. doing using mouseenter , mouseleave events. using knockout data binding. <ul class="gallery" data-bind="foreach: images"> <li> <img data-bind="attr: {src:turl},event: {mouseenter: $parent.showoverlay, mouseleave: $parent.hideoverlay}" /> </li> </ul> <div class="list-overlay overlay"> <img src="/content/images/play.png" /> watch </div> javascript: showoverlay: function (data, event) { var position = $(event.currenttarget).position(); var height = $(event.currenttarget).innerheight(); var width = $(event.currenttarget).innerwidth(); $(".list-overlay").css("top", parseint(position.top) + parseint(height) - 40); $(".list-overlay").css("left", position.left); $(".list-overlay").css("width", width) $(".

Next button for items xml file - android -

i have xml file 500 texts. have button take sentace random , show it. want add 2 more buttons next , back. take every sentace. code rando button. final textview tv = (textview) findviewbyid(r.id.quote); resources res = getresources(); mystring = res.getstringarray(r.array.quote); string q = mystring[rgenerator.nextint(mystring.length)]; tv.settext(q); button btn = (button) findviewbyid(r.id.btn); btn.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { mystring = getresources().getstringarray(r.array.quote); string q = mystring[rgenerator.nextint(mystring.length)]; tv.settext(q); } }); } what code these buttons? thank you all code: import java.util.random; import android.app.activity; import android.content.context; import android.content.res.resources; import android.os.bundle; import android.support.v7.app.actionba

hadoop - Find common elements using Pig script -

i newbie world of hadoop,currently exploring pig scripts. have write pig scripts finds out common data between 2 files. for instanace, samplefilea has data: 1,a,,m 2,b,25,f the above data describes column 1 id , column 2 name ,column 3 age , column 4 gender samplefileb has same data: 1,a,,m 2,b,25,f i tried various joins not getting expected output because of blank or null present in column 3 of first record. the expected output is: (2,b,25,f),(2,b,25,f) (1,a,,m),(1,a,,m) but getting is: (2,b,25,f),(2,b,25,f), ,(1,a,,m) i not sure empty data coming in output. your highly appreciated.

java - Using GSON to parse mixed type fields? -

how can use gson mixed type fields, possible? { 'field': false } // or { 'field': [ 1,2,3,4 ] } my gson class: public class mymodel { public hashmap<arraylist,boolean> blockedusers; } yes possible, have handle if json array or primitive type. try code below: string case1 = "{'field':false}"; string case2 = "{'field':[1,2,3,4]}"; jsonelement jsonelement = ((jsonobject)(new jsonparser().parse(case1))).get("field"); if(jsonelement instanceof jsonarray) { jsonarray jsonarray = (jsonarray)jsonelement; if(jsonarray != null && jsonarray.size() > 0) { (jsonelement ajsonelement : jsonarray) { // todo: handle json element inside array system.out.println(ajsonelement); } } } else if (jsonelement instanceof jsonprimitive) { boolean value = jsonelement.getasboolean(); system.out.println("value:" + value); }

Java JFrame Window not appearing when run from Eclipse -

a simple problem. try run simple demo created , display window frame eclipse, , nothing happens. no errors, no window, code runs completion. i added breakpoints , made sure code runs expected. code straight java tutorials (framedemo), renamed package fit placed (other code package runs fine): package ui; import java.awt.*; import javax.swing.*; /* framedemo.java requires no other files. */ public class framedemo { /** * create gui , show it. thread safety, * method should invoked * event-dispatching thread. */ private static void createandshowgui() { //create , set window. jframe frame = new jframe("framedemo"); frame.setdefaultcloseoperation(jframe.exit_on_close); jlabel emptylabel = new jlabel(""); emptylabel.setpreferredsize(new dimension(175, 100)); frame.getcontentpane().add(emptylabel, borderlayout.center); //display window. frame.pack(); frame.se

html - showing and hiding content with Javascript -

kindly see theme. when click on "about us, contact us, newsletter" shows div content except present content , clicking close button disappear. how this? want code in way..... http://abyadwaswad.com/vipe/index-image.html without seeing theme and/or code, can't more giving example code. 1 requires jquery i'm sure in standard javascript. html: <ul id="menu"> <li class="menu-item" id="menu-item-1">menu item 1</li> <li class="menu-item" id="menu-item-2">menu item 2</li> <li class="menu-item" id="menu-item-3">menu item 3</li> </ul> <div id="menu-content"> <div id="menu-content-1"> content of menu #1. </div> <div id="menu-content-2" hidden="hidden"> content of menu #2. </div> <div id="menu-content-3" hidden=&quo

angularjs - Angular JS directive loading explained -

i'm looking understand expected behavior of angular directives when page loaded once returned using routing. if have directive below on page, debugger line reached when page first loaded. when navigate away page page different controller, return original page directive, directive doesn't load. expected behavior when dealing different controllers? or should directive link called every time page loaded regardless? app.directive('directive1', function () { return { restrict: 'e', replace: true, template: '<div></div>', link: function (scope, element, attr) { debugger; console.log('directive loaded'); } } }); it's on page this <directive1 id="mydirective" style="height:100%;"></directive1> the flow this pg1.htm(directive)/controller1 --> pg2.htm/controller2 --> pg1.htm(directive)/controller1 since spa, moving inside angularjs app,

php - True meaning of memory exhaustion error? -

i got pretty standard looking error: allowed memory size of 134217728 bytes exhausted (tried allocate 343982 bytes) except says cannot allocate 0.34 mb out of 134mb. all answers google point adding more memory script, however, not see why need add more memory script has 394x it's memory requirements. how possible? for details sake run: php 5.5 nginx 1.6 ubuntu 14.01 at point of exhaustion, 128mb tried allocate further 0.33mb. cant because has reached limit of 128mb.

php - mySQL auto increment problem: Duplicate entry '4294967295' for key 1 -

i have table of emails. the last record in there auto increment id 3780, legit record. new record insert being inserted right there. however, in logs have occasional: query fail: insert mail.messages (timestamp_queue) values (:time); array ( [0] => 23000 [1] => 1062 [2] => duplicate entry '4294967295' key 1 ) somehow, autoincrement jumped int max of 4294967295 why on god's green earth jumped high? have no inserts id field. the show status table, auto_increment table reads: 4294967296 how occur? realize id field should perhaps big int, worry have somehow thing jumps up. josh edit: update mysql version 5.0.45 red hat patched since set id bigint last few id's like: 3777 3778 3779 3780 4294967295 4294967296 4294967297 4294967298 4294967299 4294967300 as can see, incremental, no gaps (so far). totally weird. i had same problem exact same number. problem had field on int(10) when changed bigint(20) solved problem.

google maps - Android, something like on compass click listener -

i have map 60° tilt, , need set in 60 again after user touches compass, because sets tilt 0° would resetting tilt angle in oncamerachangelistener trick?

java - using Apache HttpClient in a new thread, I don't know if it finished running -

i faced strange problem. hope find out reason. code: public static void asyncsend(final roomnotification notification, final int retrytimes) { thread thread = new thread(new runnable() { @override public void run() { boolean finish = false; try { objectmapper mapper = new objectmapper(); string messagestring = mapper.writevalueasstring(notification); logger.info("json send hipchat :{}", messagestring); #1 content content = request.post("https://api.hipchat.com/v2/room/<hidden>/notification?auth_token=<hidden>") .bodystring(messagestring, contenttype.application_json) .execute().returncontent(); #2 logger.info("hipchat return:{}", content.asstring()); finish = true; } catch (clientprotocolexception e) { e.printstacktrace();

system.byte[] error c# when converting from string to byte -

i want convert string byte[] in c# , of previous topics use code : string s = "0a"; system.text.asciiencoding encode = new system.text.asciiencoding(); byte[] b = encode.getbytes(s); console.writeline(b); but when run code prints : " system.byte[]" i think may have deciphered question. trying hex digits of string array? i'm assuming want take 2-digit hex values string , convert each lot bytes. if not, i'm lost else. please note have not included error checking! byte[] data = new byte[s.length/2]; for(int = 0; < s.length/2; ++i) { byte val = byte.parse(s.substring(i*2,2), system.globalization.numberstyles.hexnumber); data[i] = val; } foreach(byte bv in data) { console.writeline(bv.tostring("x")); }

r - Shiny server deployment to shinyapps.io error -

i have issue deploying app shinyapps.io. running deploy within rstudio (r 3.1.1/win64) following message: preparing deploy application...done uploading application bundle...done deploying application: 20528... waiting task: 1656427 building: parsing manifest building: installing packages building: installing files building: pushing image: 54178 deploying: starting instances terminating: stopping old instances application deployed http://littlebig.shinyapps.io/crisis shinyapps deployment completed: http://littlebig.shinyapps.io/crisis however, when launching app message saying "application failed start" following error message: attaching package: ‘shiny’the following object masked _by_ ‘.globalenv’: tagserror in paste(tags$script(src = "__assets__/sockjs-0.3.min.js"), tags$script(src = "__assets__/shiny-server-pro.js"), : attempt apply non-functioncalls: local ... eval.parent -> eval -> eval -> eval -> eval -> pa

javascript - Passing in a key results in extra characters in my firebase URL, how do I remove them? -

when placing "key" variable inside of string, displays 'simplelogin%3a5' instead of 'simplelogin:5'. there way pass in latter? var populatetasks = function(date, key){ $scope.ref = new firebase("https://myfirebase.firebaseio.com/users/"+key+"/tasks"); }; results in: https://myfirebase.firebaseio.com/users/simplelogin%3a5/tasks need: https://myfirebase.firebaseio.com/users/simplelogin:5/tasks var uri = "//what need convert"; var uri_dec = decodeuricomponent(uri); var res = uri_dec;

java - Dice program longest streak not resetting -

here output following code: roll>>4 (1)higher or(2)lower?>> 1 current: 1 longest: 1 roll>>7 (1)higher or(2)lower?>> 2 streak ended. play again? 1-yes 2-no?>> 1 longest: 2 roll>>4 (1)higher or(2)lower?>> when game ends , hit "1" play again, longest streak continues left off. how make resets every time play new game? here code: package diceman; import java.util.*; public class diceman2 { public static void main(string[] args) { scanner in = new scanner(system.in); random gen = new random(); int current = 1; int longest = 0; while (true) { // generates random number int random1 = gen.nextint((6) + 1); int random2 = gen.nextint((6) + 1); int random = (random1 + random2); system.out.println("roll>>" + (random)); // user plays game system.out.println("(1)higher or(2)lower?>>"); int input = in.nextint();

node.js - Nodejs request handlers not waiting for function to return -

i have request handler particular route following: function dothing(req, res) { res.json({ "thing" : "thing", "otherthing": externalmodule.somefunction("yay"); }); } it seems result being send before "somefunction" call completes, "otherthing" json non-existent. how can wait function return data before sending response? use callbacks. example: externalmodule.somefunction = function(str, cb) { // logic here ... // ... execute callback when you're done, // error argument first if applicable cb(null, str + str); }; // ... function dothing(req, res, next) { externalmodule.somefunction("yay", function(err, result) { if (err) return next(err); res.json({ "thing" : "thing", "otherthing": result }); }); }

c - Explain this implementation of free from the K&R book -

this excerpt malloc/free implementation on k&r book. having great difficulty in understanding free function, if statement in loop: if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) . if p >= p->s.ptr true, p must last node in free list, since circular list, p->s.ptr must point base header (remember therer list header defined static header base; ). how can bp < p->s.ptr true? can please explain it? /* free: put block ap in free list */ void free(void *ap) { header *bp, *p; bp = (header *)ap - 1; /* point block header */ (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; /* freed block @ start or end of arena */ if (bp + bp->s.size == p->s.ptr) { /* join upper nbr */ bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr

android - What is the working of setTag and getTag in ViewHolder pattern? -

i have simple code snippet implementing custom listview. my code follows: weatheradapter.java : public class weatheradapter extends arrayadapter<weather>{ context mcontext; int mlayoutresourceid; weather mdata[] = null; view row; public weatheradapter(context context, int layoutresourceid, weather[] data) { super(context, layoutresourceid, data); mlayoutresourceid = layoutresourceid; mcontext = context; mdata = data; } @override public view getview(int position, view convertview, viewgroup parent) { row = convertview; weatherholder holder = null; if(row == null) { layoutinflater inflater = ( (activity) mcontext).getlayoutinflater(); row = inflater.inflate(mlayoutresourceid, parent, false); holder = new weatherholder(row); row.settag(holder); } else { holder = (weatherholder)row.gettag(

java - Video does display in android emulator -

video not display while run project. push a.mp4 file in file explore -> mnt -> sdcard -> a.mp4 still videos not play while run project. please me mistake in below code. public class mainactivity extends activity { videoview video_player_view; surfaceview sur_view; mediacontroller media_controller; displaymetrics dm; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } public void getinit() { video_player_view = (videoview)findviewbyid(r.id.videoview1); media_controller = new mediacontroller(this); dm = new displaymetrics(); this.getwindowmanager().getdefaultdisplay().getmetrics(dm); int height = dm.heightpixels; int width = dm.heightpixels; video_player_view.setminimumheight(height); video_player_view.setminimumwidth(width); video_player_view.setmedia

sql - NULL vs DEFAULT NULL vs NULL DEFAULT NULL in MYSQL column creation? -

following sql table definition illustrated 1 of create table statement mysql database developed former developer of company. drop table if exists `classifieds`.`category_vehicles`; create table `classifieds`.`category_vehicles`( `adv_id_ref` bigint unsigned not null, `category_id_ref` tinyint unsigned not null, `forsale_status` tinyint (1) not null, `vehicle_type_id_ref` tinyint unsigned not null, `price` double null default null, primary key (`adv_id_ref`) ) engine = innodb charset = latin1 collate = latin1_swedish_ci ; in there @ statement price double null default null, normally using price double null; if want enable column accept null values. so differences between these 3 statements? 1) price double null; 2) price double default null; 3) price double null default null; thank much. there no difference. null default null implicit default. from create table documentation: if neither null nor not null specified, column treated though null

sockets - Got stuck at java.net.SocketInputStream.socketRead0(Native Method) -

i got stuck @ java.net.socketinputstream.socketread0(native method). please see thread dump below, it's been in status 3 hours. thread-0" prio=10 tid=0x00007facd02a5000 nid=0x309 runnable [0x00007facd4a43000] java.lang.thread.state: runnable @ java.net.socketinputstream.socketread0(native method) @ java.net.socketinputstream.read(socketinputstream.java:150) @ java.net.socketinputstream.read(socketinputstream.java:121) @ sun.security.ssl.inputrecord.readfully(inputrecord.java:442) @ sun.security.ssl.inputrecord.read(inputrecord.java:480) @ sun.security.ssl.sslsocketimpl.readrecord(sslsocketimpl.java:927) - locked <0x00000000e34a0428> (a java.lang.object) @ sun.security.ssl.sslsocketimpl.readdatarecord(sslsocketimpl.java:884) @ sun.security.ssl.appinputstream.read(appinputstream.java:102) - locked <0x00000000e34a0590> (a sun.security.ssl.appinputstream) @ java.io.bufferedinputstream.fill(bufferedinputstream.java:235)

Javascript is not executing while loading a php page2 into page1 via ajax -

i beginner php , javascript. facing issue i've page page1 has 2 input fields , button(go).while clicking 'go' page2 populates on same page (page1) has data table. trying implement js on table js scripts not executing. (if have data table in single page works upper scenario not). page1(main page having inputs , button) <script src="../javascript/file_history.js"></script> <input name="advance_search" type="text" id="advance_search" size="26" /> <input name="button" type="button" onclick="showfilehistory()" value="go" /> the other page having data table on ajax call through js <script src="../javascript/file_history.js"></script> <script type="text/javascript" src="../javascript/gs_sortable.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"

c# - EF DBConfiguration associated automatically to DBContext without annotation -

using latest ef (6.1.1) , ef sql server compact (6.1.1) pulls in compact 4.0. target net 4.5.1 looking code ef , later on piece structuremap. created dbconfiguration class: public class myconfiguration : dbconfiguration { setdatabaseinitializer<mycontext>(new myinitializer()); setproviderservices(sqlceproviderservices.providerinvariantname, sqlceproviderservices.instance); } and context: public class mycontext : dbcontext { public mycontext(string connection) : base(connection) {} .... } with xunit run: using (var ctx = new mycontext(string.format("data source={0}", path.combine(databasepath, databasename)))) { ctx.database.initialize(true) } the test case creates (and seeds through initializer) compact database. there bunch of implicit stuff happening behind scenes don't get. for example, don't need have following annotation on mycontext class: [dbconfigurationtype(typeof(myconfigurati

windows - Cygwin doesn't find /.bashrc -

i install cygwin on windows 7 64bit, , location on /.bashrc location c:/cygwin64/home/admin/bashrc , can't see cygwin, it's says: bash: /.bashrc: no such file or directory what try navigate folder command: cd /cygdrive/c/cygwin64/home/admin/ and use: /.bashrc but says: no such file or directory what see file? i had same problem on cygwin installation. cygwin_nt-6.1 2.5.2(0.297/5/3) x86_64 cygwin i created ~/.bashrc file in (cygwin) home directory, aliases set did not work. the problem did not have ~/.bash_profile file in home directory. must contain following line recognize desired .bashrc . ~/.bashrc i created appending needed line echo ". ~/.bashrc" >> ~/.bash_profile see stackoverflow > cygwin shell doesn't execute .bashrc

how to search for every word in the search query using PHP MySql -

i using php , mysqli fetching records database . table engine = innodb . mysql v5.5 suppose have records 1 | beautiful switzerland girl | 2 | beautiful rabbit in park | 3 | natural sea | now if search query beautiful return first 2 records problem if searched beautiful anything , return nothing want first 2 records displayed in case because has word beautiful in it. using select * table name '%value%' order id asc mysql query searching right . is there other query or method achieve or possible option develop custom algorithm . i suggest lucene or solr full text searching functionality. give fast data comparatively direct database query. reference links : http://oak.cs.ucla.edu/cs144/projects/lucene/ http://www.avajava.com/tutorials/lessons/how-do-i-use-lucene-to-index-and-search-text-files.html

css - How to glue :after to last word -

i has code <div class="cont"> <span class="wrap"> <span class="inner"> hello, name mao </span> <span class="emptyornot"> </span> </span> .cont { width: 150px } .wrap:after { content: 'a'; background: #ccc; display: inline; } http://jsfiddle.net/rcsd7l74/ i need :after stay last word in .wrap . , if container small - break line before last word. the css have well; problem you're having new-lines, in html, collapse single white-space character; remove , works (leading this, admittedly ugly, html): <div class="cont"> <span class="wrap"> <span class="inner"> hello, name mao</span><span class="emptyornot"></span></span> </div> to allow prettier html (though, in fairness, html should minimsed when sent client anyway), such

regex - Convert functions of math to functions of javascript in java -

i have made string mathematical expression parser follows: public class expsolver { public string solve(string s){ try { scriptenginemanager mgr = new scriptenginemanager(); scriptengine engine = mgr.getenginebyname("javascript"); return engine.eval(s).tostring(); } catch (scriptexception ex) { logger.getlogger(expsolver.class.getname()).log(level.severe, null, ex); } return "0"; } public static void main(string args[]){ system.out.println(new expsolver().solve(new java.util.scanner(system.in).nextline())); } } now want add codes parse mathematical functions such sin, cos, tan, ^ (power), log etc. program. best , code efficient solution that? have seen regex expressions unable on such large scale. how using expression parser of math.js , use via java scriptengine? here example: package org.mathjs; import java.io.ioexception; import java.io.inputstreamreader; import j

Aligning text in the horrizontally and vertically in the center in html/css -

this question has answer here: best way center <div> on page vertically , horizontally? 26 answers i needing vertically , horizontally align text center of nav div. provide both html , css down below. here html portion of code. <html> <head> </head> <title> dom chronicles </title> <body> <div id="header"> </div> <div id="space"> </div> <div id="nav"> <ul> <li>home</li> <li>music</li> <li>blog</li> <li>shop</li> <li>contact</li> </ul> </div> </body> </html> here css portion of code. @font-face { font-family: mager; src: url(fonts/elegantlux-mager.otf); } #header { width: 1000px; height: 400px; margin: 0 auto; background-color: gray; } #s

python - scipy.optimize.newton gives TypeError: 'float' object is not callable -

im new python , writing code finding roots of function: from scipy import optimize x = eval(raw_input()) #initial guess f = eval(raw_input()) # function evaluated f = eval(raw_input()) #derivative of function f round(optimize.newton(f, x, f, tol = 1.0e-9), 4) but interpreter returns: typeerror: 'float' object not callable i'm not sure im missing out code. can me out..thank in advance optimize.newton expects reference callable object (for example function). not mean give function string 'x*x' have define 1 first, like: def my_func (x): return x*x then can plug my_func optimize.newton (besides other required parameters).

c# - Understanding the WPF Dispatcher.BeginInvoke -

Image
i under impression dispatcher follow priority of operations queued , execute operations based on priority or order in operation added queue(if same priority) until told no case in case of wpf ui dispatcher . i told if operation on ui thread takes longer duration database read ui dispatcher simple tries execute next set of operations in queue. not come terms decided write sample wpf application contains button , 3 rectangles, on click of button, rectangles filled different colors. <stackpanel> <button x:name="fillcolors" width="100" height="100" content="fill colors" click="onfillcolorsclick"/> <textblock width="100" text="{binding order}"/> <rectangle x:name="rectangleone" margin="5" width="100" height="100" fill="{binding brushone}" /> <rectangle x:name="rectangletwo" margin="5" wi

apk - How to uninstall updates of an android system app through adb? -

so there's system app , i've sideloaded apk on top of it. possible through adb uninstall sideloaded apk , have system app running? i tried 2 methods failed. using 4.4 a. removed sideloaded app /data/app folder , rebooted. system app stayed in comatose state. b. did adb uninstall (success) , rebooted. same result. this convoluted approach did it. move system apk /system/priv-app/ /sdcard/ adb uninstall reboot move system app /sdcard/ /system/priv-app/ reboot my question is, there straightforward approach doing through adb? since installed same package (app) on top, adb package manager removed old system app (same package name). you can see list of current apps/pacakges adb shell pm list packages if have old .apk , can reinstall adb install -r <apk> again. http://developer.android.com/tools/help/adb.html if see failed version downgrade , try -d adb install -r -d <apk>

c++ How to istream struct contains vector -

how istream struct contains vector of integer member, tried following code failed read file struct ss{ std::vector<int> a; double b; double c; }; std::istream& operator>>(std::istream &is, ss &d) { int x; while (is >> x) d.a.push_back(x); >> d.b; >> d.c; return is; } std::vector <std::vector<ss >> aarr; void scandata() { ifstream in; in.open(fileinp); std::string line; while (std::getline(in, line)) { std::stringstream v(line); ss s1; std::vector<ss > inner; while (v >> s1) inner.push_back(std::move(s1)); aarr.push_back(std::move(inner)); } } i did search similar problems not find one. the immediate problem here same condition terminates while loop prevents successive reads working. stream in error state. double values never read. actually, integer part of first double read i

visual studio 2010 - C# Xna 4.0 foreach loop 3d Model not loading -

i have tried making drawmodel method using foreach loops: void drawmodel(model model, vector3 modelposition) { foreach (modelmesh mesh in model.meshes) { foreach (basiceffect effect in mesh.effects) { effect.lightingenabled = true; effect.enabledefaultlighting(); effect.preferperpixellighting = true; effect.world = matrix.createtranslation(modelposition); effect.projection = cameraprojectionmatrix; effect.view = cameraviewmatrix; } mesh.draw(); } } any ideas on missing?

python - Try-clause containing multiple statements -

let's have following function/method, calculates bunch of stuff , sets lot variables/attributes: calc_and_set(obj). now call function several times different objects, , if 1 or more fails nothing should set @ all. i thought this: try: calc_and_set(obj1) calc_and_set(obj2) calc_and_set(obj3) except: pass but doesn't work. if instance error happens in third call function, first , second call have set variables. can think of "clean" way of doing want? solutions can think of rather ugly workarounds. i see few options here. a. have "reverse function", robust. if def calc_and_set(obj): obj.a = 'a' def unset(obj): if hasattr(obj, 'a'): del obj.a and try: calc_and_set(obj1) calc_and_set(obj2) except: unset(obj1) unset(obj2) notice, in case, unset doesn't care if calc_and_set completed or not. b. separate calc_and_set try_calc_and_set , testing if works, , set , won't throw

objective c - NSTimer stops when user goes to different view controller -

i have nstimer activated when user presses uibutton . leads method runs timer. timer runs when app running in background uiview animation stops when app pressed again , timer keeps running. whenever go uiviewcontroller timer stops , uilabel s revert state if timer isn't running. how can fix timer still running when user comes original view controller timer. - (ibaction)start:(id)sender { //when timer stopped! if([startstop.titlelabel.text isequaltostring:@"stop"]){ nslog(@"button stopped"); stoptime = [nsdate date]; //nsstring log of time accquired [timer invalidate]; timerisrunning = false; //format stop time nsuserdefaults nsdateformatter *savestoptime = [[nsdateformatter alloc] init]; [savestoptime setdateformat:@"hh:mm a"]; [savestoptime settimezone:[nstimezone localtimezone]]; nsstring *savestoptimestring = [savestoptime stringfromdate:stoptime]; //save stop time nsuserdefaults *saves