Posts

Showing posts from September, 2012

java - Using generics in method: exception in compilation: complaining about type :cannont convert to -

the code below throws exception in "return list;" typemismatch . suposed not to. public class teste { public <s extends testpai> s getlist(){ testpai list = new testefilho(); return list; } } class testefilho implements testpai{ } interface testpai{ } i found soluction it, puting this public class teste { @suppresswarnings("unchecked") public <s extends testpai> s getlist(){ testpai list = new testefilho(); return (s)list; } } class testefilho implements testpai{ } interface testpai{ } but sounds weird , since have other codes compiled before arent performing that. - im using eclipse ide in windows machine jre1.7.0_51 execution environment. can make works expected (in first code). thanks in advance. all types fixed! you're not using type parameter @ all. simplest way just public testpai getlist(){ testpai list = new testefilho(); return list; }

node.js - Save array of ObjectId in Schema -

i have model called shop whos schema looks this: 'use strict'; var mongoose = require('mongoose'), schema = mongoose.schema; var shopschema = new schema({ name: { type: string, required: true }, address: { type: string, required: true }, description: string, stock: { type: number, default: 100 }, latitude: { type: number, required: true }, longitude: { type: number, required: true }, image: string, link: string, tags: [{ type: schema.objectid, ref: 'tag' }], createdat: { type: date, default: date.now }, updatedat: { type: date, default: date.now } }); module.exports = mongoose.model('shop', shopschema); i want use array tags reference model via objectid obviously. set works fine when add ids property via db.shops.update({...}, {$set: {tags: ...}}) , ids set properly. when try via express.js controller assigned model, nothing gets updated , there no error message. here update function in controller: // updates ex

r - Closest point to a path -

i have 2 sets of points, called path , centers . each point in path , efficient method finding id of closest point in centers . in r. below simple reproducible example. set.seed(1) n <- 10000 x <- 100*cumprod(1 + rnorm(n, 0.0001, 0.002)) y <- 50*cumprod(1 + rnorm(n, 0.0001, 0.002)) path <- data.frame(cbind(x=x, y=y)) centers <- expand.grid(x=seq(0, 500,by=0.5) + rnorm(1001), y=seq(0, 500, by=0.2) + rnorm(2501)) centers$id <- seq(nrow(centers)) x , y coordinates. add column path data.frame has id of closest center given x , y co-ordinate. want of unique ids. my solution @ moment work, slow when scale of problem increases. more efficient. path$closest.id <- sapply(seq(nrow(path)), function(z){ tmp <- ((centers$x - path[z, 'x'])^2) + ((centers$y - path[z, 'y'])^2) as.numeric(centers[tmp == min(tmp), 'id']) }) output <- unique(path$closest.id) any on speeding appreciated. i think data.t

HBase Java API client on Windows without Cygwin? -

we have started project store load of data on hadoop / hbase cluster. have followed tutorial in apache 'quick start' guide, , have got small standalone hbase instance running on 1 of our servers. able use hbase shell create tables, put data, get, scan etc - looks good! now problem: our servers hbase installed linux, developers in company use windows machines - nice if didn't have make in company install cygwin use java api. currently, when try connect running inside eclipse java api, following error: error 2014-12-05 17:13:05,910 [testing] {main} shell - failed locate winutils binary in hadoop binary path java.io.ioexception: not locate executable null\bin\winutils.exe in hadoop binaries. followed by: org.apache.hadoop.hbase.client.noserverforregionexception: unable find region row1 after 0 tries. my question is: possible use java api hbase on windows, connecting server running on linux, without installing cygwin, hadoop , hbase on every developer's machin

javascript - Load list based on value json request -

i ran little problem while doing this. have script loads statelist on page load. great right, cascading countylist whenever state changed sends ajax call server , gets countylist items countylist dropdown depending on state. want little different while keeping same functionality. want able state , county on one-click #load. once hit load send ajax call server , state , county name tied load call. here's there problem, can change statelist value state doesnt change countylist @ all. county list null, have open statelist , click on statelist load county list. tried using on load, click, change ect. doesn't work wondering if can me. enough of me talking here code. $(document).ready(function () { var $statelist = $("#statelist"); $statelist.change(function () { var statelist = $statelist[0]; var countylist = $("#countylist"); $.ajax({ type: "get", cache: false, url: "getco

How to bottom align a cell from a row that breaks accross pages in Office Word 2013 -

Image
i found issue in ms office word 2010/2013. when inserting table spreads more 1 page, if setting "allow rows break accross pages" enabled, , row cell broken acrross 2 pages, there no way bottom align other column. columns in same row aligning bottom of part of row in page 1 instead bottom aligning bottom of row in page 2. i need bottom aligned cells printed on page 2. know work around this? please see attached image illustrates issue trying fix:

php - Placing a widget within Yii's CActiveForm loses CActiveForm functionality -

