Posts

Showing posts from May, 2011

winapi - Efficient Win32 Kernel Objects to be preferred over c++ -

as c++ programmer try stick standard , if that's not possible try use boost or other portable lib. in all, write portable code. now, windows sdk give access kernel objects lead faster code part of optimization. know kernel objects use efficiency? one example critical_section 1 believe default choice mutex on windows when using boost::threads or c++11 concurrency. sticking intra-process concurrency, of course. let's leave out gui programming now. qt enough. generally kernel objects not going more efficient. take more ram , using them requires expensive context switch. critical sections hybrids, try stay in user-mode , create kernel-mode semaphore if absolutely needed. your c++ standard library loosely wrapping whatever efficient method platform is. benchmark first.

cdi - cannot inject (@EJB) ejb using its superclass -

i learning both cdi , ejb. looking @ weld's explanation of cdi ( http://docs.jboss.org/weld/reference/latest/en-us/html/beanscdi.html ), states the unrestricted set of bean types session bean contains local interfaces of bean , superinterfaces. if session bean has bean class local view, unrestricted set of bean types contains bean class , superclasses. in addition, java.lang.object bean type of every session bean. remote interfaces not included in set of bean types. i trying test particular part the unrestricted set of bean types contains bean class , superclasses so have created 2 ejbs: referencedejb extends dummyparent , mainejb has reference ejb dummyparent.java package com.etm.ejbtest; public abstract class dummyparent { public dummyparent() { } public void sayhi() { system.out.println("hi!"); } } referencedejb.java package com.etm.ejbtest; import javax.annotation.postconstruct; import javax.ejb.singleton; import

c# - How to change the value of an asp:textbox from javascript -

i have asp:textbox <asp:textbox id="newname" runat="server" /> and when user clicks "cancel" button, want erase whatever in text box making value "". if input field of type text, in javascript: document.getelementbyid('newname').value= ""; but can't because asp:textbox. when asp:textbox rendered ui, yes, input field of type text. part may issue id, can set using clientidmode: <asp:textbox id="newname" runat="server" clientidmode="static" /> renders to: <input type="text" id="newname" /> and javascript use should work perfectly.

how to kill uWSGI process -

so have gotten nginx + uwsgi running django install however problem having when make changes code need restart uwsgi process view changes i feel running correct command here (i new linux btw): uwsgi --stop /var/run/uwsgi.pid uwsgi --reload /var/run/uwsgi.pid i no error when run these commands old code still loads i know not coding issue because ran django app in development server , ran fine the recommended way signal reloading of application data use --touch-reload option. sample syntax on .ini fine is: touch-reload /var/run/uwsgi/app/myapp/reload where myapp is application name. /var/run/uwsgi/app recommended place such files (could anywhere). reload file empty file timestamp watched uwsgi, whenever changes (by, example, using touch ) uwsgi detects change , restarts corresponding uwsgi application instance. so, whenever update code should touch file in order update in-memory version of application. example, on bash: sudo touch /var/run/uwsgi/app/myap

Azure - customErrors="off" in web.config is not displaying detailed errors in Azure app (cloud service) -

Image
i have app deployed azure , uses adfs (active directory federated services) authentication. when user tries navigate app on azure, redirects user adfs authentication page. user enters credentials , clicks ok, , adfs redirects user landing page of app. everything working fine point. i'm getting generic server error on app once user hits landing page. problem: need see detailed errors. try setting <customerrors="off" /> , repackage app , redeploy, doesn't give me detailed errors: here's i've tried: i've tried packaging app in debug mode (after release mode didn't work), i've edited both web.config's (in root of solution, in views folder, cover bases). nothing worked. what doing wrong? a couple of things try: are sure customererrors attribute set correctly? identity , access tooling in visual studio seems reset "off" (every time update via tool). are able connect role instance via remote desktop

switch statement - Can someone explain switching in Objective C -

i started learning objective c , don't understand switches. can please explain them me? thanks a switch statement meant used in place of if else statements for example int =4; if(a == 1) dosomething(); else if(a == 2) dosomethingelse(); else if(a == 3) blah(); else caseunaccountedfor(); is equivalent to int =4; switch(a) { case 1: dosomething(); break; case 2: dosomethingelse(); break; case 3: blah(); break; default: caseunaccountedfor(); break; } if 1 of cases match, switch statement not automatically exited why there's break statement @ end of each case. case 'default' matches every other case besides ones explicitly list.

