Posts

Showing posts from September, 2014

c++ - Performance difference of iostream console output between Windows and OSX? -

given following simple loop: int main (void) { (int = 0 ; < 1000000; i++) { std::cout<<i<<std::endl; } } running code on clean windows 8 professional using microsoft visual studio 2012 takes 15 secs every 100k prints. on mac os x , using same computer , takes barely 3 secs xcode output 1 mill lines. i'm 100% sure has nothing performance , related output mechanics or something. can confirm this..? know windows & visual studio fine. std::endl flush line. quite expensive this. try : std::cout << << '\n'; in other usual interactive i/o scenarios, std::endl redundant when used std::cout because input std::cin, output std::cerr, or program termination forces call std::cout.flush(). use of std::endl in place of '\n' , encouraged sources, may degrade output performance. source edit : output operation costly , depend on external factors. why slow here. example, terminal applicatio

android - What are arguments in favor of fragments vs. view flipping in this context? -

i amateur hobbyist has been working on trivia game past several weeks. first version of game works user perspective, code super messy , i'm writing second version of game scratch. i'm making significant change way game moves between pages, converting view flipping use of fragments. based on research far, think new design more in line best practices, not sure understand how arguments , against use of fragments apply game. design #1. old design relied on 3 activity files: mainactivity served splash page allowed users select appropriate difficulty level, gameactivity delivered both trivia questions and answers of viewflipper, , scoreactivity reported user's score while making sure highestscoreachieved recorded in preferences. design #2. new design rely on single activity file single fragment container , 4 fragments. startfragment splash page, questionfragment question page, answerfragment answer page, , scorefragment reports final game score. i think fragment-based

fragment - Filtering listview data of simple_list_item_2 items using searchview and arrayadapter -

i'm writing android application (min api 14) consists of 3 tabs hold fragment each. 1 of fragments holds list view (with list view item defined simple_list_item_2) , search view. now, i'm trying filter data in list view room's name (room model) protected searchview searchview; protected listview view; protected list<room> rooms; protected arrayadapter<room> roomadapter; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(getlayoutid(), container, false); view = (listview)rootview.findviewbyid(getlistviewid()); searchview = (searchview)rootview.findviewbyid(r.id.rooms_search_view); view.settextfilterenabled(true); .... roomadapter = new arrayadapter<room>(this.getactivity(), android.r.layout.simple_list_item_2, rooms){ @override public view getvie

hide DIV when radio button is clicked with Javascript -