i use cactiveform::dropdownlist() in many, many places. speed development i'd write widget encapsulates related work. have displays correctly loses validation functionality of cactiveform . here's how create dropdown directly. $activemodel refers model ( cactiverecord ) used cactiveform . $allitems cactiverecord array used populated dropdown. code works perfectly. <div class="row"> <?php echo $form->labelex($activemodel, 'keyid'); ?>: <?php $data = array(); foreach ($allitems $item) { $data[$item->keyid] = chtml::encode($item->keyname); } $options = array( 'prompt' => 'select item', 'options' => array($activemodel->keyid => array('selected' => true)), ); echo $form->dropdownlist($activemodel, 'keyid', $data, $options); ?> <?php echo $form->error($activemodel, 'keyid'); ?> </div>

java - Why the file contains only Line1 -

the generated y.txt contains line1 why line 2 abcent public class writer{ public static void main(string[] args) { try { filewriter fw = new filewriter(new file("y.txt")); printwriter pw1 = new printwriter(fw); pw1.println ("line1 "); pw1.close(); printwriter pw2 = new printwriter(fw); pw2.println("line2 "); pw2.close(); } catch (ioexception e) { e.printstacktrace(); } } } once close printwriter, file closed. the javadocs printwriter.close() state: "closes stream , releases system resources associated it. closing closed stream has no effect."

ruby on rails - Sidekiq monitor no CSS and no Bootstrap in production -

i have problem sidekiq monitor - in development works fine in production not have css working displaying plain web page no stilling on int! body knows how fix please!!!! i using version https://github.com/mperham/sidekiq/wiki/monitoring it works me linking gem assets public folder this: ln -svf /home/deploy/my_app/shared/bundle/ruby/2.1.0/gems/sidekiq-4.0.1/web/assets /home/deploy/my_app/current/public/sidekiq

apache - Can't get wampserver 2.5 accessible from a remote machine -

i desesperate wamp working! i've installed wampserver 2.5 on win7 64bits machine. in httdp.conf file, commented out line regarding vhosts: include conf/extra/httpd-vhosts.conf the httpd-vhosts.conf contains: <virtualhost *:80> documentroot "c:/users/alain/dropbox/website/exemples/grafikart/petsy_alain.dev" servername petsy.dev serveralias www.petsy.dev <directory "c:/users/alain/dropbox/website/exemples/grafikart/petsy_alain.dev"> options indexes followsymlinks multiviews allowoverride <requireany> require local require ip 192.168.1 </requireany> </directory> </virtualhost> (i tried require granted) i first installed wampserver 2.5 64 bits. i able, local machine access http://petsy.dev when tried access http://192.168.1.16/petsy.dev other machine of lan, getting 403 error (forbidden): [thu dec 04 14:43:08.519329 2014] [authz_cor

c# - Creating Drop down List for Create Action -

i have problem creating drop down list in view create action. view show field student number, title , description , nothing program , category drop-down list. not sure how create selectlist , pass view. don't know if did right. public class serviceform { [required] [display(name="student number")] public int student_number { get; set; } [required] [display(name="program")] public selectlist program { get; set; } [required] [display(name = "title")] public string title { get; set; } [required] [display(name = "description")] public string description { get; set; } [required] [display(name = "category")] public selectlist category { get; set; } } public class program { public int id { get; set; } public string program_code { get; set; } public string program_desc {

java - What exactly does the persistence API do and what are the advantages of using it? -

is persistence api similar jdbc? in other words, purpose connecting database? also, use sql? , advantage using persistence have on using jdbc? why not use jdbc? i've looked @ number of websites persistence yet still little confused , why using provide programmer advantage. short answers: the api referenced typically called "jpa" - that'll useful term search when have questions. yes, jpa replacement for/complement jdbc. typically you'll using jpa calls, can jdbc connection jpa implementations , use if need to. yes, uses sql under covers - it's client-layer abstraction around raw sql calls. the advantage allows use object-style interface when interacting database, , skip long, error-prone code related mapping db result columns fields in objects. myobject obj = em.find(somekey, ...); obj.getfoo(); obj.getbar(); is lot more maintainable string query = "select foo, bar, baz, wibble, whomp myobject_table pk_field = somekey";

mysql workbench - Must be possible to filter table names in a single database? -

as far can tell, search filter in navigator search available database names, not table names. if click on table name , start typing, appears simple search can performed beginning first letter of tables. i'm looking way able search table names in selected database. there can lot of tables sort through. seems feature there , can't find it. found out answer... if type example *.test_table or schema name instead of asterisk filter them. key schema/database must specified in search query. asterisk notation works table names well. example *.*test* filter table in schema test anywhere in table name.

iphone app id change bundle prefix -

