Posts

Showing posts from July, 2014

node.js - POST to express.js with 'Access-Control-Allow-Origin' -

i'm newbie node , express. can data server app fail on post. i have client side on " http://myapp.com " , node app on " http://myapp.com:34627 ". this node app: var express = require('express'), app = express(); var result = {}; app.configure(function() { app.use(express.json()); app.use(express.urlencoded()); }); app.set("jsonp callback", true); app.get('/get/users/:userid/:username',function(req,res) { var userid = req.params.userid; var username = req.params.username; result = { response: 'ok', url_userid: userid, url_username: username }; res.header('access-control-allow-origin','http://listasapp.in'); res.json(200,result); }); app.post('/post/user',function(req,res) { console.log( req.body ); result = { response: 'ok' }; res.jsonp(200,result); }); var server = app.listen(34627,function() {

html - alignment of navigation menu within td of table and no border -

i wondering haved failed so, that, navmenu within table in promo box , centered @ top of white space , no border on top center box/td/cell great important. <html> <head> <style> * { margin: 0px; padding: 0px; border: 0px; } #container { width: 100%; height: 1000px; max-width: 1440px; min-width: 1024px; margin: 0px auto; text-align: center; } .bigbox { height: 1000px; background-image: url(images/photos/landscape-1440.jpg); background-position: 50% 50%; } .promobox { width: 25%; height: 1000px; float: left; background-position: 50% 0%; margin: 0px; padding: 0px; vertical-align: top; } .promobox div { height: 200px; border-color: #fff; border-style: none; } div { text-align: center; position: relative; } div { position: absolute; bottom: 10px; right: 10px; color: #fff; text-shadow: 1px 1px 1px #000; } #pb1 {width: 25%; backgro

php - Javascript not working in AJAX response -

below code ajax response page. have added onclick event table row , written javascript code handle it. javascript code doesn't work.is wrong way of coding or there problem in code. suggest me simple solution <?php echo '<script type=\"text/javascript\"> function clicked(){ alert("i alert box!"); } </script>'; $q = $_get['q']; include 'db_connect.php'; $sql="select name,address,mobile,email,pan,tan client name = '$q'"; $sql_bill="select clientname,financialyear,receiptno,amount,ddate,type,chequeno,category billing clientname = '$q'"; $sql_total="select sum(amount) totalamount billing"; $result = mysql_query($sql); $result_bill = mysql_query($sql_bill); $result_total = mysql_query($sql_total); $total= mysql_fetch_array($result_total); echo "<h4><b>client details</b></h4><table align='center' border='2'>

symfony - Symfony2 - Need help on the following error when querying for tags -

having following error in doctrine query when trying find specific tag selected user. [semantical error] line 0, col 78 near 'tag blog.tags': error: class acme\demobundle\entity\blog has no association named tags can tell what's wrong query? (trying query tag selected in side bar brings posts related tag) repository public function getpostsbytags($tags) { $qb = $this->createquerybuilder('b'); $qb->select('b') ->join('b.tags', 'tag') ->where('b.tags ?', '%'.$tags.'%'); return $qb->getquery()->getresult(); } blog entity /** * @var string * * @orm\column(name="tags", type="text") */ private $tags; /** * set tags * * @param string $tags * @return blog */ public function settags($tags) { $this->tags = $tags; return $this; } /** * tags * * @return string */ public function gettags() { return $this->tags; }

Can jackson parser Object from json if I add or delete some field? -