i want hide div when radio button clicked, cannot figure out life of me.. here code: <li> residential&nbsp;&nbsp;&nbsp; <input type="radio" name="fee" id="residential" class="app_fee" value="<?php echo "$applicationfee_residential" ?>" onchange="mech_application.fee1.value = eval(mech_application.residential.value)" <?php if (isset($_post['fee'])) { print($residentialyes ? "checked" : ""); } ?> /> </li> <li> apartment/commercial <input type="radio" name="fee" id="apartment" class="app_fee" value="<?php echo "$applicationfee_apartment" ?>" onchange="mech_application.fee1.value = eval(mech_application.apartment.value)" <?php if (i

python - pypdf for lists of pdfs -

i have got pypdf work fine single pdf file, can not seem work lits of files, or in loop multiple pdfs, without failing because of string not being callable. ideas can use work around? def getpdfcontent(path): content = "" # load pdf pypdf pdf = pypdf.pdffilereader(file(path, "rb")) # iterate pages in range(0, pdf.getnumpages()): # extract text page , add content content += pdf.getpage(i).extracttext() + "\n" # collapse whitespace content = " ".join(content.replace(u"\xa0", " ").strip().split()) return content #print getpdfcontent(r"z:\gis\masterpermits\12300983.pdf").encode("ascii", "ignore") #find pdfs root, dirs, files in os.walk(folder1): file in files: if file.endswith(('.pdf')): d=os.path.join(root, file) print getpdfcontent(d).encode("ascii", "ignore") traceback (m

dc.js - Simple line chart in DC and CrossFilter -

i have data this var data = [{date:'2013/01/01', claimno:1}, {date:'2013/01/01', claimno:2}, {date:'2013/01/02', claimno:3}] i want plot line chart in dc days on x-axis , total # of claims on y-axis. i have code this var ndx = crossfilter(data); data.foreach(function (e) { e.dd = dateformat.parse(e.dd); e.month = d3.time.month(e.dd); }); var datedim = ndx.dimension(function (d) { return d.dd; }); var datesclaimsgroup = datedim.group(); var claimslinechart = dc.linechart("#claims-line-chart"); claimslinechart .width(200) .height(40) .renderarea(true) .margins({ top: 0, left: -1, right: 2, bottom: 1 }) .group(datesclaimsgroup) .dimension(datedim) .x(d3.time.scale().domain([data[0].dd, data[data.length - 1].dd])) .title(function (d) { return d.value; }); the chart plotted values in y-axis date occurance counts , not claim counts. know supposed use function

A bundle with Infinite Loop on Equinox OSGI Framework -

i have bundle running infinite loop on equinox osgi framework. because of bundle, not able start new bundle when run framework again. how can stop bundle in situation? here command type start framework: java -jar org.eclipse.osgi_3.9.0.v20130529-1710.jar -console it shows message infinitely: hello world! hello world! hello world! hello world! hello world! ........... answering question answer how stop osgi bundle while executing method, , if allowed or not. i assume bundle has entered infinite loop in bundleactivator.start method, , therefore tied osgi callback. not should do!! have no choice shutdown jvm, perhaps forcibly. now problem stop bundle being started again automatically next time launch osgi. simplest way ensure delete "storage" directory osgi remembers list of bundles started last time ran. unfortunately storage directory location subject configuration property , have not specified how have configured osgi. default equinox configuration/o

python - How can I isolate the result of scipy.integrate.quad function, rather than having the result and the error of the calculation? -

i'm trying create array of integral values used further in calculations. problem integrate.quad returns (answer, error). can't use in other calculations because isn't float; set of 2 numbers. integrate.quad returns tuple of 2 values (and possibly more data in circumstances). can access answer value referring zeroth element of tuple returned. example: # import scipy.integrate scipy import integrate # define function wish integrate f = lambda x: x**2 # integration on f on interval [0, 10] results = integrate.quad(f, 0, 10) # print out integral result, not error print 'the result of integration %lf' % results[0]

php - Localhost Wamp Failed to send email -

i downloaded source code here http://www.html-form-guide.com/php-form/php-registration-form.html membership login site site, extracted zip file paste source folder in localhost. followed instructions there, fine can add new users in database. problem encountered can't send confirmation code users email address. got error message "failed sending registration confirmation email." believe part in phpmailer code. if(!$mailer->send()) { $this->handleerror("failed sending registration confirmation email."); return false; } return true; please me new trying 1 thank much! can download file in link provided try it

javascript - How would I create a border with an absolute top and bottom, and fixed sides in CSS only? Image included -

Image
the content in pink behind it. managed create needed extend height via javascript. window resize, onscroll, etc way sides go way down connect bottom. i'd not use js @ all. ideas? added have far: jsfiddle css: body { background: #ff3300; } .border-top { display: block; z-index: 10; position: absolute; top:0; right:0; left:0; margin: 20px 20px 0 20px; border-top: 5px solid #d3ad42; background: none; pointer-events: none; } .border-right { margin: 20px 20px 20px 0; display: block; z-index: 10; position: absolute; top:0; right:0; bottom: 0; border-right: 5px solid #d3ad42; pointer-events: none; } .border-bottom { display: block; z-index: 10; position: fixed; height: 20px; bottom:0; right:0; left:0; margin: 0 20px 0 20px; border-top: 5px solid #d3ad42; background: inherit; pointer-events: none; } .border-left { margin: 20px 0 20px 20px; display:

xamarin.android - Create custom dialog with Grid of buttons -

Image
i trying add custom dialog custom buttons, possible? if so, how can it? it possible. take @ gridview need create custom adapter load images , titles each of items in grid. i go this. create simple class holding information each item in grid. let call griditem . public class griditem { public string title { get; set; } public int imageresourceid { get; set; } public action clickaction { get; set; } } title title under image, imageresoruceid resource drawable id in project, i.e.: resource.drawable.googleplus , clickaction action when item clicked. now create layout items in grid. grid_item.axml . <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <textview android:id="@+id/grid_item_title" android:layout_h

sql - Combining Rows and Taking Averages -

i have table looks #sector max1 avg1 max2 avg2 numb c 133 14 45 3 27 n 174 9 77 3 18 m 63 3 28 1 16 i join rows n , m call x , take max value of max1 , max2 while taking avg of avg1, avg2, , numb in respective columns return #sector max1 avg1 max2 avg2 numb c 133 14 45 3 27 x 174 6 77 2 17 try way: select sector, max1,avg1,max2,avg2,numb tab sector not in ('m','n') union select 'x' sector, max(max1),avg(avg1),max(max2),avg(avg2),avg(numb) tab sector in ('m','n')

Extracting JSON from PHP on Android -

i have tried , tried , can't seem bottom of it. here php code $query = "select `title` `c2torsdb`.`pe_vacancies` active=1 limit 2"; $result = mysql_query($query,$link) or die('errant query: '.$query); /* create 1 master array of records */ $posts = array(); if(mysql_num_rows($result)) { while($post = mysql_fetch_assoc($result)) { $posts[] = array('post'=>$post); } } /* output in necessary format */ if($format == 'json') { header('content-type: application/json, charset=utf-8'); echo json_encode($posts); } and here code snippet httpresponse response = httpclient.execute(httppost); string jsonresult = inputstreamtostring(response.getentity().getcontent()).tostring(); jsonobject object = new jsonobject(jsonresult); //jsonarray innerobj = object.getjsonarray("post"); string name = object.getstring("title"); //string name = name1.getstring(0); log.v("isurgeo

r - Select n first rows of a matrix -

how can select, top 100 rows of matrix in r? found using subset requires condition parameter. need make smaller matrix using first n number of rows same number of columns use head function: head(mat, 100)

.net - Can Page Post Multiple Times Silently -

we're working in .net mvc , have form submit email request. user on unstable internet connection (on airplane) , claims despite clicking send button once, form posted 6 times, resulting in 6 emails being sent. i've been looking around, have not been able find way explain behavior. there way posted form submit multiple times due spotty connection? that depend on actual browser, have yet see 1 doing (in fact, doing dangerous, e.g. in context of online ordering service example). however, such things can happen accident rather easily. people aren't aware of multiple clicks, because don't notice first click triggering anything. might happen browser doesn't show loading action/activity, unstable connections. it's possible due hardware problem (broken mouse button) multiple clicks executed, despite clicking once. just sure, i'd add minimal javascript code form: on submit, disable submit button , avoid further attempts send form (intercept onsubmi

Free dynamically created 3d array in C -

none of answers have found seem address issue. creating dynamic 3d array in c , later freeing it. can store , later access data stored in array using nested loop access violation when trying free using same nested loop setup. going wrong? unsigned char ***buff1; int r, c; somefunction(&buff1, &r, &c); for(int = 0; < r; ++i) { for(int j = 0; j < c; ++j) { free(buff1[i][j]); } free(buff1[i]); } free(buff1); somefunction(unsigned char**** buff, int *nr, int *nc) { ... *buff = (sqlchar***)malloc(*nr * sizeof(sqlchar**)); for(int = 0; < *nr; ++i) { (*buff)[i] = (sqlchar**)malloc(*nc * sizeof(sqlchar**)); for(int j = 0; j < *nc; ++j) { (*buff)[i][j] = (sqlchar*)malloc(256); } } } multiple things wrong: unsigned char**** buff what this, if not wrong? (well, ok, not technically, stylistically anyway...) (sqlchar*)malloc(256); isn't better either, since you must not cast return value of malloc() i

linux - What is the point of adding "IP domain.tld" to the ( /etc/hosts ) file if the server is not gonna be used as a mail server? -

for domain name work.. it's dns servers need point correct ip. once domain tries connect ip the server uses apache configuration determine domain based on in <virtualhost *:80> </virtualhost> for servername , serveralias etc. so if decide not set mail server, never have bother adding ip domain.tld to /etc/hosts file ? i suppose /etc/hosts file needs ip domain.tld if there mail server setup? /etc/hosts file alternative dns host name resolution. has nothing mail servers. but, use mail server has found on network. /etc/hosts local lookup file computer uses specified in /etc/nsswitch.conf. dns network service provided each domain. example, bind. domain zone files configured , hosted on domains primary dns servers. you can configure domain searches in /etc/resolv.conf.

google app engine - Which NDB query function is more efficient to iterate through a big set of query results? -

i use ndb app , use iter() limit , starting cursor iterate through 20,000 query results in task. lot of time run timeout error. timeout: datastore operation timed out, or data temporarily unavailable. the way make call this: results = query.iter(limit=20000, start_cursor=cursor, produce_cursors=true) item in results: process(item) save_cursor_for_next_time(results.cursor_after().urlsafe()) i can reduce limit thought task can run long 10 mins. 10 mins should more enough time go through 20000 results. in fact, on run, task can complete in minute. if switched fetch() or fetch_page(), more efficient , less run timeout error? suspect there's lot of overhead in iter() causes timeout error. thanks. fetch not more efficient use same mechanism, unless know how many entities want upfront - fetch can more efficient end 1 round trip. you can increase batch size iter, can improve things. see https://developers.google.com/appengine/docs/python/ndb/queryclass#kwd

How to erase letters at any position in a string in python? -

for example, string = 'xx22xx_1x_xxxx-xxxx' , x can letters. want delete first 2 positions letters xx , seventh position 1 , in order newstring = '22xx_x_xxxx-xxxx' . function erase letters @ specific positions? this it: def erase(string, positions): return "".join([y x,y in enumerate(string) if x not in positions]) demo: >>> s='xx22xx_1x_xxxx-xxxx' >>> erase(s, (0,1,7)) '22xx_x_xxxx-xxxx' >>>

android - IllegalStateException map size should not be 0 -

this question has answer here: movecamera cameraupdatefactory.newlatlngbounds crashes 16 answers i have mapfragment displays map if user goes away activity (or device goes sleep) map comes onresume gets called , move map marker. however when move camera exception 07-23 16:28:42.725: e/androidruntime(19095): java.lang.runtimeexception: unable resume activity {ecm2.android/ecm2.android.emgnotemapactivity}: java.lang.illegalstateexception: map size should not 0. likely, layout has not yet occured map view. 07-23 16:28:42.725: e/androidruntime(19095): @ android.app.activitythread.performresumeactivity(activitythread.java:2742) 07-23 16:28:42.725: e/androidruntime(19095): @ android.app.activitythread.handleresumeactivity(activitythread.java:2771) 07-23 16:28:42.725: e/androidruntime(19095): @ android.app.activitythread.handlelaunchactivity(activitythread.

java - transferred computers with Android Studio and now have Gradle error -

i had gradle error @ first needed change version. read problem on android studio website, , followed there directions , changed line in gradle file: classpath 'com.android.tools.build:gradle:0.5.0' my error didnt go away , main full of red underlines. restarted android studio , seemed fixed. but when tried compile , run on phone mac book air got error: gradle: problem occurred evaluating root project 'beerportfoliopro'. > sdk directory '/users/mike/library/caches/androidstudiopreview/compile-server/"/applications/android studio.app/sdk"' not exist. my gradle build file: buildscript { repositories { mavencentral() } dependencies { classpath 'com.android.tools.build:gradle:0.5.0' } } apply plugin: 'android' dependencies { } android { compilesdkversion 17 buildtoolsversion "17" defaultconfig { minsdkversion 11 targetsdkversion 17 } sourc

Android - ListView refresh/update from the Main Activity where it is called -

i have application lists values of product variant, unit, , quantity. i have activity listview shown: public class orderform extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_order_form); arraylist image_details = getlistdata(); final listview lv1 = (listview) findviewbyid(r.id.custom_list); lv1.setadapter(new customlistadapter(this, image_details)); } private arraylist getlistdata() { arraylist results = new arraylist(); orderdetailsclass orderdata = new orderdetailsclass(); return results; } public void onadditem(view view){ arraylist results = new arraylist(); orderdetailsclass orderdata = new orderdetailsclass(); orderdata = new orderdetailsclass(); orderdata.setvariants("flavored"); orderdata.setunit("cans"); orde

kwargs - Clunky arg check in Python -

i have function: def check_user(self, **args): allowed = ['name', 'screen_name', 'url', 'description', 'location'] arg_check = [val val in args if val not in allowed] if arg_check: raise valueerror('invalid args: ' + ' '.join(arg_check)) and works, feels unpythonic. there better way of checking this? hoping not have write big if/else statement. this way can iterate on args in loop easily. i think more pythonic version explicitly declare allowed arguments in function definition. replace none default values. def check_user(self, name=none, screen_name=none, url=none, description=none, location=none): # here # ...

Java EE/JPA Integration testing with Rollback like in Spring -

in current project i'm using java ee , jpa. i'm confronted need persist stuff and, working test driven, try figure out how test stuff. in former project spring used @transactional(rollback=true) roll transactions after each test. call persist + flush , query check if jpa done correctly. how do elegantly (minimal configuration work, least possible stuff/resources) in java ee? jeeunit looked answer, no longer continued merged 'pax exam' provide maven support don't have.

Django Login App Returning 403 Forbidden, CSRF Issues -

i'm using tutorial try out creating django login application (super simple stuff...) this code end in template ( index.html ) <div id="login-box"> {{ state }} <form class="login-widgets" action="/login/" method="post"> {% if next %} <input class="login-widgets-text" type="hidden" name="next" value="{{ next }}" /> {% endif %} username : <input class="login-widgets-text" type="text" name="username" value="{{ username}}" /><br /> password : <input type="password" name="password" value="" /><br /> <input class="login-button" type="submit" value="log in" /> </form> <!--<

java - how to manually deploy a webservice on tomcat 7? -

i've created project in i've placed dao package, jpa package, methods package , services package. in last package, i've placed service.java , serviceinterface.java , hibernateutils.java . i'm trying manually publish services on tomcat 7 using eclipse, don't know how? any please?

HL7 in WSO2 ESB - which versions are supported? -

i evaluating esb of wso2 , saw there hl7 feature can install enable hl7 transport. possible specifiy version in use of feature? @ point of application have distinguish between hl7 version 3 , hl7 version 2.6. in advance we use hapi library our hl7 parser, doesn't support hl7v3 messages.so, in esb supports 2.x versions..

activerecord - Heroku Invalid DATABASE_URL when pushing - Heroku bug, fixed now -

edits: this temporary bug heroku have fixed. my push / deploy heroku failing when working last week. it's sinatra app using activerecord on cedar stack. i able app deployed , running several times in heroku. i'm using postgres , cedar stack. i have made 1 whitespace change app.rb , pushed , push not accepted. the app working on server code last week. using database, can see it. heroku info , heroku config lists database_url correctly. i have created new database, , promoted didn't (the running instance used new database okay). i created new dyno running on cedar stack, set new db , provisioned unable push code same error. the following error message: in case i'm trying use latest version of sinatra activerecord see if there bug (it didn't help) git push heroku heroku_bug_before:master counting objects: 20, done. delta compression using 4 threads. compressing objects: 100% (14/14), done. writing objects: 100% (14/14), 1.60 kib, done. total

c# - How does one create a directory with a PCL -

while dealing creating portable class library out of current code project, workarounds obvious , problematic. system.io.directory non-pcl , still need able create directory before creating files inside them. how create folder in c# without being able call directory.createdirectory(..) ? there no built-in file , directory i/o support in pcl, since functionality differs platform platform. however, circumvent issue reference pclstorage in portable class library project. pclstorage provides portable abstraction layer library file , directory i/o reference in portable class library. in platform-specific application implementation, incorporate corresponding implementation library of abstraction layer. pclstorage applicable .net framework 4 , higher, silverlight 4 , higher, windows phone 7.5 , higher, , windows store apps . relies on async , await , means dependent on bcl async package when used e.g. .net 4, silverlight , windows phone 7.5. you might want have

jquery - why aren't these divs in the same position? -

so i've created image tagger saves coordinates database, has been implemented on page designated tagging images. call these images erb block on main page iterate through respected coordinates , use jquery display div (.tagged) @ said location. when tags displayed on main page, not in location in when tagged them on connections page. coordinates same, positions not. have ideas why is? appreciated. html generated main page html generated tagger page jsfiddle of tagger (includes css) erb block iterates through images. in particular case there 4 images. <% if @new_manual.present? %> <% n = 0 %> <% @new_manual.steps.each |step| %> <% n += 1 %> <% i_connection = contact.find(step.input_contact) %> <span class="i_contact i_contact<%= n %>" data-pos-x="<%= i_connection.pos_x %>" data-pos-y="<%= i_connection.pos_y %>" data-pos-width="<%= i_connection.pos_width %>"

jquery - Use jqueryui in index.html -

i finished codecademy tutorials on html, css, js , jquery. trying create on own. can't make simplest thing work. did in kind of "browser consele lab" till now. question is, how use or include jquery in index.html work when open in browser? after searching used google hosted libraries links still doesn't work. have 3 files created: index.html, style.css , script.js. now loads page square on it, nothing when click it, tho jquery code should correct. index.html code: <!doctype html> <html> <head> <title>my thing</title> <link rel='stylesheet' type='text/css' href='style.css'/> <script type='text/javascript' src='script.js'></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> </he

Rails: impressionist_count on a relationship table -

i'm trying use impressionist gem track visits on relation. write method works well: @document.publications.each |publication| impressionist(publication) end i have has_many, :through relation (simplified here works fine): class document has_many :components, :through => :publications end i'm running issue writing query relevant impressions based on component. failing code presently looks this: <% document.components.each |component| %> <%= component.publications.where(:document_id => document.id).impressionist_count %> <% end %> i no method error so: undefined method 'impressionist_count' #<activerecord::relation:blah i know i'm writing failing code incorrectly i'm struggling find correct way write it. you need set-up :counter_cache in association watch video, it's explained http://railscasts.com/episodes/23-counter-cache-column

r - Background color of a .shp using `readShapeSpatial` function -

Image
i looking use background color on .shp using readshapespatial function. can me this?. there function similar (except: readshapepoly ) can used add background color .shp files? this part of code... library(raster) library(maptools) library(mapdata) library(maps) library(scales) pcontorta <- readshapespatial("per_water_areas_dcw.shp") pcontorta2 <- readshapespatial("bol_water_areas_dcw.shp") pcontorta3 <- readshapespatial("ecu_water_areas_dcw.shp") pcontorta4 <- readshapespatial("pry_water_areas_dcw.shp") pcontorta5 <- readshapespatial("per_adm2.shp") pcontorta6 <- readshapespatial("bol_adm2.shp") pcontorta7 <- readshapespatial("ecu_adm2.shp") pcontorta8 <- readshapespatial("pry_adm2.shp") read.csv("coord.csv") -> data data <- data.frame(data[,1:4]) data[data$species=="b._nn",] -> primera data[data$species=="b._ghn",] -> segunda dat

c++ - When should I use a derived class facet in lieu of a base class facet? -

there few standard base class facets in c++ standard library default behavior dependent on classic "c" locale ( std::locale::classic() ). make reasonable switch derived class facets (aka byname facets) behavior depends on locale specified @ construction if program requires culturally-specific functionality. for example, std::ctype provides classic "c" character classification: §22.4.1.3.3 static const mask* classic_table() noexcept; returns: pointer initial element of array of size table_size represents classifications of characters in "c" locale does mean behavior of std::ctype functionally distinct of locale installed? instance, have japanese locale: std::locale loc("ja_jp"); and wanted use facet performed character classification on japanese characters. character classification std::ctype for: auto& f = std::use_facet<std::ctype<char>>(loc); will f 's ctype methods classify characters

Compile GhostScript 9.07 share library on Mac -

i builded ghostscript 9.07 share library. ./configure --prefix=/install/dir/ make make soinstall compile , install stage happy, when run ./gsc command appear error messages dyld: library not loaded: libgs.dylib.9.07 referenced from: /install/dir/./gsc reason: image not found trace/bpt trap: 5 someone can me? in advance have checked dylib file installed? if so, work correctly if force pre-loading of library file (ld_preload)? if works, linker search path include directory dylib installed? chirs

How to create a dynamic array of class in C++ -

i know how create class array dynamically, tried doing class a{ public: int a; int b; } main(){ *temp; temp[somevalue] = new (temp) } but issue dont want limit array somevalue want extend it, thought of using std::vector , std::lis t stuck in implementation simple example of std::vector : class myclass { public: int a; int b; myclass(int a, int b) : a(a), b(b) { } }; std::vector<myclass> temp; temp.push_back(myclass(1, 2)); temp.push_back(myclass(3, 4)); // temp vector contains 2 items

algorithm - calculate a row of numbers(see context for details) -

there 2 rows of numbers, row 1 consecutive numbers starting 0, ask fill out row 2 make sure number in row 2 times of correspoding number in row 1 appearing in row 2. for example: 0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _ _ _ _ _ to more specific, use row1 row 1 , row2 row 2, fill out row2 make sure satisies: row2[i] = count(row2, row1[i]) . count(row2, row1[i]) means frequency count of row1[i] among row2 . out of 1000 runs solution had run loop average of 3.608 times import random def f(x): l = [] in range(10): l.append(x.count(i)) return l fast = list(range(10)) while f(fast) != fast: fast = [] slow = [] in range(10): r = random.randint(0,9) fast.append(r) slow.append(r) while true: fast = f(f(fast)) slow = f(slow) if fast == slow: break print(fast) f(x) takes guess, x, , returns counts. looking solution such f(x) = x. we first choose 10 random integers 0-9 , make

c++ - How to call a method inside the operator> method if the methord called needs to change data members? -

i built own minheap requires me overload operators of classes want push it. have region class method called findsmallestcity. method loops through road objects (each have 2 cities) , returns smallest city in road inside region. my comparison operators need know of 2 regions has smaller indexed city (cities integer values) because if 2 regions have same number of roads determines "smaller" 1 has lower indexed city in it. here code operators , findsmallestcity: int region::findsmallestcity(){ curroad = head; int smallestcity = curroad->getcitya(); while(curroad != 0){ if(curroad->getcitya() <= smallestcity) smallestcity = curroad->getcitya(); if(curroad->getcityb() <= smallestcity) smallestcity = curroad->getcityb(); curroad = curroad->nextroad; } return smallestcity; } bool operator<( const region &lhs, const region &rhs) { if(lhs.numroads < rhs.numroads) return 1; else if

loops - Sub class instance variable in super-class object? -

let's have 2 classes called "superclass" , subclass. subclass extends superclass. i found out it's not possible superclass have instance variable of type subclass. that is, not work: class superclass{ subclass x = new subclass(); } because causes constructors call each other, entering perpetual loop. (because java automatically puts in call super()) is creating subclass instance variable impossible , bad design idea? or there kind of work-around? it bad idea. if super class needs instance of subclass, that's code smell. creates circular dependencies , suggests broken analysis. the workaround/fix bring whatever code super class using subclass super class.

jsp - Display Tag unique row ID issue -

i working on employee leave application managers gets see there sub-ordinate pending leave request, can choose either accept or reject request. i trying achieve using display tag, managed details db , display on jsp. <disp:table name="pendingleaverequest" > <disp:column /> /*sample display column*/ <disp:column /> <disp:column title="approve"> <input type="button" class="btn" value="approve" onclick="approveleave(this,**like pass row id**)" /> </disp:column> <disp:column title="reject"> <input type="button" class="btn" value="reject" onclick="rejectleave(this, **like pass row id**)" /> </disp:column> my problem getting exact row details. went thro' articles on display tag in stacckoverflow, couldn't find

c# - 2 Jquery in one asp.net page -

this question exact duplicate of: problems 2 jquery in 1 page [closed] i have accordion menu , datepicker put .js file in 1 folder named jquery. when running page has both jqueries datepicker works fine accordion menu doesn't work properly. $(document).ready(function () { $(".topnav").accordion({ accordion: false, speed: 500, closedsign: '[+]', openedsign: '[-]' }); }); $(document).ready(function () { $("#txtboxdob").datepicker({ changemonth: true, changeyear: true, showbuttonpanel: true, yearrange: '1940:2040' }); }); .ui-datepicker { font-size:72.5%; background-color:activeborder; co

php - Error Access forbidden -

i encounter error on php , dont know is... says "access forbidden! you don't have permission access requested object. either read-protected or not readable server. if think server error, please contact webmaster. error 403 twitter_sample.com apache/2.4.3 (win32) openssl/1.0.1c php/5.4.7" my code is <?php if($_post) { $file=$_files['media']; $postfields = array(); $postfields['username'] = $_post['username']; $postfields['password'] = $_post['password']; $postfields['message'] = $_post['message']; $postfields['media'] = "@$file[tmp_name]"; $t=new twitpic($postfields,true,true); $t->post(); exit; } ?> <style type="text/javascript"> *{font-family:verdana;} span{font-size:12px;color:#393939;} h3{font-size:14px;color:#5aaaf7;} </style> <body> <h3>upload pic twitpic, , post status on twitter</h3> <form

r - grid: Grid graphics flickering -

i'm designing interactive plot using grid package in r. part of interactivity, repeatedly delete , re-create various parts of plot. however, total number of grid elements (as obtained using grid.ls() command) stays constant; create removed. the problem follows - once i've gone through few cycles of creation , deletion, every deletion make graphic, small, causes interactive parts of plot (those i've been repeatedly deleting , creating) flicker. here's simplest example come - first run code set grid graphic, , repeatedly delete , re-create elements library(grid) pushviewport(viewport()) (x in seq(0, 1, length=5)) { (y in seq(0, 1, length=5)) { pushviewport(viewport(x = x, y = y, width=1/5, height=1/5, name=paste("foo", x, y, sep=""))) grid.rect() pushviewport(viewport(x = 0, 0, width=1/4, height=1/4, name="bar1")) grid.circle(name="testing") grid.text("123")

"updatedb; locate foo" vs "ls -laR > somefile; grep foo somefile" -

on single-user system security isn't issue, there any advantage using "updatedb" , "locate" (or slocate or mlocate) instead of doing "ls -lar > somefile" nightly , using "grep phrase somefile" find files? in fact, seem grep more flexible locate since allows regular expressions. what missing here? for specific scenario, differences marginal, locate database optimized fast searches. on multiuser system, modern locate replacements have various additional security features e.g. not reveal user files have in private directories.

javascript - click image link and fade to new page based upon the url in the div -

i have image link inside div url next page. , want that; when images clicked, fades new page specified there link. if help, awesome. <div> <a href="page three.htm"> <img src="images/tbutton.gif" width="71" height="65" border="0" alt="" id="tbutton" /> </a> </div> think should work: $(img).click(function() { window.location = $(this).closest('a').attr('href'); });

wpf controls - How to bind an item name in the inner collection in wpf -

i have structure like collectiona { itema { name } } i need bind collection's first item's name property textbox control. i have collection in view model. how specify collection's first element textbox control in wpf ? <textbox text="{binding collectiona[0].name}"></textbox>

ruby on rails - Search over multiple key of field type hash MongoID -

i apply filter on multiple key of field type hash reference example code below ######working code class model include mongoid::document field :ld, as: :load_date, type:time field :cls, as: :classification, type:hash def self.base_filter(filters) model.where("cls.#{filters}.r"=>true,"cls.#{filters}.t"=>"news",:load_date.gte=>1.month.ago).count end end ######desired not working code class model include mongoid::document field :ld, as: :load_date, type:time field :cls, as: :classification, type:hash def self.base_filter(filters) model.where("cls.#{filters}"=>{'r'=>true,'t'=>"news"},:load_date.gte=>1.month.ago).count end end is there available in mongoid or if available in mongodb how can call mongoid

ruby - Can gitlab be installed with Cherokee web server? -

i've looked on , can't figure out if use cherokee instead of apache or nginx gitlab. i'd rather not run multiple webservers (and imagine conflict anyway). i'm giving shot on ubuntu server 12.10. for record, i've installed gitlab this guide nginx section (with default settings other passwords, email addresses, , hostname). i'd install gitlab @ git.mydomain.com , prefer local server files located @ /var/www/git.mydomain.com, keep of domains under /var/www/. since have of ruby config done, need hook cherokee hosting ror following guide http://cherokee-project.com/doc/cookbook_ror.html

animation - Google Apps Script fade in -

is there way make image slide show using google apps script ui services.i have created gallery of image doesnt have transition animation. cant find example using effect animation (fade in fadeout). cant find timed events examples. thanks. using jquery, not possible using uiapp. believe caja rejects css3, therefore wouldn't able set attribute either. the thing can suggest utilizing html service allow use of jquery - sure use google's hosted jquery run faster you. hope helps, cheers.

Regarding goal-seek or fsolve (matlab) alike function in VBA -

i have been struggling while try , implement goal-seek function in vba, no results, why turning guys. i have variant of double-values, last element temporary set value, have changed (as in goalseek) sum of entire array equals 1. of course in worksheet, need in vba, handling no cells... is there way call goalseek function in vba without having use worksheet (or cells), , instead working variables? thanks, niklas if it's filling last array item code might come in handy: sub filllastelementwithdifferencetoone() dim arr variant dim integer, sum double redim arr(1 10) 'fill array .01 - .09 = lbound(arr) ubound(arr) arr(i) = / 100 next 'calculate sum = .45 = lbound(arr) ubound(arr) - 1 sum = sum + arr(i) next 'set last item of array arr(ubound(arr)) = 1 - sum 'clean set arr = nothing end sub otherwise please specify want accomplish vba , problems , post code problems occur.