we have 4 app ids on developer ios porthole. prefix1.com.example.app1 prefix1.com.example.app2 prefix2.com.example.app3 prefix3.com.example.app4 these posted in store. prefix2 , prefix3 older prefix numbers. prefix1 our current number. these apps have been in store bit (years). we require prefix2 , prefix3 app change prefix1 number functions doing. we have tried delete prefix2 , prefix3 application ids, error "can not delete while application in store." or that. we have tried add new ids, new prefix, same bundle , error "bundle used" or that. how change prefix on app3 , app4 latest prefix? turns out of writing, need contact apple have done. respond confirmation , start "engineering ticket". not sure how long going take. post when done how long took. thanks is safe change appid prefix between updates? and can contact apple at -- go https://developer.apple.com/contact/ . -- submit request clicking link under enrollme

html - Do PNGs (or JPGs) have a DPI? Or is it irrelevant when building for retina? -

a simple question have been having great difficulty finding definitive answer to: png files have dpi? or perhaps more importantly, relevant when building retina-enabled sites/apps? i've received psd assets our designer retina ipad app must convert html display within app. typically, receive such files 2048x1536 @ 72 dpi -- double size standard screen dpi. typically use css tell browser how display it. but time designer instructed provide psds @ 1024x768 @ 144 dpi (standard size double dpi.) believe incorrect, dpi setting within photoshop intended print purposes. plus, when save 144 dpi psd png or jpg, same 1 saved 72 dpi (or 30,000 dpi matter) psd. dpi doesn't seem reflected in either setting can see in resultant file nor in different file size. seems, @ best, metadata. so, it's understanding dpi isn't relevant here, , should asking double-sized assets retina projects, confirmation/clarity on issue before asking new assets. work many designers transitio

database - "Respawning" Files in Cpanel -

