Posts

Showing posts from July, 2014

java - Secure jsonp ajax calls -

i have developed restful web-service returns jsonp objects. using web-service in simple html page using ajax calls. means @ client side there html page access web-service. no server used @ client side. running page browser. problem can access web-service have implemented. want make secure kind of authentication. have read solution send token along request @ client side don't have server or anything, simple html page. please me solution secure web-service. javascipt function call webseive: function calculatepremium(investmentamount,month, premium) { var url = "http://192.1.200.107:8080/webresources/avestwebservice/getpremium"; var payloaddata = { amount: $("#"+investmentamount).val(), period: $("#"+month).val() }; $.ajax({ type: "get", url: url, cache:false, crossdomain:true, data: payloaddata, datatype: "jsonp", success: function (data,textstatus,jqxhr) { $("#...

Enum with functions in C -

while examine source code of ffmpeg, see line: enum avdurationestimationmethod av_fmt_ctx_get_duration_estimation_method (const avformatcontext* ctx); what functionality of enum here? av_fmt_ctx_get_duration_estimation_method function returns object of enum type avdurationestimationmethod .

Animation with large number of sprites in Cocos2d iOS? -

i have animate(dancing) character(guy) 6-7 seconds i.e 500-600 frames . have done animation before creating spritesheets using zwoptex , loading ccspriteframecache && ccspritebatchnode of the great ray wenderlich . in case frames heavy in number not sure if ios device able sustain it. best process animate these frames little overhead possible. can change fps while animating? idea anyone?? here put code use add animated image without use texturepacker : ccsprite *dog = [ccsprite spritewithfile:@"dog1.gif"]; dog.position = ccp(winsize.width/2, winsize.height/2); [self addchild:dog z:2]; nsmutablearray *animframes = [nsmutablearray array]; for( int i=1;i<=5;i++) { nsstring* file = [nsstring stringwithformat:@"dog%d.gif", i]; cctexture2d* texture = [[cctexturecache sharedtexturecache] addimage:file]; cgsize texsize = texture.contentsize; cgrect texrec...

Access 2007 button click event error -

i have following code in access vba on button click event. idea use temporary variable forward value textbox subform: private sub button_novi_ir_click() on error goto button_novi_ir_click_err on error resume next tempvars("brojrn").value = me.brojrntxt docmd.openform "podaci_o_izvrÅ enim radovima_form", acnormal, "", "", acadd, acnormal if (macroerror <> 0) beep msgbox macroerror.description, vbokonly, "" end if button_novi_ir_click_exit: exit sub button_novi_ir_click_err: msgbox error$ resume button_novi_ir_click_exit end sub each time click button error message "a problem occurred while ms office access communicating ole server or activex control". have no idea it. so, please can point me in right direction? thanks in advance! i don't know whether accented character in form name issue - i'll assume isn't. shouldn't supply empty st...

Using GWT UiBinder, Eclipse marks every UiField as an error -

this annoyance, not serious problem, bothers me can't figure out. have gwt project , eclipse marking every @uifield tag error "field x has not corresponding field in template file." when true compile error , can fix it. of time compiles , runs fine, though files full of red squiggly underlines. i assume i'm missing basic eclipse skill since can't find else problem. i've tried doing refresh on project. i having same issue. not code issue suggested @ruggi project compiles , runs correctly. i solved problem updating gwt install. found there update available via -> check updates. after install , reboot problem solved.

sql - Create a 350000 column csv file by merging smaller csv files -

i have 350000 one-column csv files, 200 - 2000 numbers printed 1 under another. numbers formatted this: "-1.32%" (no quotes). want merge files create monster of csv file each file separate column. merged file have 2000 rows maximum (each column may have different length) , 350000 columns. i thought of doing mysql there 30000 column limit. awk or sed script job don't know them , afraid take long time. use server if solution requires to. suggestions? this python script want: #!/usr/bin/env python2 import os import sys import codecs fhs = [] count = 0 filename in sys.argv[1:]: fhs.append(codecs.open(filename,'r','utf-8')) count += 1 while count > 0: delim = '' fh in fhs: line = fh.readline() if not line: count -= 1 line = '' sys.stdout.write(delim) delim = ',' sys.stdout.write(line.rstrip()) sys.stdout.write('\n') fh i...

c++ - g++ Bug with Partial Template Specialization -

i writing tmp-heavy code g++ (version 4.8.1_1, macports) , clang++ (version 3.3, macports). while g++ rejects following code listing unbridled fury , clang++ compiles grace , splendor . which complier in right? (i suspect it's g++, want reassurance others before submitting bug report.) do have easy or elegant workarounds suggest? (i need use template aliases, switching on structs, causes g++ accept code, not option.) here code listing, made just you . template <class... ts> struct sequence; template <int t> struct integer; // definition of `extents` causes g++ issue compile-time error. template <int... ts> using extents = sequence<integer<ts>...>; // however, definition works without problems. // template <int... ts> // struct extents; template <int a, int b, class current> struct foo; template <int a, int b, int... ts> struct foo<a, b, extents<ts...>> { using type = int; }; template <int b, int....

c# - How To Display Multiple Rows in XamGrid -

i using listbox control show items , when double cilck item means thier particular item fields display in xamgrid , problem when selected item means showing need display multiple things in grid 1 or more items my codings are, private void lsimagegallery_mousedoubleclick(object sender, mousebuttoneventargs e) { rtbsproject.db.rtbsinventorymgmtentities2 myrtbsinventorydb = new db.rtbsinventorymgmtentities2(); rtbsproject.db.rtbsinventorymgmtentities2 db_linq = new db.rtbsinventorymgmtentities2(); try { string curitem = lsimagegallery.selecteditem.tostring(); #region if (cmbitemcombo.selecteditem == null) { var selectedimage = (imageentity)this.lsimagegallery.selecteditem; string itemname = selectedimage.itemname_en; var query = (from myitems in myrtbsinventorydb.tbl_itemmaster myitems.activeflag == true && ...

bash - why does ( cd && sleep 5000 ) start second process -

i have script test.sh #!/bin/bash ( cd . && sleep 5000 ) i execute ./test.sh & , run ps lax | grep test.sh i have 2 processes running... 0 1000 6883 6600 20 0 10600 1332 - s pts/2 0:00 /bin/bash ./test.sh 1 1000 6884 6883 20 0 10604 704 - s pts/2 0:00 /bin/bash ./test.sh why have 2 processes running , second process come from? why don't have 2 processes if remove cd ".." command? thanks explanation, don't , think i'm lacking basics here... or vodoo? ;) grouping series of bash commands inside parenthesis execute them in sub-shell.

ios - Auto Layout using initWithFrame? -

if i'm implementing autolayout programatically in ios proper use initwithframe method? if not how initialise view of preferred size? better avoid initwithframe unless have no choice. auto layout, approach define 2 constraints specify width , height. there's different ways if you're doing programmatically, in updateviewconstraints method of view controller, or updateconstraints method of view, check if constraints have been created , if not, add them view. e.g. [myconstraints addobjectsfromarray:[nslayoutconstraint constraintswithvisualformat:@"h:|-[_mysubview]-(200)-|" options:0 metrics:nil views:_myviewsdictionary]]; [myconstraints addobjectsfromarray:[nslayoutconstraint constraintswithvisualformat:@"v:|-[_mysubview(100)]-|" options:0 metrics:nil ...

email - SMF "<apache>: sender address must contain a domain" -

i have smf forum installed on own server. reason unable found, smf send emails new user-activation without "from" email address, "apache". obviously, email server not allow , email never received. i following postfix message postmaster account. <email@dest.example.com>: host dest.example.com[255.255.255.255] said: 501 <apache>: sender address must contain domain (in reply mail command) reporting-mta: dns; my.example.com x-postfix-queue-id: 62653a403d7 x-postfix-sender: rfc822; apache arrival-date: sat, 13 jul 2013 01:44:57 +0200 (cest) final-recipient: rfc822; email@dest.example.com action: failed status: 5.0.0 remote-mta: dns; dest.example.com diagnostic-code: smtp; 501 <apache>: sender address must contain domain return-path: <apache> received: my.example.com (postfix, userid 48) id 62653a403d7; sat, 13 jul 2013 01:44:57 +0200 (cest) to: email@dest.example.com subject: example title x-php-originating-script: 48:subs-post.php ...

html - Image positioning with two p within div -

please see code pen visual of mean http://codepen.io/markrbm/pen/knztj i have 4 column layout. .wrapper confined 2 cols wide. .locstitle 1 col wide , .locsexcerpt 1 col wide , in position want them in. want .locsimage to left of .locsexcerpt directly under .loctitle cant move bottom of .locslist . if move mark-up above .locsexcerpt displays right of .locstitle , above .locsexcerpt . think have narrowed down issue code have linked , shown below. in advance. html <div class="wrapper"> <div class="locslist"> <p class="locstitle">galway</p> <p class="locsexcerpt"> lorem ipsum dolor sit amet, consectetur adipisicing elit. provident, quod quas aut quisquam necessitatibus ut aliquid eligendi sunt voluptas fugitlorem ipsum dolor sit amet, consectetur adipisicing elit. provident, quod quas aut quisquam necessitatibus ut aliquid eligendi sunt voluptas fugit!</...

wpf - Would a single resource file referenced in a window and at the app level have only one instance? -

i have loose form of mvvm have c# class containing resource data xaml bound to. file referenced in 2 places, mainwindow.xaml file , @ application level in app.xaml file. when referece in mainwindow code-behind there seems 1 instance , can set values in 1 instance seen in both window level , application level. can confirm or correct assumption? see edit below i have mainwindow , mainwindowresource.cs file binding of mainwindow. resource file looks (shortened): public class mainwindowresource : inotifypropertychanged { #region data members private color _arrowbordercolor = colors.black; private color _arrowcolor = colors.black; private bool _viewfityaxis = true; private string _viewfityaxistooltip = ""; #endregion data members #region properties public color arrowbordercolor { { return _arrowbordercolor; } set { _arrowbordercolor = value; setpropertychanged("arrowbordercolor"); } } public co...

php - Customer redirected from site to PP, session data empties -

i have cart products , shopping cart stored within session. session works fine through entire process, except when customer goes paypal's website. when customer redirected paypal, returned website, of session data lost. the session id remains same before , after redirect i have tried setting referrer_check variable no value. still not work. the same code works on dev server, , have ensured settings match between dev , live server, sessions, still not able save sessions after return. i'll provide settings requested. i've tried this: session lost after page redirect in php (adding exit() right after redirect) i'll keep updating things i've tried responses this.

sql server - stored procedure with out parameter -

i have stored procedure follows: alter procedure [dbo].[sp_checkemailavailability] -- add parameters stored procedure here ( @email varchar(50)=null, @count int output ) begin -- set nocount on added prevent result sets -- interfering select statements. set nocount on; -- insert statements procedure here select @count=count(*) dbo.tx_userpersonaldetails s_email=@email end i have following code in aspx.cs page:- sqlcommand cmd = new sqlcommand("[dbo].[sp_checkemailavailability]", objcon); int result = 0; try { cmd.commandtype = commandtype.storedprocedure; sqlparameter parm = new sqlparameter("@email", sqldbtype.varchar); parm.value = txtusername.text.tostring(); parm.direction = parameterdirection.input; cmd.parameters.add(parm); sqlparameter parm1 = new sqlparameter("@count", sqldbtype.int); // pa...

php - How to style drop down list? -

this question has answer here: how style <select> dropdown css without javascript? 24 answers how add css styles drop down list on form? searched lot on internet no useful results found. thanks echo "<form method='post' action='advisor.php?view=$view'> select student: <select name='data'>"; while($row = mysqli_fetch_array($query)) { echo "<option value=\"".$row[3] . "\">".$row[0] ." " . $row[1] . " (".$row[3].")". "</option>"; } echo " </select> <input type='submit' name='submit' class='buttonm' value='show questions' /> </form>"; } check out - http://bavotasan.com/20...

linux - strange macro in c, using multiple statements -

this question has answer here: are compound statements (blocks) surrounded parens expressions in ansi c? 2 answers i found strange syntax while reading linux source code. container_of macro looks like #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) what confused me syntax ({statement1; statement2;}) i tried simple code like int = {1;2;}; i compiled gcc. after running, 'a' seemed 2. couldn't compiled microsoft vc++. syntax expanded feature of gcc? if so, how can same effect without gcc expansion, define multiple statements , return value using macro? the ({ ... }) syntax gcc extension, called statement expressions . the typeof gcc extension. both extensions available in other compilers...

ios - UICollectionViewLayout. Where are all my items? -

when implement uicollectionview without custom layout object, 16 of reusable cells appear. is, have 1 section 16 items in section. when create custom layout object, 1 cell appears. if change # of sections 5, 5 cells appear. why collectionview draw sections when using layout object, , items when using default grid???? missing something? i subclass uicollectionviewlayout here: static nsstring * const kpadlayouttype = @"gridpads"; - (id)initwithcoder:(nscoder *)adecoder { self = [super initwithcoder:adecoder]; if(self) { [self setup]; } return self; } - (void)setup { self.iteminsets = uiedgeinsetsmake(22.0f, 22.0f, 13.0f, 22.0f); self.itemsize = cgsizemake(125.0f, 125.0f); self.interitemspacingy = 12.0f; self.numberofcolumns = 4; } # pragma mark _____layout - (void)preparelayout { nsmutabledictionary *newlayoutinfo = [nsmutabledictionary dictionary]; nsmutabledictionary *celllayoutinfo = [nsmut...

java - Wrong updating TextView in Android app -

Image
i create simple android app ( https://www.linux.com/learn/docs/683628-android-programming-for-beginners-part-1 ) latest android studio. code: public class test_act extends activity { private static final int millis_per_second = 1000; private static final int seconds_to_countdown = 30; private android.widget.textview countdowndisplay; private android.os.countdowntimer timer; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.full_act); countdowndisplay = (android.widget.textview) findviewbyid(r.id.time_display_box); android.widget.button startbutton = (android.widget.button) findviewbyid(r.id.startbutton); startbutton.setonclicklistener(new view.onclicklistener() { public void onclick(view view) { try { showtimer(seconds_to_countdown * millis_per_second); } catch (numberformatexcep...

javascript - IE iframe doesn't handle application/json response properly -

i upgrading parts of asp.net mvc website more restful, using asp.net web api. 1 of features moving more restful design file upload. client, using jquery plugin, ajaxform , wrap creation of iframe submit form containing file input element. working great asp.net mvc. when changing use our web api endpoint, returns response content-type of "application/json", noticed problems internet explorer 9. appears ajaxform success function never called. can tell, appears iframe in ie interprets body of response content-type of "application/json" file attachment downloaded. means never fires iframe's "loaded" event, means ajaxform onload event handler never triggered, , our ajaxform success function never called. we noticed issue in ie 7 well, not recreate issue in latest release versions of firefox or chrome, when forcing them use iframe rather file api formdata. to resolve issue now, forcing response content-type "text/plain", returning asp.net...

Running .exe on a XAMPP Server -

i wondering if possible run program on xampp server? making game , need run controller program on server receive info client programs. possible? know can start program on server remotely, opens program on server pc, not wanting. also, know if possible click , link on index.php page , opens client.exe on pc. far, launches on server pc. using echo exec('') command launch program. thanks, doglover on server side can try either php/cgi , stores data in file or mysql database. on client side can try either java/flash or can force download of file on user computer using content disposition in header.

design - Analogy between Account class and java.io.File -

i designing expensemanager application , came across design/refactoring decision. account domain object (immutable) looks this: public class account { private long accountid; private string accountname; //getters //static nested builder instantiate in immutable fashion } it nothing value object (not domain object :( ) earlier had deisgned (and implemented) accountmanager class managed account creation, edition, deletion, etc. public class accountmanager { public createaccount(account account) { //impl } //similarly edit, delete methods } but when read this article, got me thinking. the analogy java.io.file class has method createnewfile() creates file in underlying file system. file class uses filesystem object this. similarly, thought account class should have createnewaccount() method , use accountmanager internally. which better design decision? using accountmanager account operati...

javascript - Is it possible to bind multiple functions to multiple delegation targets in one place? -

as possible define multiple event handlers in 1 single function in jquery this: $(document).on({ 'event1': function() { //do stuff on event1 }, 'event2': function() { //do stuff on event2 }, 'event3': function() { //do stuff on event3 }, //... }); then again can this: $(document).on('click', '.clickedelement', function() { //do stuff when $('.clickedelement') clicked }); i wondering if possible (the following code not work, it's illustration): $(document).on('click', { '.clickedelement1', function() { //do stuff when $('.clickedelement1') clicked }, '.clickedelement2', function() { //do stuff when $('.clickedelement2') clicked }, //... , on }); this code gives me error complaining "," after '.clickedelementx'. tried this: $(document).on('click', { '.clic...

c# - Is it safe to call Add on SortedDictionary in one thread and get Item in another? -

i'm working on making sorteddictionary thread safe , thing i'm not sure is: safe have call add sorteddictionary in 1 thread, this: dictionary.add(key, value); and item dictionary in thread, this: variable = dictionary[key]; there no explicit enumeration in either of places, looks safe, great sure it. no, not safe read , write sorteddictionary<k,v> concurrently: adding element sorted dictionary may involve re-balancing of tree, may cause concurrent read operation take wrong turn while navigating element of interest. in order fix problem need either wrap instance of sorteddictionary<k,v> in class performs explicit locking, or roll own collection compatible interfaces implemented sorteddictionary<k,v> .

windows - Dirrectory name invalid -

the following code gives me weirdest errors have seen in long time. gives reference /*.* when not using that? code: t_src = src.get() t_dst = dst.get() print t_src try: item in os.listdir(t_src): print item s = os.path.abspath(os.path.join(t_src,item)) d = os.path.abspath(os.path.join(t_dst, item)) filename in os.listdir(s): try: if os.path.isfile(filename): print filename elif os.path.isdir(filename): print "possible dirrectory" print filename #shutil.copytree(filename, d) except: print "unexpected error:", traceback.format_exc() except: print "unexpected error:", traceback.format_exc() the error: c:\windows\system32\cmd.exe /c python copydir.py as.txt unexpected error: traceback (most recent call last): file "copydir.py", line 46, in co...

php - Unexpected character in input: '\' -

i'm trying launch php script cron job in bluehost. when access script manually woks, when triggered cron job gives following error: [17-jul-2013 08:36:01] php warning: unexpected character in input: '\' (ascii=92) state=1 in /home2/xxxxx/public_html/xxxxx/reblog.php on line 17 [17-jul-2013 08:36:01] php parse error: syntax error, unexpected t_string in /home2/xxxxx/public_html/xxxxx/reblog.php on line 17 line 1 following: $client = new tumblr\api\client($consumerkey, $consumersecret); i have feeling cron job uses different version of php, set 5.4. any suggestions? there's cli php version 5.4 available, ask bluehost full path , use it.

php - how to add checkbox intems in to data base in one row -

i crated form, <td> <input type="checkbox" name="mode[]" id="mode" value="sweet" /> sweet<br /> <input type="checkbox" name="mode[]" id="mode" value=" sour" /> sour<br /> <input type="checkbox" name="mode[]" id="mode" value=" creamy" /> creamy<br /> <input type="checkbox" name="mode[]" id="mode" value="bland" /> bland<br /> </td> and php code is, for ($i=0; $i<sizeof($mode); $i++) { $emode = mysql_real_escape_string($mode[$i]); $query =<<<eof insert frutesdetails(fruitname,fruitcolor,seasonfrom,seasonto,fruitetaste,fruitbenefit) values (...

html - How to set javascript on a dynamic array? -

i working on dynamic array inside table means table appears based on user input. users need fill table , click submit. need place javascript here check if user didn't select or didn't write in column. if so, user should not able proceed. <form action="klr.php" method="post" name="myform" > <?php ($i = 1; $i <= $de; $i++) { ?> <tr> <td>tube</td> <td> <select id="in4-<?php echo $i; ?>" name="t1[<?php echo $i; ?>]" onclick="gettext3(<?php echo $i; ?>)" onchange="gettext39(<?php echo $i; ?>)" onmouseout="gettext89(<?php echo $i; ?>)"> <option value="0">0</option> <option value="12">12</option> <option value="18">18</option> ...

windows - Save Outlook Email as text file, and then run a script on it? -

i'm using outlook 2007. have no experience windows programming or vba, of background on unix systems. attempting have outlook save each incoming emails text file, , run python script parse text file. i found this question seems provide vba code accomplish first task, i'm not sure how utilize it. open visual basic editor, have no idea how proceed there. tried saving text module, when attempt add "run script" in outlook rule, no scripts available. doing wrong? edit: clarification. i'm assuming you're familiar coding @ some level, if not on windows. may want general background reading on outlook vba; resources on microsoft article , this article outlookcode, , on - there's ton of resources out there walkthroughs , examples. addressing specific question: take @ this microsoft kb article , describes how trigger script rule. the key getting started once you've gotten vba editor open double-click module on left, example thisoutlookses...

tabular - Stata 12 - A Long Tab and Getting Past the "More" Automatically -

if tab values in stata 12 , there long list of values, stata 12 seems pause , display more. seems want me press return (or perhaps value) in order continue. did not notice feature earlier features of stata, stata 11, meaning when hit tab display of values @ once (presuming list not long , did not result in error). there way around in stata 12 in not prompted hit return such long list? try set more off . extra characters.....

Cassandra - TimedOutException - Wrong prompt? - strange acknowledged_by and acknowledged_by_batchlog value set-up -

i'm trying bit more information timedoutexception. after inputing data 6 minutes(a lot of insert succeed), get: caused by: timedoutexception(acknowledged_by: 0 , acknowledged_by_batchlog: true ) the exception occurs during batched insert operations. i'm using cassandra 1.2.6. can't perceive special cassandra behavior during timeoutexception occur. i red acknowledged_by , acknowledged_by_batchlog , cannot understand set-up of value in case(0,true)(wrong prompt?). case of atomic_batch_mutate, why 2 value reveal other facts? javadoc in cassandra code, placed on acknowledged attribute: "if write operation acknowledged replicas not enough satisfy required consistencylevel, number of successful replies given here. in case of atomic_batch_mutate method field set -1 if batch written batchlog , 0 if wasn't ." javadoc in cassandra code, placed on acknowledged_by_batchlog attribute: " in case of atomic_batch_mutate method field tells if batch writt...

apache - Error with PHP Websocket and Wamp Server -

Image
i'm new of websockets, i'm trying connect websocket: phpwebsocket wamp server, first, in httpd.conf wrote listen 9300, , if go localhost:9300 works right, when go console , write: php -q c:\wamp\www\demos\server.php i got error: here's code of server.php: <?php set_time_limit(0); require 'class.phpwebsocket.php'; function wsonmessage($clientid, $message, $messagelength, $binary) { global $server; $ip = long2ip( $server->wsclients[$clientid][6] ); if ($messagelength == 0) { $server->wsclose($clientid); return; } if ( sizeof($server->wsclients) == 1 ) $server->wssend($clientid, "there isn't else in room, i'll still listen you. --your trusty server"); else foreach ( $server->wsclients $id => $client ) if ( $id != $clientid ) $server->wssend($id, "visitor $clientid ($ip) said \"$message\""); } function wsonope...

c - Getting Negative Values Using clock_gettime -

in following program, have tried measure execution time of job(for loop). of time works fine, however, sometimes, returns negative values!! first guess variable may overflowed. can please let me whether right or not? how can solve problem? thanks int main(int argc, char **argv) { long int st; long int et; struct timespec gettime_now; clock_gettime(clock_realtime, &gettime_now); st= gettime_now.tv_nsec; (i=0; < 1000; i++) a[i]=b[i]; clock_gettime(clock_realtime, &gettime_now); et= gettime_now.tv_nsec; printf("time diff: %ld\n", et-st); } you neglecting tv_sec of struct timespec in both cases , using nano-second not correct st , ev 's tv_nsec may of different second's. from man , tv_sec - represents seconds since epoch tv_nsec - current second in nano-second precision (1/1000000000 sec) it better write own function find difference. sample code (not tested), timespec diff(timespec start, timespec end) { timespec temp; ...

javascript - Facing a issue when trying to use a IF statement with arrays -

i creating shopping cart uni project, facing problems when testing array. if more 5 elements selected total price should have 10% discount. variable discount works fine when 1 element selected quantity bigger 5 returns 0 if quantity split between 2 elements (meaning if potatos = 6 discount works if potatos = 4 , blueberry = 2 doesnt work anymore ). here code : function calc() { var numberpotatos = document.getelementbyid('potatos_id').value; var numberblueberry = document.getelementbyid('blueberry_id').value; var numberstrawberry = document.getelementbyid('strawberry_id').value; var numbereggplants = document.getelementbyid('eggplants_id').value; var numberkiwis = document.getelementbyid('kiwis_id').value; var numberbananas = document.getelementbyid('bananas_id').value; var output = ""; var myarray= new array (6); myarray [0] = numberpot...

python - Append different object into list but the list result in same objects repeating -

im trying create function return neighboring node of state of n-queens on chess board, , below code, generate list of neighboring node based on parameter input state. #generate neighboring state's function def generate_neighbor_node (cur_state): current = cur_state neighbor = current neighbor_list = [] in range(qs): chg_value = neighbor[i] chg_value +=1 if chg_value == qs: chg_value =0 neighbor[i] = chg_value print neighbor neighbor_list.append(neighbor) #reverse process, change node value original next #loop generate valid neighbor state chg_value -=1 if chg_value == -1: chg_value = (qs-1) neighbor[i] = chg_value return neighbor_list print board ai = generate_neighbor_node(board) print ai output this: 1. [1, 3, 2, 0] 2. [2, 3, 2, 0] 3. [1, 0, 2, 0] 4. [1, 3, 3, 0] 5. [1, 3, 2, 1] [[1, 3, 2, 0], [1, 3, 2, 0], [1, 3, 2, 0], [1...

python - summing the number of occurrences per day pandas -

i have data set in pandas dataframe. score timestamp 2013-06-29 00:52:28+00:00 -0.420070 2013-06-29 00:51:53+00:00 -0.445720 2013-06-28 16:40:43+00:00 0.508161 2013-06-28 15:10:30+00:00 0.921474 2013-06-28 15:10:17+00:00 0.876710 i need counts number of measurements, occur looking this count timestamp 2013-06-29 2 2013-06-28 3 i dont not care sentiment column want count of occurrences per day. if timestamp index datetimeindex : import io import pandas pd content = '''\ timestamp score 2013-06-29 00:52:28+00:00 -0.420070 2013-06-29 00:51:53+00:00 -0.445720 2013-06-28 16:40:43+00:00 0.508161 2013-06-28 15:10:30+00:00 0.921474 2013-06-28 15:10:17+00:00 0.876710 ''' df = pd.read_table(io.bytesio(content), sep=...

android - Pre load convert view -

i have 3 kind of layouts in list. my problem 2 kinds showing, when list shown @ beginning. when scroll down, have these 2 layouts ready converted , provide smooth scroll when third kind of layout arrive, don't have converted layout , causes small jitter. my question: there why pre load (or pre inflate) layouts ready converting in getview()? thanks!

caching - Symfony2 ACL Cache -

is there example or better documentation how cache acl queries in symfony2. i found following: http://api.symfony.com/2.0/symfony/component/security/acl/domain/doctrineaclcache.html but not know how apply on checks. i've managed cache objectidentities. bit of not much. after lot of digging around in security*.xml files i've made following modifications of config.yml: i've added cache id (service id) acl configuration i've enabled doctrine result cache. config.yml: doctrine: orm: result_cache_driver: type: apc security: acl: cache: id: security.acl.cache.doctrine prefix: my_acl_prefix_ this enable caching of objectidentities, lot of other queries happening when symfony\component\security\acl\dbal\aclprovider::getancestorids() being called. method directly executes sql query, , uses no cache. in 2.2 , 2.3 there comment in method saying: // fixme: skip ancestors ...

c++ - Boost serialization with shared_ptr without implementing serialize() function in pointed class -

in boost tutorial , example of using shared pointers, have class a, , create shared pointer pointing object of class a : boost::shared_ptr<a> spa(new a); then serialize it: std::ofstream ofs(filename.c_str()); boost::archive::text_oarchive oa(ofs); oa << spa; so why class a have have function? void serialize(archive & ar, const unsigned int /* file_version */); the reason want use shared pointer avoid defining function of complex classes. i'm not using shared pointer, i'm using real pointer, , i'm serializing address pointer pointing at. the reason want use shared_pointer avoid defining function of complex classes. in opinion, wrong reason use shared pointers. using shared pointers is good, reason memory management you, not have call delete yourself. in (rare) cases, using smart pointers may not best solution , prefer memory management yourself. important criteria decide use smart pointers or not, serialization being side ...

php - Make every word in a string into classes -

i trying create cms-system can add photos website, , photo-part, want have ability enter programs had used create photo. i should possible add more 1 program. right saving programs in database this: in programs-row: photoshop illistrator indesign then @ website, nice if icons/logos of used programs, show next photo. so question how create new div, new class, based on words programs-row? fx: photoshop illustrator indesign becomes to: <div class="photoshop"></div> <div class="illustrator"></div> <div class="indesign"></div> hope guys can me problem :) thanks ;) use explode function , foreach loop perform string manipulation. $programs = explode(" ", $data); foreach($programs $value) { //echo out html - $value contains program name } i leave figure out how format program name html need.

c# 4.0 - how to calculate the number of the week in a year? -

i calculte number of week in year. i see post in post acepted answer use code: public static int getiso8601weekofyear(datetime time) { // cheat. if monday, tuesday or wednesday, it'll // same week# whatever thursday, friday or saturday are, // , right dayofweek day = cultureinfo.invariantculture.calendar.getdayofweek(time); if (day >= dayofweek.monday && day <= dayofweek.wednesday) { time = time.adddays(3); } // return week of our adjusted day return cultureinfo.invariantculture.calendar.getweekofyear(time, calendarweekrule.firstfourdayweek, dayofweek.monday); } however see problem. number of week repeated if last day of month in sunday. for example, last day of march of 2013 year in sunday. week number 13th, correct. in april, how c# use 6 weeks in month calculate number of week, first week of april has not day of april, because days belong march because last day of week 30th march. c# says first week of apri...

java - Proper way to handle file writes in separate threads -

i looking write files multiple times (100k+) , writes happen on flaky network. this, considering using java executorservice generate threads, i'm not quite sure combination of settings make following happen: only allow 1 write happen @ time (order matters of course) allow write ample time conduct each write (say 5 second) @ point bail if writing slow, have executor collect writes in queue , wait. don't allow overall program exit until thread queue empty. separate threads writers. i.e., if same exact writer comes in function, put in own queue. if different writer pointer comes in, give own queue (no need put separate writers in same queue). i believe can done combination of executor features along .wait() , .notify() command on main program's object. however, not sure how precisely work executor api done. here got: private void writetofileinseperatethread(final printwriter writer, final string text) { executorservice executor = executors.newsinglethrea...

javascript - How can I only run an AJAX call on change when the mouse (or finger) is no longer dragging? -

i have series of interactive sliders change calculated values. the calculations run on every tiny move of dragged handle (via mousedown or touch drag event). i need update database values prefer grab values after user "drops" handle. how can determine if finger or mouse down, in order skip ajax call? function handleisbeingdragged() { // calculations based on input values here // pseudo-code check mouseup event if (mouseup) { // save if mouse - avoid hundreds of updates per drag event $.ajax(); } } you need add bit of hysteresis code. it happens wrote generic debounce function another answer here on so useful this. here's how you'd use it: function savethedata() { $.ajax(); /// } var savethedatadebounced = debounce(50, savethedata); function handleisbeingdragged() { savethedatadebounced(); } the debounce function: // debounce - debounces function call // // usage: var f = debounce([guardtime, ]...

javascript - Not getting json the way I want -

i trying send or retrieve, not sure fault is, in specific way... here how should when using json.stringify(test): {"1":"<div class=\"test\">test1</div>","2":"<div class=\"test\">test2</div>","1":"<div class=\"test\">test1</div>"} but ajax/json return looks this: ["'1':'<div class='test'>test1</div>'","'2':'<div class='test'>test2</div>'","'3':'<div class='test'>test3</div>'"] i need curly brackets @ beginning , " not there. here how send , data. test.php $test = array(); $test[] = array('id' => '1', 'name' => 'test1'); $test[] = array('id' => '2', 'name' => 'test2'); $test[] = array('id' => '3', 'name...

apache - WordPress and www subdomain -

i have setup wordpress domain xyz.test. in domain configuration have set entry www subdomain same entry primary domain ( xyz.test ). however, when entering www.xyz.test in browser, not go wordpress server, returns apache`s "no content message". how solve issue? apache allows name based virtual hosts. means can host multiple fqdns on same ip address. need add name based virtual host www.xyz.test points same directory. or add server alias in xyz.test virtualhost configuration: servername xyz.test serveralias www.xyz.test

jquery - Best way to form submission without using form action in JavaScript -

i building phonegap application using javascript, html , jquery mobile. all html in same file, separated <div data-role="page"> pages. several pages have form including 1 or more text/selection input , submit button. the submit not traditional form submit button button using onclick runs javascript function can many things. i want form have features: when pressing button , after running function, clear form. in cases function should change page. the enter button on 1 of inputs should submit form (activate function). should use form html tag? if should use action? how clear form? etc. if trying bind onclick input type="submit" you're gonna have bad time. unfortunately if return false or e.preventdefault when clicking button, form still sends submit trigger once onclick code finished submit. example: <form action="woot.php" method="post"> <input type="submit" value="submit...