javascript - Calling fnGetPosition on datatables.net throws "Cannot call method 'toUpperCase' of undefined" error -

i trying position of row in datatables using following code var table = $('#userinformationtable').datatable(); var row_id = table.fngetposition($('#row_' + id)); table.fndeleterow(row_id); the $('#row_' + id) returning tr. the fngetposition not work. getting error: typeerror: cannot call method 'touppercase' of undefined what doing wrong? table.fngetposition(); expects dom node , you're passing jquery object. change from: table.fngetposition($('#row_' + id)); to table.fngetposition($('#row_' + id)[0]);

Creating a hash from two arrays with identical values in Ruby -

i'm having issues creating hash 2 arrays when values identical in 1 of arrays. e.g. names = ["test1", "test2"] numbers = ["1", "2"] hash[names.zip(numbers)] works gives me need => {"test1"=>"1", "test2"=>"2"} however if values in "names" identical doesn't work correctly names = ["test1", "test1"] numbers = ["1", "2"] hash[names.zip(numbers)] shows {"test1"=>"2"} expect result {"test1"=>"1", "test1"=>"2"} any appreciated hashes can't have duplicate keys. ever. if permitted, how access "2"? if write myhash["test1"] , value expect? rather, if expect have several values under 1 key, make hash of arrays. names = ["test1", "test1", "test2"] numbers = ["1", "2", "3"

Objective-C header parsing -

i need parsing of objective-c headers. i've tried using doxygen , parsing xml output, doesn't support objective c headers without comments (it chokes on macros defined in properties, check doxygen not recognizing properties ) i've tried using appledoc , xml output not complete enough (for example, there no information of inheritance classes) , has same problem macros on properties. i've tried parsing output of library objective c metadata (using otool ), noticed metadata doesn't keep types on methods (so method:(id)param:(id) ) does know tool want? i'm suspecting clang me, far -ast-dump , similar options tries generate ast source don't have (only headers). you may able use libclang. libclang programmatic interface designed implementing tools syntax highlighting , code completion. clang -ast-dump works me. (note -ast-dump not supported driver, have work pass flags driver handles. can use clang -### ... see driver doing.) % clang

jquery - Remove a li from listview on splitbutton click with popup -