so straight point- im trying clean host entirely (databases too) , after delete last 2 files wp-content , wp-includes (700mb of files) restored instantly. may simple question me s odd , don`t it. besides file-manager used filezilla , same thing happens(my hosting company su@%$ failed give me reply after 48h). i have recorded short video of problem better understand issue. https://www.youtube.com/watch?v=wql35r0-vvw&feature=youtu.be hope you`ll able me. thank ! i`m working on website ngo after hacked , want wipe every single file server , rebuild files have inside infected pages(php scripts) wont deleted chances of files owned webserver, if compromised via wordpress vulnerability. they're owned webserver , not user, you're unable delete them. if have root/sudo access, can use on command-line remove them. if don't, you'll need host help.

encryption - AWS EMR SSE Consistent view -

i trying create emr cluster on aws below cli command, not create cluster in consistent view , server side encryption flag not getting set (fs.s3.consistent , fs.s3.enableserversideencryption both false in emrfs-site.xml). whats wrong? aws emr create-cluster \ --name "reporting-aws-cli-temp" \ --instance-type m1.medium \ --service-role emr_defaultrole \ --instance-count 2 \ --ami-version 3.3.1 \ --ec2-attributes subnetid=subnet-111111,keyname=somekey,instanceprofile=server-role \ --log-uri s3://some-logs \ --emrfs sse=true,consistent=true,retryperiod=3,args=[fs.s3.serversideencryptionalgorithm=aes256] 2nd part of question have below problem statement csv data want analyze periodically posted aws ec2 instances (server) amazon s3 bucket , using hive read data amazon s3 bucket , doing analysis. data post on amazon s3 needs encrypted , hive has first decrypt file , analyse current state able achieve following periodically post file s3 in 3 separate way plain csv fi

javascript - show cursor/caret at the beginning of input box -

problem : have html text input box text in it, when user click input box, have caret/cursor appear @ beginning of input box. i move caret using setselectionrange() function, don't effect caret shown @ end of text input box moved beginning. @ beginning of input upon shown. example: http://jsfiddle.net/edh8mkht/1/ html <body> <input type="text" id="myp" onmousedown="mousedown()" value="mozilla" /> </body> js function mousedown() { document.getelementbyid("myp").style.color = "green"; document.getelementbyid("myp").setselectionrange(0,0); } question 1 : i use mousedown event move caret, doesn't move caret @ all, same thing happens if use onfocus event. because caret appears after 2 events , making setselectionrange has no effect? question 2: what's way solve problem using javascript? note: cannot use placeholder. fiddle showing initial s

qt - How to make image to fill qml controls button -

i want icon fill button . here code: import qtquick 2.3 import qtquick.controls 1.2 import qtquick.layouts 1.1 import qtquick.window 2.2 window{ id: root title: "settings" flags: qt.dialog minimumheight: 700 minimumwidth: 700 maximumheight: 700 maximumwidth: 700 columnlayout{ id: columnlayout anchors.fill: parent rowlayout{ button{ iconsource: "images/1x1.png" checkable: true checked: true layout.minimumwidth: 100 layout.minimumheight: 100 } button{ iconsource: "images/1x2.png" checkable: true checked: false layout.minimumwidth: 100 layout.minimumheight: 100 } button{ iconsource: "images/2x1.png" checkable: true che

Access 2013 not prompting for password to push information to Sharepoint 2007, causing crashes -

we have sharepoint 2007 server list enter information through access interface. for awhile of our users have been using access 2010 no problem. however, couple of our users have access 2013 , unable use push information sharepoint. i have narrowed down password information not being passed sharepoint let send data. our access 2010 users have enter password each time use it. our access 2013 users not prompted password , freeze when try view list connected sharepoint server. the way access 2013 not freeze if user goes external data , use imports , links sharepoint site. when this, asked username , password. after this, can click of list , use them normal. however, access closed same issues occurs. is there way turn on password prompts access 2013? i've looked @ ways retain information, finding useful site https://accessexperts.com/blog/2012/01/18/how-to-save-your-sharepoint-password-in-windows/ . however,none of our users have access add site trusted list , o

sql - PHP Populate Dropdown From Database and then Update on Button Click -

i'm having trouble populating dropdown list database , updating selected item on button click. i'm trying have when pick option b in dropdown, it'll update option on click of submit button. i can dropdown box populate fine, when clicking button won't update correctly. i'm learning go, pointers appreciated. <form id='filter' name='filter' method='post' action=''> <?php $getissuedvouchers2 = "select * vouchercodes status = 'active'"; $issuedvouchersresult2 = mysql_query($getissuedvouchers); ?> <select> <?php while ($ivselectrow = mysql_fetch_array($issuedvouchersresult2)) { echo "<option name='updatestatus'>" . $ivselectrow['vouchid'] . "</option>"; }

EXCEL VBA: Compare then Update/change, remove and add between 2 sheets -

i'm comparing 2 worksheets in same workbook, row row (and each cell of row) code able identify of row has been changed(change), if doesn't exist in second sheet show removed (remove), or if exist in second sheet needs added (add). tab in work sheet are: original \ updated \ changes what trying achieve create fourth 1 (final) changes applied, before there found problems code (btw source , template found at: here )it works great(with remove , add), when using great number of registries (hundreds) of them, flagged changes doesn't display right values, , sometimes, reworking in same tabs , trying apply the macro again gets error @ marked line(*). i.e.: original \ updated \ changed car_01 |500| ms \ car_01 |750 |ms \ car_01| 15.5| ms at first approach problem thinking related type of parameter @ cells vs input has in macro far haven't found right type (already have try it: general, number , te

javascript - underscore template: lookup a variable by name -

i'm looking way lookup value of variable passed underscore template, using string contains variable name. example, suppose template contains following: <% _.each(detailfields, function(fieldname) { %> <% print(getvaluebyname(fieldname)); %> <% } %> getvaluebyname() function i'm looking for. according underscore documentation, values passed _.template() put local scope using 'with' statement. if understand correctly, means window[fieldname] or this[fieldname] won't work. eval(fieldname) option, i'd rather avoid using eval(). thanks mu, miss obvious. :) thought backbone.marionette passing in attributes of model. didn't realize passing in whole model well, , conveniently named "model". model.attributes[fieldname] solved issue.

svg - Lower case component names (use) are no longer supported in JSX: <use> -

i using svg element in react jsx, thinking <use> valid in jsx. following error correct ? lower case component names (use) no longer supported in jsx: see http://fb.me/react-jsx-lower-case while parsing file <svg classname="icon"> <use xlink:href="#icon-call"></use> </svg> using dangerouslysetinnerhtml fixed it. <svg classname="icon" dangerouslysetinnerhtml={{__html:'<use xlink:href="#icon-dnd-on"></use>'}}> </svg> tl;dr i think you're stuck using dangerouslylsetinnerhtml now. explanation react supports subset of html/svg elements , <use /> isn't supported yet . with v0.12 react switched restricting lower-case tag names html/svg elements , you've encountered fails elements aren't on whitelist. fb recommends opening issue valid tags don't yet support. you can use {react.createelement('use')} force react render <

Error while installing heroku toolbelt on Windows 8: Unable to execute file C:\Program Files(x86)\Heroku\ruby-1.9.3\bin\gem.bat -

Image
i wanted install heroku toolbelt. choose full instalation. while install got error. after install finishes heroku login not work. try out: follow link no matter related running game on windows 7, try on windows 8. , let know if works.

javascript - How can i add simple link in html5 desktop notification -

how can add simple link (a href) in html5 desktop notification on body section? try onclick function, work's few seconds. if try press later notification disappear , nothing do. best way link. try write, print me text. var notification = new notification('title', { icon: '...', body: '<a href="#">aaa</a>' }); unfortunately there no support links , other markup in html notifications. method clickable link notification use onclick: function makenotification() { var notification = new notification('this clickable notification', {body: 'click me'}); notification.onclick = function () { window.open("http://stackoverflow.com/"); }; } function notifyme() { // let's check if browser supports notifications if (!("notification" in window)) { alert("this browser not support desktop notification"); } // let's check if user okay notificat

sublimetext2 - Sublime text editor: Change plugin hotkey? -

in sublime text 2 or 3 (i use both, , answer same both), how change hotkey of installed plugin/package? (on windows or linux / ubuntu) i know how change key bindings of built-in sublime commands (preferences > key bindings). instance, 1 binding have is: {"keys": ["ctrl+super+b"], "command": "show_panel", "args": {"panel": "output.exec"}} but in case of plugin, how know string use "command"? there easy way find out "command" arbitrary function in sublime? i general answer applies plugin 1 install. though example, today i'm trying change hotkey plugin called simpleclone, has assigned ctrl + shift + right split right. ctrl + shift + right rather poor hotkey choice maker of plugin since has use in operating system: when typing selects word right. hence want change assigned key binding. if plugin has shortcuts defined, in *.sublime-keymap files. if want find shortcut gues

indexing - What is the use case that makes EAVT index preferable to EATV? -

from understand, eatv (which datomic not have) great fit as-of queries. on other hand, see no use-case eavt. this analogous row/primary key access. docs : "the eavt index provides efficient access given entity. conceptually similar row access style in sql database, except entities can possess arbitrary attributes rather being limited predefined set of columns." the immutable time/history side of datomic motivating use case it, in general, it's still optimized around typical database operations, e.g. looking entity's attributes , values. update: datomic stores datoms (in segments) in index tree. navigate particular e's segment using tree , retrieve datoms e in segment, eavt datoms. comment, believe you're thinking of navigation of more b-tree structures @ each step, incorrect. once you've navigated e, accessing leaf segment of (sorted) datoms.

visual studio - Team Foundation Server (TFS) "My alerts" doesn't exist after configuring SMTP server -

we followed these guides in attempt turn on email/text alerts tfs work items when updated or changed: http://msdn.microsoft.com/en-us/library/ms181334.aspx fta: web browser, connect team project , open alerts management (my alerts from profile menu). if don't see option, must configure smtp server support tfs. we didn't see option, followed guide set smtp server using guide here: http://msdn.microsoft.com/en-us/library/ms400808.aspx fta: verify configuration, open alerts management. might need refresh browser see option if enabled smtp server. we've sent successful test email through administration area can't verify because users not seeing "my alerts" option set own alerts in online portals. is there else need not included in guide set these up? if go following url on tfs server: https://nakedalm.visualstudio.com/defaultcollection/democorp/_admin/_alerts (replacing server yours) should see alerts

asp.net - Why is my datetime model property required -

i have vb.net mvc3 project (.net 3.5) , inside project model nullable datetime ( datetime? ). this property has no <required()> annotation, yet reason not allowed left empty in form. when is, generates validation error of "a value required." so, nullable thing important. once nullable, datetime can bound nothing after containing object, model, autobound controller parameter. if have same issue, sure set datetime new datetime, or else views flip out having nothing editorfor helpers. its important, apparently, shut down visual studio every often. connection between iis express , visual studio seems flaky time time: looks older version of site kept getting deployed instead of version had in front of me.

How to send JavaScript collection to PHP variable? -

i trying send data form php file using javascript. php file pushes data database. now, works have problem array getelementsbyclassname . after sending database can see "array" no values of array. here's js: function przekaz_form($wejscie) { var datas = document.formularz.datas.value; var klient = document.formularz.firma.value; var comment = document.formularz.comment.value; var collect = document.getelementsbyclassname($wejscie); var datan = document.formularz.datan.value; var items = new array(); for(var = 0; < collect.length; i++) { items.push(collect.item(i).value); } jquery.ajax({ url: 'addtobase.php', type: 'post', data:{ devices: items, datas: datas, klient: klient, comment: comment, datan: datan }, success: function(output) { alert('success'); } }); }

jquery - ElevateZoom - Uncaught TypeError: undefined is not a function - Magento 1.9.1 RWD -

i began using magento 1.9.1 ce build new version of website. after making minor changes, noticed on product view page, image zoom , ability select different product images under more views both not working. here example of product page displaying behavior: http://birne.pe/vestidos-faldas/faldas/test.html after digging, discovered magento uses elevatezoom plugin functionality. however, can't figure out might have changed cause break. this error message seeing: uncaught typeerror: undefined not function app.js:1194 productmediamanager.createzoom app.js:1194 productmediamanager.initzoom app.js:1256 productmediamanager.init app.js:1268 (anonymous function) app.js:1277 c jquery-1.10.2.min.js:4 p.firewith jquery-1.10.2.min.js:4 x.extend.ready jquery-1.10.2.min.js:4 q jquery-1.10.2.min.js:4 anybody else experiencing same issue or know how can fix it? or there more information should add improve chances of receiving answer question? thank you! in c

c# - Server resource usage between a class with Reflection and a new class .NET -

i have make loop find id of xml document id taken object name. object name taken textbox in .net web page control, have 2 choices: use vector of object (new custom class id , value).creating , filling in control when user put value in textbox. use reflection in controller find textboxes , take name of each 1 on list use later in loop. the question have server resource usage each of choices have. see needs more resourses , kind of slower other.

sql - List all championships that were in progress in a month/year -

i'm trying solve select statement. problem list championships in progress in month , year. for exemple, wanna list all championships in progress in march, 2005. i have columns: table: championships (id_champ, name, startdate, enddate). how can list championships in progress in march, 2005? i'm trying this: select * championships (month(startdate) <= 3 , year(startdate)<=2005) , (month(startdate)<=3 , year(enddate)<=2005 anyone here knows correct way or best way solve it? to catch active in march 2005: select * championships year(enddate) = 2005 , 3 between month(startdate) , month(enddate).

java - Printer port class -

please there native class has functions usb printer port updating , control? i'd queue print jobs, update , modify print files. hoping java has solutions cos i'd read data mailbox/website , queue them printing, changing queue jobs if desired, during printing process

ios - deleting records that has recursive relationships in coredata -

Image
i have below relationship in model. userstatement has levelupstatement , parentstatement has a-to 1 relationship between. problem have when try delete levelupstatement. have nullify both end of relationship , when try delete below: (mainuserstatement parentstatement) self.mainuserstatementmodel.levelupstatement = nil; self.mainuserstatementmodel.levelupterm = nil; [[ashcoredatastack defaultstack].managedobjectcontext deleteobject:self.mainuserstatementmodel.levelupstatement]; error getting is: terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-deleteobject: requires non-nil argument'. i know managedobjectcontext exists. problem should not there. how can safely delete levelupstatement without effecting levelupterm , parentstatement? you need change order of lines of code: [[ashcoredatastack defaultstack].managedobjectcontext deleteobject:self.mainuserstatementmodel.levelupstatement]; self.mainuserstatementmodel.le

java - How to get most recent 100 data from a Map? -

i have map of long , string - map stores timestamp key , value data. map<long, string> eventtimestampholder = new hashmap<long, string>(); now want 100 recent data above map looking @ timestamp part of key , keep on adding data in list of string. in general populate 100 recent data in list. what best way this? can use treemap here , sort keys basis on timestamp properly? in general timestamp going - 1417686422238 , in milliseconds in case mean "recent" added, can try linkedhashmap maintain order of insertion. can iterate on first 100 items. you can iterate on map this: for(long key : eventtimestampholder.keyset()) { string value = eventtimestampholder.get(key); }

c - How to read input of unknown length using fgets -

how supposed read long input using fgets() , don't quite it. i wrote this #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char buffer[10]; char *input; while (fgets(buffer,10,stdin)){ input = malloc(strlen(buffer)*sizeof(char)); strcpy(input,buffer); } printf("%s [%d]",input, (int)strlen(input)); free(input); return 0; } #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char buffer[10]; char *input = 0; size_t cur_len = 0; while (fgets(buffer, sizeof(buffer), stdin) != 0) { size_t buf_len = strlen(buffer); char *extra = realloc(input, buf_len + cur_len + 1); if (extra == 0) break; input = extra; strcpy(input + cur_len, buffer); cur_len += buf_len; } printf("%s [%d]", input, (int)strlen(input)); free(input); return 0; }

javascript - Sticky boxes with option to close -

i'm new web development , might not using right terminology, making sense. trying have sticky boxes contain words user submitted form pressing enter. couldn't find better example of i'm trying achieve picture plug-in 8 in link attached. boxes want in background, behind calendar pop-up window. want have option in box close box (e.g. little "x" icon). final submission when user clicks submit button. thanks lot tips http://tutorialzine.com/2013/04/50-amazing-jquery-plugins/ the answer below. shows how add 'sticky' tags website (similarly ones used stackoverflow: jsfiddle.net/5gd6r/4

Tableau calculated field-formula -

i trying create simple formula calculation in table . this table structure experience platform revenue pc website 100 mobile android 20 mobile ipad 10 mobile iphone 20 my calculation trying find share : calc1 : share of site= sum of revenue mobile / sum of revenue (mobile+pc) calc2: share of platform= sum of revenue apps/revenue mobile can highlight how can create formula , new tableau. thanks for calc1, try calculated field like: sum(iif([experience]='mobile',[revenue],0))/sum([revenue]) calc2 uses similar logic: sum(iif([platform]='android',[revenue],0))/sum(iif([experience]='mobile',[revenue],0)) you should able need using tableau built in table calculations, dragging in need , adjusting filters necessary.

c++ - How do I tell which version of g++ is the earliest version that uses `atomic` instead of `cstdatomic`? -

i have 1 system runs g++ 4.4.7 , supports #include <cstdatomic> . have system runs g++ 4.9.1 , supports #include <atomic> . how can discover earliest version of g++ supports <atomic> , or conversely latest version of g++ supports <cstdatomic> , without building compilers , doing manual search? more broadly, how can answer question arbitrary system header x? there gcc git mirror these things. <cstdatomic> first appears in april 2008 this commit , disappears in december 2009 this one . far can tell, <atomic> appears in same commit. looking @ tags , latter round time when gcc 4.5 released, , sure enough, browsing through source trees, <cstdatomic> disappears 4.5 (but kept in later 4.4 releases) , <atomic> appears in place. addendum: place in source tree libstdc++v3/include/ . <cstdatomic> in c_global , <atomic> in std .

c# - How to get a projectile to shoot towards a gameobject -

im working on turretai. have when enemy within range turret targets enemy i'm unable turret shoot projectiles toward enemy. have turret class. using unityengine; using system.collections; public class defence : monobehaviour { public float distancefromcastle,cooldown; public gameobject enemy; public gameobject bullet; public int protectionradius,bulletspeed; // use initialization void start () { protectionradius = 35; bulletspeed = 50; cooldown = 5; } // update called once per frame void update () { enemy = gameobject.findgameobjectwithtag("enemy"); if(enemy != null) { distancefromcastle = vector3.distance(gameobject.findgameobjectwithtag("enemy").transform.position,gameobject.findgameobjectwithtag("defence").transform.position); //print (distancefromcastle); if(distancefromcastle <= protectionradius)

python regex- getting everything (except \n) between two characters in a multiline string -

i have file input: >x0 cuugacgauca cgcaucg >x55 uacggcgg uucagc aucg >x300 aaacccgggg and need concatenation of lines between '>' characters: cuugacgaucacgcaucg uacggcgguucagcaucg aaacccgggg my attempt use "re.match(r'^>.*\n(.*)>.*' ,a,re.dotall)" , delete '\n' each match, regex not returning anything. wrong? some people, when confronted problem, think "i know, i'll use regular expressions." have 2 problems. - jamie zawinski that being said, why not more understandable string processing? tmp = [] seqs = [] open('txtfile') f: line in f: if line.startswith('>'): seqs.append(''.join(tmp)) tmp = [] else: tmp.append(line.strip()) else: seqs.pop(0) seqs.append(''.join(tmp)) alternatively, if want use regex, try first stripping newlines , splitting >x[digit] patterns: re.split(r&#

css3 - How to I make a parent div resize height based on children dimensions in this example? -

i'm making section lists user reviews on website i'm working on. problem i'm having when posts long of review, div won't resize fit text, text either overflows, or cuts off @ bottom of div. wish more specific question, have many nested div's here, don't know 1 should edit. http://codepen.io/donnaloia/pen/mykeob html <br> <br> <br> <div class="maincontainer"> <div class="reviewrow"> <div class="commentpanel"> <div class="reviewerpic"> <img src="mugshot.img"></div> <div class="authordiv"> <strong>reviewed dave</strong> <div class="stars"><img src="/static/img/stars.png"> </div> <hr> <div class="reviewcomment">this less "pros , cons" review useful commentary kindle compared other ereaders , means ebook industry. (i believe has changed kindle's cre

c++ - using vectors to make generic stacks -

so trying define stack class, uses vectors make generic stack. reason when try create new stack receive error saying nothing was declared, understand saying nothing made, never made new object. did follow guide on how make generic stacks. http://www.tutorialspoint.com/cplusplus/cpp_templates.htm here stack class used: #ifndef stackers #define stackers #include <vector> #include "wrapper.hh" template <class t> class stack { private: vector<t*> elems; public: stack(); void push(t* obj); // push element t* pop(); t* peek(); // pop element t* findmax(); t* findmin(); bool isempty(); }; template <class t> bool stack<t>:: isempty(){ return elems.size()==0; } template <class t> void stack<t>::push (t* obj) { // append copy of passed element elems.push_back(obj); } template <class t> t* stack<t>::peek () { // append copy of passed element

Google Cloud SDK 0.9.39 still fails to do setup-managed-vms -

i updated gcloud components on os x mavericks laptop, have: $ gcloud version google cloud sdk 0.9.39 $ boot2docker version boot2docker-cli version: v1.3.2 git commit: e41a9ae i hoping managed vms setup work, alas: $ gcloud preview app setup-managed-vms select runtime download base image for: [1] go [2] java [3] python27 [4] please enter numeric choice (4): 2 pulling base images runtimes [java] google cloud storage pulling image: google/appengine-java traceback (most recent call last): file "/users/hussein/google-cloud-sdk/./lib/googlecloudsdk/gcloud/gcloud.py", line 175, in <module> main() file "/users/hussein/google-cloud-sdk/./lib/googlecloudsdk/gcloud/gcloud.py", line 171, in main _cli.execute() file "/users/hussein/google-cloud-sdk/./lib/googlecloudsdk/calliope/cli.py", line 385, in execute post_run_hooks=self.__post_run_hooks, kwargs=kwargs) file "/users/hussein/google-cloud-sdk/./lib/googlecloudsdk/call

url facade in laravel 5 -

in l4 worked perfectly: <a href="{{ url::to('autor/'.$o->surname)}}">{{$o->surname}}</a> in l5 produces blank screen and need resort this: <a href="autor/{{ url::to($o->surname)}}">{{$o->surname}}</a> how adjust syntax make work? where docs me? laravel 5 uses {{$var}} escape content , use {!!$var!!} echo unescaped strings laravel 5 docs

python - socket.settimeout quits program not using except clause -

i have below python code, no data received , program quits without running except clause print , return statements any ideas on happening? sock.settimeout(10) try: pkt = sock.recv(255) except socket.error: print "connection timed out!" return the problem socket.timeout exception different exception socket.error . so, except socket.error: doesn't catch socket.timeout same reason except valueerror: doesn't catch keyerror . (the documentation isn't obvious in 2.x. 1 of many things cleaned in python 3.3/pep 3151—see the nice new docs —but long you're sticking 2.x don't benefit that.) the right solution handle right error: sock.settimeout(10) try: pkt = sock.recv(255) except socket.timeout: print "connection timed out!" return if want handle socket errors (like, say, failure recv call) same way: sock.settimeout(10) try: pkt = sock.recv(255) except (socket.timeout, socket.error) e: print &

regex - python - find text between two $ and get them into a list -

i have text file - $ abc defghjik here not $ not here go there $ .... i want extract text between 2 $ signs , put text list or dict. how can in python reading file? i tried regex gives me alternate values of text file: f1 = open('some.txt','r') lines = f1.read() x = re.findall(r'$(.*?)$', lines, re.dotall) i want output below - ['abc', 'defghjik', 'am here', 'not now'] ['you', 'are not', 'here go there'] sorry new python , trying learn, appreciated! thanks! in regular expressions $ character of special meaning , needs escaped match literal character. match multiple parts use lookahead (?=...) assertion assert matching literal $ character. >>> x = re.findall(r'(?s)\$\s*(.*?)(?=\$)', lines) >>> [i.splitlines() in x] [['abc', 'defghjik', 'am here', 'not now'], ['you', 'are not', 'here go there']]

loops - c++ confusion on outputs -

this might seem stupid question, dont understand difference between these functions. setting both of these 0, why xxx() print 0,2,4,6,4,2,0 , xxy() print regular 0,1,2,3,4,5. question i'm asking is, why xxx() reduce after hits max value allowed '6' void xxx(int n) { cout << n; if (n < 5) { xxx(n + 2); cout << n;; } } void xxy(int n) { cout << n; if (n < 5) xxy(n + 1); } int main() { xxx(0); xxy(0); } well... pay atenciĆ³n here: cout << n; if (n < 5) { xxx(n + 2); cout << n; } when have recursive call xxx(n+2) current "iteration" stacked start new function. when function ends, previous iteration proceeds normally. therefore when max value (6) reached, iteration end continuing cout of previous "iteration"... in previous iteration n value 4... value displayed , iteration end continuing cout of n in previous iteration 2 , on... in

ddos - How can I configure NGINX to block HTTP and XMLRPC (Wordpress pingback) attacks? -

hey how can configure nginx block http attacks , xmlrpc attacks? thanks actually makes more sense: if ($http_user_agent ~ wordpress) { return 444; } returning status code 444 tell nginx not send response bad requests , close connection immediately. save lots of traffic , resources compared sending 403 page other response suggests. source: https://javapipe.com/block-wordpress-xml-rpc-ddos-attacks-with-nginx

groovy - Binding 'and' to && -

i'm trying build groovy dsl binds and && : def binding = new binding([ and: && ]) def shell = new groovyshell(binding) println shell.evaluate ''' true , false ''' } however i'm getting compile-time error: >groovyc andor.groovy org.codehaus.groovy.control.multiplecompilationerrorsexception: startup failed: andor.groovy: 2: unexpected token: && @ line 2, column 7. and: && ^ 1 error how can bind "and" && operator? groovy parses left operand right left(operand).getright() . turning and && operator parser related, , doubt able without tweaking groovy source code, antlr, etc. to snippet working, code intercepts boolean::call metaprogramming, creating new eboolean object. uses getproperty method intercept getright() part: import org.codehaus.groovy.control.compilerconfiguration class eboolean { boolean left op op def