in work, want use jackson in situation: { "student": { "name" : "hello", "id" : "stu_001" } } then, define class student: class student { public string name; public string id; //get , set methods } but, in case, json be: { "student": { "name" : "hello", "id" : "stu_001", "age" : "23" } } or: { "student": { "name" : "hello" } } all in all, want use jackson parser students data, when json add or delete filed, how can solve jackson? thank you~ oops! i search google, , find answer! use following code: ```objectmapper.configure(org.codehaus.jackson.map.deserializationconfig.feature.fail_on_unknown_properties, false);``` when add field original don't have, ignore field.when delete field, assign field "null".

android - Align author text on last line of quote if there's room, otherwise put it on new line -

Image
above example of output want. notice "by john" aligned right on last line of quote. if there's not enough space, author appear on new line, still right aligned. you have take 2 different textviews in case , give gravity="right" second one

java - MySQL - Hibernate does not create foreign key constraint -

i am, moving application derby mysql, , facing problem hibernate doesn't create foreign key constraints while creating tables. me mappings seems correct working fine derby. i using mysql server 5.6, , mysql5innodbdialect. verified in mysql workbench using show create table command table being created using innodb engine. mysql connector used - mysql-connector-java - 5.1.6 logs: 2014-04-21 12:38:29,820 error org.hibernate.tool.hbm2ddl.schemaexport - unsuccessful: alter table dependency_track add constraint fk25e3373737e62d9a foreign key (tool_id) references tool_master 2014-04-21 12:38:29,820 error org.hibernate.tool.hbm2ddl.schemaexport - cannot add foreign key constraint 2014-04-21 12:38:30,127 error org.hibernate.tool.hbm2ddl.schemaexport - unsuccessful: alter table dept_role add constraint fk7e895e3080d96d8 foreign key (department_id) references department 2014-04-21 12:38:30,128 error org.hibernate.tool.hbm2ddl.schemaexport - cannot add foreign key constraint pers

objective c - data not passing between view Controllers cannot solve -

i attempting pass string between 2 view controllers, first named detailcontroller , second videocontroller. connected button using push segue. "prepareforsegue" method being called, string returning null in videocontroller. have been stuck on problem ages , still cannot find solution. appreciated. detailcontroller.m prepareforsegue method - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender { nsstring *mystring=self.city.camera; nslog(@"%@", mystring); nsstring *see=@"what going on?"; nslog(@"%@", see); videocontroller *video= (videocontroller *) segue.destinationviewcontroller; video.cam= self.city.camera; } videocontroller.m #import "videocontroller.h" #import "city.h" #import "detailcontroller.h" #import "viewcontroller.h" @interface videocontroller () @end @implementation videocontroller @synthesize webview,city,cam; - (void)viewdidload { nss

plsql - The way oracle calculate mod(binary_float, 0) -

oracle document ( http://docs.oracle.com/cd/b19306_01/server.102/b14200/functions088.htm#i77996 ) says "mod returns remainder of n2 divided n1. returns n2 if n1 0.". got unexpected result (i thought should 1.1 got 0) when put binary_float in n2. sql> select mod(1.1,0), to_binary_float('1.1'), mod(to_binary_float('1.1'), 0) dual; mod(1.1,0) to_binary_float('1.1') mod(to_binary_float('1.1'),0) ---------- ---------------------- ----------------------------- 1.1 1.1e+000 0 does has idea? interesting. think has floor vs round used internally in calculations. for example, remainder function similar mod, except uses round instead of floor. example, return nan (not number): select remainder(to_binary_float(1.1), 0) dual output: nan whats more interesting can use nanvl function provide default value if nan returned (in case, mimic mod behavior , return 1.1), , return float

javascript - jQuery function not working when placed on .js separate file -

i have php file jquery function working properly (basically identifies every '.limitcharacters' elements, calculates width , height , makes stuff on them): $('.tablecontent').find('.limitcharacters').each(function(){ var percent = ((($(this).width()) / ( $(this).closest('div').width()))*100); if (percent > 95 || $(this).height() > 40){ $(this).css('white-space','nowrap').css('color','red'); $(this).parent().css('width', '85%').css('display','inline-block').css('overflow','hidden'); $(this).parents().eq(1).css('height','36px'); } }) but when try move separate .js file (which has many functions inside being called php file, , works properfly), in order call php file whenever need it, not work. how i've created on separate .js file: function limitcharacterswidth(actualwidth, actualhei

ASP.Net MVC 4 Manage Roles - Windows Authentication -

i have mvc 4 web application want implement sqlroleprovider , windows authentication it. after did search in google added sqlroleprovider tables in database running aspnet_regsql command in vs command prompt. added web.config : <authentication mode="windows" /> <rolemanager enabled="true"> <providers> <clear /> <add connectionstringname="portaldbcontext" applicationname="/" name="aspnetsqlroleprovider" type="system.web.security.sqlroleprovider" /> <add applicationname="/" name="aspnetwindowstokenroleprovider" type="system.web.security.windowstokenroleprovider" /> </providers> </rolemanager> now need know how can manage roles? mean how create/edit/delete roles , assign/un-assign users roles? should create these pages myself or there available may nuget ? i roll own. , has been years, not sure if supported anymore

bash - How to pass filename through variable to be read it by awk -

good day, i wondering how pass filename awk variable, in order awk read it. so far have done: echo file1 > aenumerar echo file2 >> aenumerar echo file3 >> aenumerar ae=`grep -c '' aenumerar` r=1 while [ $r -le $ae ]; lista=`awk "nr==$r {print $0}" aenumerar` aelist=`grep -c '' $lista` s=1 while [ $s -le $aelist ]; word=`awk -v var=$s 'nr==var {print $1}' $lista` echo $word let "s = s + 1" done let "r = r + 1" done thanks in advance clue or other simple way bash command line instead of: awk "nr==$r {print $0}" aenumerar you need use: awk -v r="$r" 'nr==r' aenumerar

php - Echo out user information in the same table to their page base on their store information without echoing out the same information to another user -

first of stored users in same table , created page called welcome.php, want echoing out user info mysql based on entry. now when created first user , echo out welcome.php, comes out table, , if create user info in same table echo out @ same welcome.php based on user login info such as, if create user called john fred etc , user called michael kenneth etc. so user john fred comes out welcome.php information same table, , user michael kenneth doesn't come welcome.php when sign user michael kenneth instead shows user john fred. don't know error comes from; maybe login.php, or welcome.php. here code echoing in welcome.php <?php $tnumber2 = "{$_session['tnumber2']}"; // connect database $db = mysql_connect("$sname","$uname","$pname") or die("could not connect database."); $select = mysql_select_db("$dname") or die("could not select database."); $sql="select * `$tname` limit 0, 2

android - Extract image from URL using Jsoup -

i tried extract image other websites following code , had no problems, them tried other website , nothing happend. no image came up. protected void doinbackground(void... params) { try { // connect web site document document = jsoup.connect(https://www.indiegogo.com/project/spy-cam-peek-i/embedded).get(); // using elements class data elements img = document.select("div.i-project-card i-embedded img[src]"); // locate src attribute string imgsrc = img.attr("src"); //download image url inputstream input = new java.net.url(imgsrc).openstream(); // decode bitmap bitmap = bitmapfactory.decodestream(input); } catch (ioexception e) { e.printstacktrace(); } return null; } finally y managed grab image. the image src inside div under attribute data-src this (<)div class="image"

ruby on rails - Why isn't #truncate including the given block as in the example? -

according documentation, #truncate can accept block, not including it! http://api.rubyonrails.org/classes/actionview/helpers/texthelper.html#method-i-truncate 2.0.0p247 :310 > helper.truncate("once upon time in world far far away") { link_to "continue", "#" } => "once upon time in world..." how include block truncate? rails 3.2.14. i think block part new in rails 4.0. http://apidock.com/rails/v3.2.13/actionview/helpers/texthelper/truncate it looks sort of thing helper.truncate("once upon time in world far far away", :omission => link_to("continue", "#"))

google analytics - New users vs active users in Measurement protocol -

how google analytics measure active users vs. new users in measurement protocol . how measure new users? , based on ipaddress ? send same cid=555 requests. in website see uses cookies though thank you cid stands client-id = random number generated google analytics when come website first time. can grab (even gtm) , use measurement protocol. if use client-id ga can recognize, stitch data (campaign source/medium) etc. if use new 1 (like '555' mentioned), see incoming measurement protocol request request new user. be smart though use cid -- key that's vital pairing information might have visitors.

ruby on rails 4 - Devise: Don't redirect on password reset if already logged in -

if user logged in , clicks on password reset link email, automatically redirected logged in area. want user able reset password, logged in or not. how prevent redirect? what trying is, use devise recoverable module change logged in user password. not recoverable module built for. as per carlosantoniodasilva , collaborator of devise this feature recovering passwords, not signed in users change passwords. if want that, can use registerable module or handle yourself. registerable module handles signing users through registration process, allowing them edit , destroy account.

android - Can't implement adMob AdListener Class -

im getting error: - type adlistener cannot superinterface of admanager; superinterface must interface when im trying implement admob adlistener on app: import com.google.android.gms.ads.adlistener; public class admanager implements adlistener{ what doing wrong? according new sdk (google play services) you no longer implement adlistener activity or class.. you can use inner class: adview.setadlistener(new adlistener() { public void onadloaded() {} public void onadfailedtoload(int errorcode) {} // implement methods need. }); (taken from: https://developers.google.com/mobile-ads-sdk/docs/admob/play-migration )

internationalization - Localize javascript arithmetic operators -

i have multilingual application "language" localized in terms of page content. forms using simple arithmetic calculate field values based upon user input. so 1.1*2 = 2.2 works in romanian fraction written 1,1 calculation becomes 1,1*2 = 2,2 fails nan. so do? update: thousands separators issue. @ yui-library yui data types which has both parse , format functionality. seems "easiest" in terms of specifying separators i'm "only" looking @ 4 different languages. though poses issue https since application serving https , yahoo cdn not support have self host , roll own bundling. would unformat function of library numeral.js work? http://numeraljs.com/

database - SQL : Column check constraint cannot reference other columns. (for different tables) -

i have 2 tables: t1(a,b) where create table t1( char(2) not null primary key check(t1.a not in t2.b), b char(2) unique ); t2(c,b) where create table t2( c number(2) primary key, b char(2) unique references t1 check(t1.b not in t1.a) ); here, t2.b references t1.a . my question how can put check constraint t1.a , t1.b such values allowed t1.a different allowed t2.b ? the knapsack problem in worst case needs verify subsets of given knapsack determine best combination put in knapsack hence worst case performance using backtracking evaluates valid combinations o(2^n) no of subsets of given set of n items. hence has exponential time complexity.

ruby on rails - Authenticate user and admin separately -

class applicationcontroller < actioncontroller::base protect_from_forgery skip_before_filter :authenticate_user! , :only => ["welcome#index"] # before_filter :authenticate_user! :except => ["welocme#index"] def after_sign_in_path_for(user) # user_dashboard_index_path user_dashboard_index_path end def after_sign_out_path_for(user) welcome_index_path end after_filter :authenticate_admin! def after_sign_in_path_for(admin) admin_dashboard_index_path end def after_sign_out_path_for(admin) welcome_index_path end end admin should not access users dashboard , user should not access admin dashboard. how can achieve this? i have done in project: protect_from_forgery with: :exception def after_sign_in_path_for(resource) if user_signed_in? user_dashboard_index_path elsif admin_signed_in? admin_dashboard_index_path else xyz_path end end same sign-out: def after_

python - Simple for loop explanation -

why code... alist = ['cat','dog','cow'] item in alist: print alist output ['cat', 'dog', 'cow'] ['cat', 'dog', 'cow'] ['cat', 'dog', 'cow'] while changing print alist item outputs: cat dog cow i understand when printing alist print list many times there elements in list guess don't understand why different. i grateful if explain difference me or point me in right direction. you have list - contains cat, dog, , cow. then say: each thing in list, print list. you have 3 things in list (cat, dog, , cow) list gets printed 3 times. when switch statement print item instead of print alist saying each thing in list print thing - each thing in list gets printed, ie cat, dog, cow.

codeigniter - CI Form validaion returns false but validaion_errors() is blank -

my code : public function add() { if ($this->input->post()) { //echo '<pre>';print_r($this->input->post());exit; $this->form_validation->set_rules('agency[title]','title','required'); $this->form_validation->set_rules('agency[first_name]','first name','trim|required|min_length[3]'); $this->form_validation->set_rules('agency[last_name]','last name','trim|required|min_length[3]'); $this->form_validation->set_rules('agency[email]','email','trim|required|valid_email|is_unique[agency.email]'); $this->form_validation->set_rules('password','password','trim|required|min_length[3]'); $this->form_validation->set_rules('conf_password','confirm password','required|matches[password]');

matlab - Finding the area of some specific graph color in a 3D graph -

Image
i have graph (and raw data) shown below. the axis in graph in cm. want know area of deep blue area in graph (the answer should 20 sq.cm. or that). there way find it? if you're sure literally mean deepest shade of blue, corresponds minimum of data. can find minval = min(mydata(:)); . once have minimum value, select points equal value minvals = mydata == minval; . note collect elements equal deepest blue, in floating point sense. if didn't literally mean deepest shade of blue, might want consider selecting points within threshold of minimum value instead. count them total = sum(minvals(:)); . then multiply number of points value representing area of each point in cm2.

haskell - UndecidableInstances and newtypes -

i have undecidableinstances problem haven't been able figure out how avoid using newtype . here's had originally: {-# language typefamilies, flexiblecontexts #-} class record r key :: r -> string class (record r) => sizedrecord r size :: r -> int class database d type dbrecord d class (record a) => agent agentid :: -> string agentid = key class (database (uagentdb u), agent (uagent u), record (uagent u)) => universe u type uagent u type uagentdb u -- plus other stuff data simpleuniverse d = simpleuniverse { sudb :: d -- plus other stuff } deriving (show, eq) instance (record (dbrecord d)) => universe (simpleuniverse d) -- line 28 type uagent (simpleuniverse d) = dbrecord d type uagentdb (simpleuniverse d) = d -- plus other stuff the message is amy9.hs:28:10: constraint no smaller instance head in constraint: record (dbrecord d) (use -xundecidableinstances permit this) in instance de

c++ - How to make my application DPI-aware? -

when user sets dpi scaling draw fonts , windows larger in displays, don't want application affected (i don't want application's fonts , controls larger) i tried use setprocessdpiaware() function or add manifest file, didn't work. how can prevent windows (xp, 7 , 8) change application's font size? you're asking wrong question. want dpi-independent. answer size in points, , relative in ems. avoid dpi , pixels completely.

javascript - Chrome extension Content Security Policy directive error -

i'm trying make radio stream chrome extension there problem. when run script in browser normal js+html+css works, when try runing chrome extension error: refused execute inline script because violates following content security policy directive: "script-src 'self' chrome-extension-resource:". either 'unsafe-inline' keyword, hash ('sha256-...'), or nonce ('nonce-...') required enable inline execution. after added manifest: "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'" but after getting error message(error in manifest line code above) this manifest: { "background": { "scripts": [ "jquery.js", "jquery-ui.js", "plate.js" ] }, "browser_action": { "default_icon": "images/action-normal.png", "default_popup": "player

mysql - java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) -

after validation of select combo box have selected not able insert in database. tomcat gives following error java.sql.sqlexception: parameter index out of range (1 > number of parameters, 0). how caused , how can solve it? you error when call of setxxx() methods on preparedstatement , while sql query string not have placeholders ? this. for example wrong : string sql = "insert tablename (col1, col2, col3) values (val1, val2, val3)"; // ... preparedstatement = connection.preparestatement(sql); preparedstatement.setstring(1, val1); // fail. preparedstatement.setstring(2, val2); preparedstatement.setstring(3, val3); you need fix sql query string accordingly specify placeholders. string sql = "insert tablename (col1, col2, col3) values (?, ?, ?)"; // ... preparedstatement = connection.preparestatement(sql); preparedstatement.setstring(1, val1); preparedstatement.setstring(2, val2); preparedstatement.setstring(3, val3); note parameter i

PHP Recordset Paging, changing url Parameter -

bit of newby php & mysql, , use dreamweavers inbuilt functions, trying hands dirty , understand things little more , subsequently fix couple of problems. i have file (search.php) when viewed has 2 url parameters ' letter ' , ' search ' 'search.php?letter=a&search=no' within body of page, have recordset paging function (from dreamweaver). when using paging, end url similar this 'search.php?pagenum_results_empty=1&totalrows_results_empty=2937&letter=a&search=no' very want change parameter ' search ' ' no ' ' yes '. can work out, need remove ' search=no ' query string, , add ' search=yes ' link. i'm not not able remove query string, or barking wrong tree. any advice gratefully received php code $issearch = $_get['search']; $querystring_results_empty = ""; if (!empty($_server['query_string'])) { $params = explode("&", $_server['que

android - how to show other application inside my main xml? -

how show other activity inside activity idea how that? want show other activity inside main layout , take 50% of screen not show on full screen idea??? string packagename = "com.mobile_banking"; // must know package name intent = new intent(intent.action_main); packagemanager manager = getpackagemanager(); = manager.getlaunchintentforpackage(packagename); startactivity(i); with activity, can't show 2 activities in single one. what looking fragmentactivity , fragments custom sizes in it. first learn fragments , fragmentactivity once learn basics, can follow these links: android 2 fragments in same activity how implement 2 fragments in single view?

Check if selected dropdown value is empty using jQuery -

here dropdown in question: <select name="data" class="autotime" id="eventstarttimemin"> <option value=""></option> <option value="00">00</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> what want check if current value empty: if ($("eventstarttimemin").val() === "") { // ... } but not work, though value empty. appreciated. you forgot # on id selector: if ($("#eventstarttimemin").val() === "") { // ... }

winapi - How to get a user input on a MessageBox on C++? -

i have application on c++ (on windows api) , ask user approve task using messagebox. however, it's bit sensible task , nobody reads message, want change have input box , user type "i agree". does know simple way that? find dialogboxparam() can it, it's overkilling needs, can think on more simple (or simple way use it)? i found prompting user input box? [c++] quite similar question, there no satisfactory answer me (using lib not option). you have write own dialog that. messagebox , related apis not offer such functionality. use task dialog api (introduced in vista) show dialog box button having customised caption. might little better plain messagebox limited set of buttons. i'm little cynical trying achieve in case. if force users type i agree ignore content of dialog box , type ask them type. the difference in outcome between typing dialog , standard button press dialog user take longer past dialog, , dislike software, still not have read

php - Trouble with password verification with salt/password/hash -

i've got 1 function create new user generating salt, appending password, , hashing combination. i've got function user login verification, takes user's entered password , adds user's unique salt, hashes, , compares encrypted password in database (see comments throughout code). i've echoed out important variables in uservalidate() function, can never hash+user password match encrypted password database. can tell me i'm doing wrong? create user function: function createnewuser($firstname, $lastname, $email, $password, $address, $city, $state) { $conn = connectpdo(); // create salt $salt = mcrypt_create_iv(64, mcrypt_dev_urandom); // add salt password $salted_password = $salt.$password; // hash salt/password combination, added "password" column of database $encrypted_password = hash('sha256', $salted_password); $datetime = date("y-m-d h:i:s"); $stmt = $conn->prepare("insert user

sql - sqlException (0x80131904) The name'...' is not a valid identifier -

i have stored procedure dynamic based on database needs access. running procedure program gives me error: system.data.sqlclient.sqlexception (0x80131904): name '...' not valid identifier..... when run stored procedure ssms, same error, if print instead of exec, run code manually, works fine. declare @sql varchar(8000) if @provider='' set @sql = ' update ' + @linkserver + '.dbo.[billing header] set [bill primary]=1 billing in( select distinct billing ' + @linkserver + '.dbo.[history detail] ' + @wheredatefacility + ' , [insurance code] = rtrim( '''+ @primarycode +''')); select @@rowcount rc;' else set @sql = ' update ' + @linkserver + '.dbo.[billing header] set [bill primary]=1 billing in( select distinct hd.billing ' + @linkserver + '.dbo.[history detail] hd inner join ' + @linkserver + '.dbo.[billing header] bh on bh.billing=hd.bi

animate not working-JQuery -

am doing wrong simple animate not work? fiddle $('#my_btn').click(function(){ alert('clicked'); $("#my_txt").animate({left:'350px'}); }); thanks an element must have position other default static top , left have effect #my_txt {position: relative; } fiddle preferably have initial left style set well #my_txt { position: relative; left : 0; }

How to store and get a pointer reference in a global scope in GO -

i have got follow code: package main func main() { // create pointer referece of session of mongo db session := mongodb.createsession() // question 1 : how store pointer reference in global scope , using anywhere of code defer session.close() // note suppose code call handler methods call process in package controller(the last 1 code) } code of creating session of mongodb package mongodb func createsession() *mgo.session { session, err := mgo.dial("192.168.0.108:27017/databasename") if err != nil { panic(err) } session.setmode(mgo.monotonic, true) return session } place want use pointer reference store in main package controller func process() { // question 2 : how can pointer reference store in question 1 if posible collection := mongodb.createcollection(session, "namedatabase", "colectiondata") mongodb.insertdata(collection, "ale", "45646565") } the idea avoid passing reference ses

java - Balance Check if brackets are closed in a string using stacks -

i writing program check see if sets of brackets closed in user-inputed string, confused how because need use stacks accomplish it. my idea add brackets stack if exist, if closing bracket shows up, pop off top 2 characters stack , if second popped off character matches first (as in type of bracket matches , both opening , closing bracket) line balanced. however, need have able work strings multiple brackets , characters in them, example: wfsfs[{{{(s;dkls(dslkf)s;dlkf}]}]}}}sd i confused how make work using stacks! ideas? here code came far doesn't work multiple brackets (int = 0; < x.length(); i++){ if (x.charat(i) == '('){ stack.push('('); } if (x.charat(i) == '['){ stack.push('('); } if (x.charat(i) == '{'){ stack.push('('); } if (x.charat(i) == ')'){ stack.pop(); if (stack.em

javascript - Syntax error when trying to test for empty string -

in javascript, trying simple task of testing , returning longest of 2 words. if words empty return should "empty string". keep getting syntax error when testing empty string or elseif statement. using (!word1) , (!word2) because understanding in javascript boolean statement , should false. please tell me going wrong: function longest(word1, word2) { if (word1.length >= word2.length) { return (word1); } else { return (word2); } else if (!word1) || (!word2) { return "an empty string"; } } console.log(longest('hi')); if conditions should surrounded 1 pair of parentheses. change else if (!word1) || (!word2) else if (!word1 || !word2) .

python 2.7 - Why does this runs twice? -

i made program runs using systrayicon and thou works fine, every time checks something, twice. can fix reducing chance half, that's shortcut not proper fix. from systray import systrayicon random import randint def shutprogram(systrayicon): = getsomething() while true: if getsomething() != : = getsomething() if randint(0,100) <= 10: print "stop, hammer time!" stopthis() else: print "you may pass" menu = (('start', icon.next(), shutprogram),) systrayicon(icon.next(),"shut program",menu) oh, got. when tried 'getsomething', had wait bit because had delay prompted returning string 'wait, getting info'.

javascript - PersistJS the call back function is not working -

i have found library handle client storage, latest version found here https://github.com/jeremydurham/persist-js but 1 thing not work call function var result = store.get('saved_data', function (ok, val) { console.log(ok, val); }); i retrieve result except call function not working. 1 appreciated. there no callback persistjs. use result needed.

node.js - Error on installing Zombie package in nodejs -

my requirements scrape third party https websites posting details. clicking button using nodejs. i found client side event handling can achieved using zombie package in node. have followed steps in https://www.npmjs.org/package/zombie by existing command "npm install zombie" getting below error, not install zombie package successfully. any suggestion on this,,,,,,,,,, npm http https://registry.npmjs.org/zombie npm http 304 https://registry.npmjs.org/zombie npm http https://registry.npmjs.org/eventsource npm http https://registry.npmjs.org/encoding npm http https://registry.npmjs.org/jsdom npm http https://registry.npmjs.org/html5 npm http https://registry.npmjs.org/q npm http https://registry.npmjs.org/ms npm http https://registry.npmjs.org/request npm http https://registry.npmjs.org/ws npm http https://registry.npmjs.org/mime npm http https://registry.npmjs.org/tough-cookie npm http 200 https://registry.npmjs.org/eventsource npm http https://registry.npmjs.org/ev

node.js - How mongodb connection works on concurrent requests in NodeJS express server? -

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

Jasper plugin in Grails: org.hibernate.LazyInitializationException: could not initialize proxy - no Session -

i trying generate report in doc format using jasper plugin, exception generated at: jasperreportdef report = jasperservice.buildreportdefinition(params, request.getlocale(), result) line in controller exception: could not initialize proxy - no session. stacktrace follows: org.hibernate.lazyinitializationexception: not initialize proxy - no session @ org.apache.commons.beanutils.propertyutilsbean.invokemethod(propertyutilsbean.java:2170) @ org.apache.commons.beanutils.propertyutilsbean.getsimpleproperty(propertyutilsbean.java:1332) @ org.apache.commons.beanutils.propertyutilsbean.getnestedproperty(propertyutilsbean.java:770) @ org.apache.commons.beanutils.propertyutilsbean.getproperty(propertyutilsbean.java:846) @ org.apache.commons.beanutils.propertyutils.getproperty(propertyutils.java:426) @ net.sf.jasperreports.engine.data.jrabstractbeandatasource.getbeanproperty(jrabstractbeandatasource.java:111) @ net.sf.jasperreports.engine.data.jrabstractbeandatasource.getfieldvalu

html - Android: How to show only one class from website in webview in android -

webviewclient yourwebclient = new webviewclient() { @override public boolean shouldoverrideurlloading(webview view, string url) { view.loadurl(url); return false; } @override public void onpagefinished(webview view, string url) { webview.loadurl("javascript:document.getelementbyclassname('storytieup');"); } }; webview = (webview) findviewbyid( r.id.browser ); webview.getsettings().setjavascriptenabled(true); webview.getsettings().setsupportzoom(true); webview.getsettings().setbuiltinzoomcontrols(true); webview.setwebviewclient(yourwebclient); webview.loadurl("http://stars.nhl.com/club/newsindex.htm"); this webviewclient code want display div contents class name 'storytieup', when run code shows whole website contents, need 1 div show in webview, use jsoup in portions here don't want use jsoup because of reasons, there solution display 1 div class name, in advance

See object changes in post_save in django rest framework -

i curious if there way see has changed on object after saving using django rest framework. have special behavior need check if field has been changed original value hoping handle using post_save on generics.retrieveupdatedestroyapiview . my first thought check using pre_save seems pre_save 's object argument has changes applied it. old answer django rest framework version 2.3.12: to check if has changed on update, have compare unchanged model instance self.object changed model instance serializer.object. the object argument passed pre_save method serializer.object not yet saved in database new changes. the unchanged model instance self.object has been fetched database using self.get_object_or_none(). compare obj argument in pre_save method. def pre_save(self,obj): unchanged_instance = self.object changed_instance = obj ..... # comparison code new answer django rest framework 3.3: pre_save , post_save no longer valid http://www.django-rest-f

Java Lambda Iteration List from JPA -

this question has answer here: why stream return no element? 1 answer i found strange behaviour when using lambda jpa, seems java 8 lambda don't iterate when list object. for example: list<myobject> list = anotherobject.getmyobjectlist(); // list list.foreach(myobject -> system.out.println("not printed")); system.out.println("size?: " + list.size()); // print size = 2 i try list.stream().foreach() same results.. after hours of testing found trick list<myobject> copylist = new arraylist<>(list); // copy list copylist.foreach(myobject -> system.out.println("omg printed!")); huh? ideas?, bug? or im doing wrong? entity clases working good, relations good... :) thanks in advance :). it know concrete class of list returned anotherobject.getmyobjectlist() . may have bug i

c# - Removing duplicates from datatable -

i'm trying remove duplicates in datatable similar this question . however, when need on ordered dataset, 1 of criteria time 1 of columns, , need earliest time instance remain. i came across question on ordered lists datatable , i'm not sure how combine two. basically, i'm reading file dataset, want sort on time , 3 other columns, , delete duplicates leaving earliest time instance. columns in question name (int), phone number (long), time (int) , location (string). if name, phone , location duplicated, remove after first (earliest) time. dsholdingset.tables["filedata"].columns.add("location", typeof(string)); dsholdingset.tables["filedata"].columns.add("name", typeof(int)); dsholdingset.tables["filedata"].columns.add("field", typeof(string)); dsholdingset.tables["filedata"].columns.add("time", typeof(int)); dsholdingset.tables["filedata"].columns.add("phone", typeof(