i know how remove list item listview on split-button click can see here: jsfiddle code: $('#produsele').children('li').on('click', function () { var selected_index = $(this).index(); $(this).closest('li').remove() //alert('selected index = ' + selected_index); }); but want able after popup asks if sure want delete it, in jsfiddle the html <div data-role="page" id="produsele"> <ul id="listaprod" data-role="listview" data-split-icon="delete" data-split-theme="d" data-inset="true"> <li><a href="#"> <img src="images/pic1.jpg" /> <h2>first product</h2> <p>description</p></a> <a href="#sterge" data-rel="popup" data-position-to="window" data-transition="p

asp.net mvc - I'm not getting friendly url in a form with GET method -

i setup route that: routes.maproute( name: "pesquisar", url: "pesquisar/{aaa}/{bbb}/{id}", defaults: new { controller = "home", action = "pesquisar", aaa = urlparameter.optional, bbb = urlparameter.optional, id = urlparameter.optional } ); when press send button in form (with method) url that: http://localhost:00000/pesquisar?aaa=one&bbb=two but expecting for: http://localhost:00000/pesquisar/one/two when map rout, adds end of list. when router looks rule match, starts @ begining of list , itterates through it. take first rule matches, not specific rule. because natural append code end, default rule (which works everything) @ start. try re-ordering code this: ///the specific rout want use routes.maproute( name: "pesquisar", url: "{action}/{aaa}/{bbb}/{id}", defaults: new { controlle

javascript - Changing useragent if ipad -

what want detect if user using ipad, change useragent iphone. want ensure page detects change before page load.. i've tried doing no luck. <script type="text/javascript"> var navigator = new object; var useragent = httpcontext.current.request.useragent.tolower(); if (useragent.contains("ipad;")) { navigator.useragent = 'iphone'; } </script> the useragent readonly can not set anything. you using httpcontext.current.request.useragent.tolower(); not valid javascript. c# browser can not execute. instead @ navigator.useragent var nav = ''; if (navigator.useragent.indexof('ipad') != -1) { nav = 'its ipad'; } else { nav = 'its other device'; } console.log(nav);

php - Wordpress portfolio page display only images from certain filter -

i have been following many tutorials on portfolio uses quicksand.js filter animation. in function can create filters (categories) slugs. can't, after endless hour of reading, figure out how display thumbnails filter. i've included parts of portfolio functions.php i know lot of code, last resort. can't working hoping php / wordpress guru might point out i've missed. through reading on it, did managed pull out featured images posted in 'featured' using: <?php $args = array( 'post_type' => 'portfolio', 'tax_query' => array( array( 'taxonomy' => 'filter', 'field' => 'slug', 'terms' => 'featured' ) ) ); $query = new wp_query( $args ); ?> however, pulls out image , it's title, without formatted html need. applying use lost. thanks in advance. my index.php h2>featured work</h2> &

php - Username without Email Extension in PHPMailer -

i want use university email server send/receive emails project hosts on our university server. have true username , password email. example: our login username "xxxxxx" email address "xxxxxx@metu.edu.tr" on squirrelmail. username has no email extension. can login , see emails using these credentials: username: xxxxxx password: yyyyyy now set phpmailer settings that: define('smtp_host', 'mail.metu.edu.tr'); define('smtp_port', '587'); define('smtp_secure', 'tls'); define('smtp_user', 'xxxxxx@metu.edu.tr'); define('smtp_password', 'yyyyyy'); here phpmailer error: smtp -> error: password not accepted server: 535 5.7.8 error: authentication failed: authentication failure smtp -> server:250 2.0.0 ok smtp error: not authenticate. all settings correct. password correct too. because can send email myself using hosting username "x

c# - asp.net integrate facebook login -

hi using facebook login authenticate in local application.but @ last when click on facebook image shows error: given url not allowed application configuration.: 1 or more of given urls not allowed app's settings. must match website url or canvas url, or domain must subdomain of 1 of app's domains. i know domain name error have set in facebook aap url , site url. i have set same url in iis , facebook app .still got error. here code: <html> <head> <title>facebook login authentication example</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <script> // load sdk asynchronously (function (d) { var js, id = 'facebook-jssdk', ref = d.getelementsbytagname('script')[0]; if (d.getelementbyid(id)) { return; } js = d.createelement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.

php mysql 4 tables join -

i have 4 tables, in table's 'tbl_order' has single record of each cusotmer. in table's 'tbl_orderdetail' there more 1 services (records) of each customer. in table's 'tbl_services' there more 10 pre-define services. inch table's 'tbl_users' there customer's basic information. my question : how can fetch data each customer using php mysql. tables details below: tbl_order: order_id,order_type,order_date,time,customer_id,booking_type,booking_status,order_no,car_no,booking_date tbl_orderdetail: id,order_id,service_id tbl_services : service_id,s_name,s_price tbl_users : customer_id ,user_name you can join 4 tables using primary key of 1 table forign key of other table , @ of query use order user_name

java - Hibernate Search behaves differently between DEV and PROD with same databse -

i have 1 domain object needs indexed hibernate search. when fulltextquery on object on dev machine, expected results. deploy app war , explode prod server (a vps). when perform same "search" on prod machine, don't expected results @ (it seems results missing). i've run luke ensure indexed, , appears should be... i'm new hibernate search, appreciated. here's domain object: package com.chatter.domain; import javax.persistence.cascadetype; import javax.persistence.column; import javax.persistence.entity; import javax.persistence.fetchtype; import javax.persistence.generatedvalue; import javax.persistence.generationtype; import javax.persistence.id; import javax.persistence.joincolumn; import javax.persistence.manytoone; import javax.persistence.table; import org.apache.solr.analysis.lowercasefilterfactory; import org.apache.solr.analysis.snowballporterfilterfactory; import org.apache.solr.analysis.standardtokenizerfactory; import org.hibernate.sear

python, perl socket blocking difference when reading data from it? -

in perl, can do socket(server, pf_inet, sock_stream, getprotobyname('tcp')); bind(server, $my_addr); listen(server, somaxconn); $client_address = accept(client, server); $line = <client>; # read until newline or eof print $line when access via browser $line = <client> return , print without blocking. if i'm trying same in python following from socket import * host = "" port = 9000 address = (host, port) server = socket(af_inet, sock_stream) server.bind(address) server.listen(somaxconn) client, addr = server.accept() client_fd = client.makefile() data = client_fd.readlines() print data client_fd.readlines() blocking unless kill request in browser. there way around this? , why <client> in perl not blocking? your (updated) perl example reading one line client; python 1 reading all lines of input client, until socket closed. , client doesn't close socket, because it's hoping able http keepalive. should use readline

java - What exactly is an Enum? -

right i'm trying figure out enum in java. know how work , how/when use them i'm little unclear on are. based on behavior seems me nothing more class private constructor. seems me compiler doing special them enums have special method called values() doesn't show in enum class on oracle doc site. my question is, enums , how compiler interpret them? an enum class inherits enum class (a) private constructor, mentioned; , (b) fixed list of named, final instances. under covers, when declare enum : public enum foo { a(1) { public void bar() { system.out.println("a#bar"); } }, b(2) { public void bar() { system.out.println("b#bar"); } }, c(3) { public void bar() { system.out.println("c#bar"); } }; private foo(int x) { // code goes here... } public abstract void bar(); } ...you can imagine compiler ge

nlog - Supressing ServiceStack log messages using NLogFactory -

i using nlog servicestack , having difficulty turning off logs generates. nlog configuration follows: <logger name="servicestack.*" minlevel="off" writeto="file" final="true"/> <logger name="*" minlevel="info" writeto="file"/> basically should not log generated ss , else, log things @ info level or below. ss seems ignoring these settings though , happily logging away. however, if logging myself , grab logger ss namespace, like logmanager.logfactory.getlogger("servicestack.servicehost.servicecontroller") .debug("log message @ debug level"); it obey nlog configuration. seems if internal logs ignoring configuration. there missing, or not doing correct way?

Read a binary file (jpg) to a string using c++ -

i need read jpg file string. want upload file our server, find out api requires string data of pic. followed suggestions in former question i've asked upload pics server using c++ . int main() { ifstream fin("cloud.jpg"); ofstream fout("test.jpg");//for testing purpose, see if string right copy ostringstream ostrm; unsigned char tmp; int count = 0; while ( fin >> tmp ) { ++count;//for testing purpose ostrm << tmp; } string data( ostrm.str() ); cout << count << endl;//ouput 60! not right size fout << string;//only 60 bytes return 0; } why stops @ 60? it's strange character @ 60, , should read jpg string? update almost there, after using suggested method, when rewrite string output file, distorted. find out should specify ofstream in binary mode ofstream::binary . done! by way what's difference between ifstream::binary & ios::binary , there abbrev

python - The browser appears to have exited before we could connect. The output was: mkdir: cannot create directory -

i had python script running successfully. .py script open headless browser(pyvirtualdisplay & xvfb) , perform task , close browser. had issue xvfb processes being left open after script run. after run many times tend accumulate. periodically run killall command through ssh shell kill stagnant xvfb processes. didn't seem cause problems. attempted automate task setting cron job executed following command. ps -eo pid,etime,comm | egrep '^ *[0-9]+ +([0-9]+-[^ ]*|[0-9]{2}:[0-9]{2}:[0-9]{2})' | grep xvfb | awk '{print $1}' | xargs kill -9 command kill old xvfb processes. assumed 2 hours old? since have run command have not been able run .py script , receive following error: <class 'selenium.common.exceptions.webdriverexception'>: message: "the browser appears have exited before connect. output was: mkdir: cannot create directory `/.mozilla': permission denied\nerror: cannot open display: :9866\n" [83] => args = [84] =>

eclipse - IBM Worklight 6.0 - "Error: Unable to read repository at http://public.dhe.ibm.com/ibmdl..." -

Image
i trying add ibm worklight plugin eclipse environment in mac 10.7.5 system. using eclipse version juno 4.2.2 (sr2) java ee developers, , using java 7. tried install worklight plugin through "eclipse marketplace" , through "install new software" using ibm url. in both cases getting below error after installation progress @ "44%". an error occurred while collecting items installed session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.collect, operand=, action=). unable read repository @ http://public.dhe.ibm.com/ibmdl/export/pub/software/mobile-solutions/worklight/wdeupdate/plugins/com.ibm.imp.webtools.dojo.library.distributions_2.0.0.v20130508_1207.jar. connection reset unable read repository @ http://public.dhe.ibm.com/ibmdl/export/pub/software/mobile-solutions/worklight/wdeupdate/plugins/com.worklight.studio.plugin_6.0.0.20130614-0631.jar. connection reset let me know if missing while adding plugin.

java - Android Intent not working -

i trying start activity using intent never seems work. i've tried scoping variables on place , never seems work. using thread start activity. if because of ide, using android studio. i'm wondering mistake ids here because can't find any. have included android manifest because might have messed there too. here code: package com.mtprogramming.magicsquaresgame; import com.mtprogramming.magicsquaresgame.util.systemuihider; import android.annotation.targetapi; import android.app.activity; import android.content.intent; import android.os.build; import android.os.bundle; import android.os.handler; import android.view.motionevent; import android.view.view; /** * example full-screen activity shows , hides system ui (i.e. * status bar , navigation/system bar) user interaction. * * @see systemuihider */ public class opening extends activity { /** * whether or not system ui should auto-hidden after * {@link #auto_hide_delay_millis} milliseconds. */ private static final

Android AsyncTask case to freeze application on phone call received -

my android application communicate web services download , upload data using asynctask. if receive phone call during communication application hanged up, else every thing ok. how can handle issue. thanks try use service these kinds of tasks, understanding happens better take @ android's activity life-cycle: http://developer.android.com/training/basics/activity-lifecycle/

php - Deep Associations works with recursive => 2 but too slow to load -

i have 3 models product having product_family_id foreign key productfamily , productfamily have customer_id foreign key customer. putting recursive 2 in product model allow me customer name customer product. slow data vast tried using bind model below. didn't worked me. using cakephp framework. $this->product->bindmodel(array( 'belongsto' => array( 'productfamily' => array( 'foreignkey' => false, 'conditions' => array('product.product_family_id = productfamily.id') ), 'customer' => array( 'foreignkey' => false, 'conditions' => array('productfamily.customer_id = customer.id') ) ) )); use containable the containable behaviour data want without over

c - Subtracting 1 from a function pointer -

i saw line in signal.h in /usr/include/sys/ on mac. based on it's use return type of function signal , i'd expect sig_err pointer function takes integer input , returns void. macro expansion of sig_err seems subtract 1 function pointer type, found weird. how c parse it? #define sig_err ((void (*)(int))-1) ( (void(*)(int)) -1) does not subtract 1 function pointer, cast constant value -1 function pointer. as side note, adding or subtracting function pointer not allowed in iso c , can done as (somewhat peculiar) gcc extension handles if char pointer; in gcc, addition , subtraction operations allowed on pointers of type void, , pointers functions. normally, iso c not allow arithmetic on such pointers because size of "void" silly concept, , dependent on pointer pointing to. facilitate such arithmetic, gcc treats size of referential object 1 byte.

php - Create a Shipment Order in ups.com through api -

Image
i have api key , login credentials of ups.com want create shipment after order placed in website through api call,i have read documentation not getting specific code or call. welcomed.... you may find example code in ups developer kit portal ( https://www.ups.com/upsdeveloperkit ). login ups username , password download desired compressed file (e.g.: rating, shipping, etc.). see picture below. inside compressed files find web services , xml api's documentation , code samples written in java , c# , perl , php . best!

build - How to access ant variables in python script -

i have made build.properties file in ant in have defined variables shown below webinf.dir = web-inf src.dir = ${webinf.dir}/src now these variable accessed in ant build.xml file , working fine. want access these variables in python file also. , want value of src.dir come web-inf/src not ${webinf.dir}/src please how can this. thanks.. i believe can use single properties file (e.g. build.py) that's read ant , python. example: build.xml <project default="build"> <property file="build.py"/> <target name="build"> <echo message="${src.webinf}"/> </target> </project> script.py #!/usr/bin/python import configparser config = configparser.configparser() config.read("build.py") print config.get("properties", "src.webinf") build.py [properties] src.webinf = web-inf example usage $ ant buildfile: /applications/mamp/htdocs/clicks/t

sql server - How to avoid bloating transactionlogs while creating an index? -

does know avoid bloating transactionlogs while creating index? my problem: have script creates lot of indexes. while running script, transactionlog doesn't stop growing. there way, how reduce logging while creating index? regards if recovery model of database full , can temporary switch database bulk-logged recovery model if database set simple or bulk-logged recovery model , index ddl operations (including create index) minimally logged whether operation executed offline or online. here list of such operations can minimally logged: http://msdn.microsoft.com/en-us/library/ms191244(v=sql.105).aspx

html - Box-made navigation bar adapting to screen width? -

i'm trying create navigation bar composed blocks using code : <nav id="mainnav"> <ul> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> </ul> </nav> and css #mainnav { padding: 0px; } #mainnav li { display:inline-block; } #mainnav { /* box */ display: bloc

mysql - issue getting the value from database to combobox -

this controller: <?php class combobox extends ci_controller { function dynamic_combobox() { $this->load->model('combobox_model'); $data['college'] = $this->combobox_model->getcollege(); $this->load->view('header', $data); $this->load->view('left_menu', $data); $this->load->view('manage_user', $data); $this->load->view('footer', $data); } } ?> this model: $this->db->get('colleges'); $data = array(); if ($query->num_rows() > 0) { foreach ($query->result_array() $row){ $data[] = $row; } } $query->free_result(); return $data; this view: <form action="<?php echo site_url(''); ?>" method="post"> college <select name="id" id="id" style="width: 350px;"> <option class="droplist&q

ruby on rails 3 - what does "Connecting to database specified by database.yml" in the log file mean? -

i'm working on rails 3.2.9 app , on performing action, app doesnt go further , when chech log file line last in log connecting database specified database.yml i have no idea what's causing problem.. when sign or sign in needs connect db , works fine then.. when function (called execute test case) clicked, app doesnt go further , freezes there itself.. please me if have come across ...or suggest may cause!! check answer. may you. rails connecting database specified database.yml

php - My website showing on two domains -

my website showing on 2 domain as, developing on own domain, how can possible, there 1 domain don't know whose? when open link there showing same. hacked, or 1 getting access website? i don't know how prevent other domain link website. if case then, please suggest some, how prevent website seen on 2 domains? i see have put php tag suggest this: if ($_server['http_host'] != 'rtc') { exit; } however better handle kind of things in http server settings. example apache has virtual named hosts .

iphone - How to detect network type i.e. 3G/4G? -

this question has answer here: determining 3g vs edge 5 answers i working on application call web services using wifi cellular data of iphone. application working fine on wifi , 3g network not working in 4g network. please tell me how detect whether app connected through 3g or 4g , how resolve problem related 4g network. any appreciable. in advance. here same issue , may bellow code of example helps you. using private apis, can read information directly in status bar. https://github.com/nst/mobilesignal/blob/master/classes/uiapplication+ms.m + (nsnumber *)datanetworktypefromstatusbar { uiapplication *app = [uiapplication sharedapplication]; uistatusbar *statusbar = [app valueforkey:@"statusbar"]; uistatusbarforegroundview *foregroundview = [statusbar valueforkey:@"foregroundview"]; nsarray *subviews = [foreground

postgresql - Postgre SQL incorrect syntaxt near If -

i'm trying create function it's having error @ if statement don't know what's problem it. create function uspgetcountrylistwithpagenumber(in "pagenumber" integer, in "pagesize" integer, in "whereclause" text, in "orderby" text) returns setof getcountrylistitem $body$declare rowdata "getcountrylistitem"%rowtype; if $1 <> -1 , $2 <> -1 rowdata in loop execute 'select "countryid","countryname"' || 'from "mastercountry"' || $3 || $4 || 'limit' || $2 || 'offset' || ($1-1)*$2 return next rowdata; end loop; return; else rowdata in loop execute 'select "countryid","countryname"' || '

c++ - Implement the stack that pops the most frequently added item -

i asked implement stack pops added item in interview. gave him below answer not happy solution. class stack { // map of value , count map<int,int> cntmap; public: void push(int val) { // find val in map // if found increment map count // else insert pair (val,1) } int pop( ) { // find key in cntmap max value // using std::max_element // decrement cntmap count popped val } } can me correct approach? it's interesting question, because in push , using key, , in pop , using mapped value. std::map supports first immediately: have is: ++ cntmap[ val ]; the [] operator insert entry if key isn't present, initializing mapped type default constructor, int results in 0 . don't need if . the second more difficult. comments, however, give solution: need custom compare , takes 2 std::pair<int, int> , , compares second element. std::max_element return iterator entry you're interes

javascript - window.onload() not working with html content generated by proprietary fwk -

i using mobile application development framework adf mobile whereby develop cross-platform mobile applications.ui layer can developed set of components (amx) generate html5 based user interface , dom structure can debugged ios simulator+ safari browser builtin debugger. adf mobile internally uses cordova i need have javascript called when page completes loading. tried various approaches $(document).ready(function () { console.log("just inside $(document).ready()"); }); window.onload = function () { //handler function }; /* $(window).load(function () { //handler function }); $(window).bind('load', function () { //handler function }); window.addeventlistener("load", handlerfunction); */ everything related 'load' event fails 'ready' event getting fired expected. once handler function associated "load" event, when inspect window object of html using safari dom debugger, onload attribute has handler function

c++ - When a float variable goes out of the float limits, what happens? -

i remarked 2 things: std::numeric_limits<float>::max()+(a small number) gives: std::numeric_limits<float>::max() . std::numeric_limits<float>::max()+(a large number like: std::numeric_limits<float>::max()/3) gives inf. why difference? 1 or 2 results in overflow , undefined behavior? edit: code testing this: 1. float d = std::numeric_limits<float>::max(); float q = d + 100; cout << "q: " << q << endl; 2. float d = std::numeric_limits<float>::max(); float q = d + (d/3); cout << "q: " << q << endl; formally, behavior undefined. on machine ieee floating point, however, overflow after rounding result in inf . precision limited, however, , results after rounding of flt_max + 1 flt_max . you can see same effect values under flt_max . try like: float f1 = 1e20; // less flt_max float f2 = f1 + 1.0; if ( f1 == f2 ) ... the if evaluate true , @ least ieee

javascript - jQuery .load() function not working on my php file -

my particular situation using jquery .load() function include page site after clicking link. have chosen write code inline. have user control panel several buttons link pages edit information. have 1 password , 1 settings. i'm trying 1 work , write each loop apply more links click. php file looks this: <?php include_once("template/main_site/core/init.php"); protect_page(); if (empty($_post) === false) { $required_fields = array('current_password', 'password', 'password_again'); foreach ($_post $key=>$value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'fields lighted red required.'; break 1; } } if (encryptbetter($_post['current_password']) === $user_data['password']) { if (trim($_post['password']) !== trim($_post['password_again'])) {

box api - Box Api v2 java - How to reuse the access-token within 3600 secs -

i using box api v2 (java) integrating webapp box.com. i forward user authorize url https://www.box.com/api/oauth2/authorize?response_type=code&client_id=client-id ..and receive 'code' @ redirect end-point. using code, able access_token , refresh_token. know access_token valid 1 hr. but can re-use access_token within 3600 sec period? eg:a user comes within 30 minutes , tries fetch/put files in scenario, need create new boxclient. recommended method of client authentication using existing access token? if answerer can paste code snippets using box java api, quite helpful. or refreshing new access_token , refresh_token, method available? boxclient client = new boxclient(my_client_id, my_client_secret);boxoauthmanager mgr = client.getoauthmanager(); // refresh boxoauthrequestobject requestobject = boxoauthrequestobject.refreshoauthrequestobject(refresh_token, my_client_id, my_client_secret); boxoauthtoken newtoken = mgr.refreshoauth(requestobject); clien

java - Does Hibernate Fully Support SQLite -

jboss hibernate doesn't support sqlite - https://community.jboss.org/wiki/supporteddatabases2 and same mentioned in below so: hibernate+sqlite+netbeans can please highlight this. want use embedded sqlite hibernate swing desktop application. i evaluating derby (javadb) can embedded , part of jdk. since sqlite embedded database c-like environments, written in c , compiled native code, changes hibernate (or orm) support aren't high. java cross-platform , bit weird have platform-dependent dependency. on android, sqlite used, there platform supplies jdbc driver it. usually, windows binaries compatible on different windows versions - long architecture stays same. if @ sqlite download page you'll notice there's 32-bit pre-built windows binary. 1 can used on windows version (except windows rt, maybe), cannot use on linux or os x. in order use sqlite java, need include correct binary specific os / architecture, making java application platform-dependent

gerrit - Different branch definitions for git push -

what difference between: git push origin head:refs/for/master and git push origin refs/for/master shouldn't second command push changes remote repo origin , move head? 'refspec' option following 'repository' name. according --help page refspec in form of <source ref>:<destination ref> refs name of branch , means use 'source ref' update 'destination ref'. so git push origin head:refs/for/master means update remote master using head(current branch) can omit 'destination ref' part. if git tries find remote branch name same 'source ref'. so git push origin refs/for/master means using local 'refs/for/master' branch update remote 'refs/for/master' branch. /for/ used gerrit not local repository. git can't find local 'refs/for/master' branch , can't anything.

javascript - Multiple file upload/submit forms -

i have single page multiple file upload forms. generated in loop. problem: first file upload control works, , rest don't. <div> <form action="/docs/1046/uploaddocument?id=1046&amp;propertytypeid=1" enctype="multipart/form-data" method="post"> <input name="x-http-method-override" type="hidden" value="put"> <div style="display: none"> <label for="filecommercial_transport_license"></label> <input id="filecommercial_transport_license" name="filecommercial_transport_license" type="file" onchange=" $('#btnsubmitdata').click(); "> <input id="btnsubmitdata" type="submit" onclick=" txt = $('#filecommercial_transport_li

Jquery Smartspinner Reset Value -

i use jquery smartspinner it's work fine can't reset value in function onload set initvalue:3 when set new value in smartspinner box dont override new value set old initvalue in thats plugin var duration = $("#bookingduration").spinit({ height: 18, width: 65, min: 1, initvalue: 3, max: 62 }); now have calender , send new duration in box $('#cdateto').datepicker({ dateformat: 'dd.mm.yy', mindate: $('#cdatefrom').datepicker('getdate'), onselect: function () { // diff var d1 = $('#cdatefrom').datepicker('getdate'); var d2 = $('#cdateto').datepicker('getdate'); var diff = 0; if (d1 && d2) { diff = math.floor((d2.gettime() - d1.gettime()) / 86400000); } duration.reset(diff); $("#bookingduration").val(diff); } }); when diff 10 , press key or down load old initvalue 3 have trails withe jquery val override not work i

c# - Populating SelectList based on three different tables -

i'm not experienced asp.net mvc nor entitity framework. the problem following: have database table tax code sets, organizations , table 'displaydata' contains information sets linked organization. returning organizations , tax code sets works well. should able build list of tax codes based on chosen organization. relevant code far looks this: ienumerable<taxcodes> taxcodelist = null; ienumerable<organizations> orglist = null; ienumerable<displaydata> taxcodeids = null; model.orgid = convert.toint64(request.querystring["orgid"]); if (model.orgid == 0) model.orgid = 1; taxcodelist = db.taxcodes.asnotracking().distinct().orderby(s => s.id).tolist(); orglist = db.organizations.asnotracking().distinct().orderby(s => s.org_id).tolist(); taxcodeids = db.displaydata.where(s=>s.companyid == model.orgid).tolist(); model.taxcodelist = new selectlist(taxcodelist

android - getView in BaseAdapter calling behaviour on fling -

say have listview of 20 elements displaying 8 elements @ time screen. i have noticed getview called many more times when perform fling operation on listview when scroll list (in both cases scrolling/flinging top bottom). question why flinging call getview more times normal scrolling? i understand there ways make getview efficient understand why getview called more fling operation. the behavior of getview() method such called many times views changed in screen. whenever scrolling of listview recycle old records , inflate new records calling getview() method. view recreated each , everytime scroll list , show new records when scrolling stops. the adapters built reuse views, when view scrolled no longer visible, can used 1 of new views appearing. reused view convertview. if null means there no recycled view , have create new one, otherwise should use avoid creating new. convertview recycling. let's have listview can display 10 item @ time, , displaying item 1 -

jqplot same properties for multiple plots -

question reusing plot properties e.g. plot_x = $.jqplot('somedivid_x', [line], { grid: { background: "rgba(0,0,0,0.0)", drawborder: false, shadow: false, color: "#fff" }, series:[ { pointlabels:{ show: true, location:'s', ypadding : 5, edgetolerance : -100, }}], seriescolors: ["#ff666d"], seriesdefaults:{ renderer:$.jqplot.barrenderer, rendereroptions: { filltozero: true, barwidth: '60' } }, axes: { xaxis: { renderer: $.jqplot.dateaxisrenderer, }, yaxis: { min:0, max:100 } } }); this plot definition attached somedivid_x. want reuse definition similar plots using same properties this how can achieve it. var plotoptions = { grid: { background: "rgba(0,0,0,0.0)", drawborder

Select certain elements from a vector and create a new vector with those elements in Matlab? -

i have vector 'y' looks this: [1 1 1 0 1 2 2 2 2] i use y(y>1) command elements greater 1, in case, elements = 2 . how create new vector based off elements y(y>1) command gave me? i'd end with x = [2 2 2 2] any appreciated. you did answer own question y(y>1) : >> y = [1 1 1 1 1 0 0 0 2 2 2 2 2] y = 1 1 1 1 1 0 0 0 2 2 2 2 2 >> x=y(y>1) x = 2 2 2 2 2 because (y>1) returns array of logical values size of y containing result of given check. >> (y>1) ans = 0 0 0 0 0 0 0 0 1 1 1 1 1 you can use array address data in data array, points logical array 1 returned