Posts

Showing posts from February, 2015

ruby - Rails 3 creates duplicate form object for nested records when updating them -

there 2 models class category < activerecord::base has_many :products accepts_nested_attributes_for :products, allow_destroy: true validates_associated :products end class product < activerecord::base belongs_to :category validate_uniqueness_of :name, scope: :category_id end and form category <%= simple_form_for @category |f| %> <%= f.simple_fields_for :products |p| %> <%= render :partial => "product_fields", :locals => { :f => p } %> <% end %> <% end %> as can see there uniqueness validation makes sure products uniq within category. problem starts when validation not passed. calling @category.update_attributes(params[:category]) results in duplicate form object. when rendering form errors rails creates additional associated product id of duplicate record different name. for example: given have 2 products within category: bread , butter. if set butter bread when editing category's pro

aem - Error Handling in CQ5.6.1 -

i working on cq 5.6.1 project. trying find how redirect 404 error custom error page specific application. reading various articles on error handling, find /apps/sling/servlet/errorhandler/404.jsp 1 handles 404 error. since there multiple projects deployed in cq, need show error page create under project. is, 404 error project1 must redirected custom error page under project1. thinking should include redirection code /apps/sling/servlet/errorhandler/404.jsp. right approach or there better way automatically redirect projects error page? this right approach. don't have create such custom handler manually - acs aem commons provides error page handler supporting many sites.

amazon web services - S3 IAM policy works in simulator, but not in real life -

i have client want able upload files, not navigate freely around s3 bucket. i’ve created them iam user account, , applied following policy: { "version": "2012-10-17", "statement": [ { "sid": "stmt1416387009000", "effect": "allow", "action": [ "s3:listallmybuckets" ], "resource": [ "arn:aws:s3:::*" ] }, { "sid": "stmt1416387127000", "effect": "allow", "action": [ "s3:listbucket" ], "resource": [ "arn:aws:s3:::progress" ] }, { "sid": "stmt1416387056000", "effect": "allow",

>=sysdate-30 business day's data pick in oracle -

i need pick sysdate- 30 business days data table test. when doing select * test cre_d>=sysdate-30; it include saturday,sunday , holidays if any.i want pick sysdate- 30 business days(idealy sysdate-38 because 4 weekend came in week not looks correct because holidays may came , sysdate-38 should change sysdate-39.) kindly suggest best way doing this.thanks! create table t_tb select sysdate-level dt dual connect level < 50; select to_char(dt,'d'), dt t_tb to_char(dt,'d') between 2 , 6and rownum <= 30 is want?

scala - What are the advantages of SpecificMutableRow in Spark SQL? -

from comments seems: a parent class mutable container objects reused when values changed, resulting in less garbage. and a row type holds array specialized container objects, of type mutablevalue, chosen based on datatypes of each column. intent decrease garbage when modifying values of primitive columns. source - https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/specificmutablerow.scala can explain how efficent? fact avoids boxing enough? it avoids boxing in storage, helpful when combined specific interface (i.e. parquet reader or code generated expression evaluation). the other advantage is reused (unlike generic row). many operations can operate on range of data without allocating objects.

html - Node.js posting undefined -

i trying post , insert data html form using node.js having problem posting data html form node.js , extracting data passed undefined inserting in database using node-mysql new node.js here app.js code var app = require('express')(); var server = require('http').server(app); var io = require('socket.io')(server); var bodyparser = require('body-parser'); var jsonparser = bodyparser.json() var sql = require('mysql'); var connection = sql.createconnection({ host : 'localhost', user : 'root', password : '', port : '3306', database : 'node' }); server.listen(3000); app.get('/nodethis', function (req, res) { res.sendfile(__dirname + '/insert.html'); }); app.use(bodyparser.json()) app.post('/nodethis', jsonparser, function (req, res) { var post={user_name:req.body.name1,user_what:req.body.what,user_why:req.body.why}; console.log(post); }); here html

PHP Multidimensional Array to flat csv -

i'm working on small analytics system fetches information different advertising sources , puts them array. need export information flat csv excel import or other reports software. here's array array ( [site1] => array ( [source1] => array ( [campaign1] => array ( [ad1] => array ( [impressions] => 1141379 [clicks] => 168 [spent] => 113.0382 ) ) [campaign2] => array ( [ad2] => array ( [impressions] => 612691

treeview - Custom popup in JavaFX -

is there way create custom popup in javafx? can't use tooltip, since appear on double click, different style standard tooltip. my demands popup are: 1. if user double click, show popup 2. if user clicks outside popup, hide it see this guide on different types of popups.

php - MySqli Real Escape Not Working -

i've been using script upload articles website , done bit of maintainance , when add article on server it's adding slashes text. here code i'm using: $con = mysqli_connect("localhost","db_username","db_password","db_database"); $title = ucwords($_post['title']); $category = $_post['category']; $article = $_post['article']; $alt = $_post['alt']; $title = mysqli_real_escape_string($con, $title); $article = mysqli_real_escape_string($con, $article); $alt = mysqli_real_escape_string($con, $alt); $insert_post_sql = "insert ".$site_id."_articles (id, category, photo, alt, title, article, added, views) values('$id', '$category', '.$extension', '$alt', '$title', '$article', '$added', '$views')"; $insert_post_res = mysqli_query($con, $insert_post_sql); if(mysqli_affected_rows($con)>0){ move_uploaded_file($_files[&quo

c# - GetShortPathNameW cannot find file specified -

i'm trying short path name of path contains wide characters, here code using, throwing exception file not found. file exists, doing wrong? using system; using system.collections.generic; using system.text; using system.runtime.interopservices; using system.componentmodel; namespace getshortpathnamew_test { class program { [dllimport("kernel32.dll", setlasterror = true)] private static extern int getshortpathnamew(string pathname, system.text.stringbuilder shortname, int cbshortname); static void main(string[] args) { system.text.stringbuilder new_path = new system.text.stringbuilder(1500); int n = getshortpathnamew("\\\\?\\c:\\\\temp\\test1.txt", new_path, 1024); if (n == 0) { throw new win32exception(marshal.getlastwin32error()); } } } } you explicitly call unicode version getshortpathnamew , not specify correct para

emulation - How to connect android using novnc? -

first have installed novnc , sdk in linux, each of them runs correctly, however, don't know how connect emulator novnc. following commands used in experience. android list targets android create avd -n myavd -t 1 emulator -avd myavd -qemu -vnc 2 vncserver vncserver -geometry 1024x768 :1 ./utils/launch.sh --vnc 127.0.0.1:5901

angularjs - Angular JS Unit Testing $httpBackend spec has no expectations -

i have unit test in expectation http call made. use $httpbackend.expect() this. works fine, , unit test fails if http request not made (which good), , passes if http request made. the problem thought passes, jasmine spec runner shows "spec has no expectations" unit test, makes me think not using recommended way test http call made. how avoid seeing message? example test: it('should call sessioncheck api', function () { inject(function ($injector, sessiontrackerservice) { $httpbackend = $injector.get('$httpbackend'); var mockresponse = { isauthenticated: true, secondsremaining: 100 }; $httpbackend.expect('get', 'api/authentication/sessioncheck') .respond(200, mockresponse); sessiontrackerservice.start(); jasmine.clock().tick(30001); $httpbackend.flush(); }); }); i wrap call flush follows: expect($httpbackend.flush).not.tothrow(); i prefer approach be

c# - How to clear everything in winforms Panel? -

i add treeview panel if click button, appends treeview . how can clear in panel? tried panel1.controls.clear() , panel1.controls.remove(treeview1) . nothing happened. try mytreeviewbase.nodes.clear(); this method removes tree nodes collection. treenodecollection.clear method

tsql - Limiting the number of updated/deleted rows in SQL Server Management Studio -

it easy make mistakes when comes update , delete statements in sql server management studio. can delete way more want if had mistake in where condition or, worse, delete whole table if mistakenly write expression evaluates true time. is there anyway disallow queries affects large number of rows within sql server management studio? know there feature in mysql workbench, couldn't find in sql server management studio. no. it responsibility ensure that: your data backed up, can restore data after making inadverdent changes. you not writing new query scratch , executing directly on production database without testing first. you execute query in transaction, , review changes before committing transaction. you know how filter query avoid issuing delete / update statement on entire table. if in doubt, issue select * or select count(*) -statement first, see records affected. you don't rely on silly feature in front-end might save @ times, screw on @ other ti

delphi - Why won't my control accept keyboard input? -

i've built custom control i'm trying send input to. accept mouse input , report mousedown, mousemove , mouseup correctly, whatever reason, won't accept keyboard input. when click on it, doesn't receive focus, , keys press interpreted whatever control had focus already. this simple. first place thought in controlstyle property, thing can see in helpfile keyboard input csnostdevents , disables it, , control doesn't have that. need make control can receive input focus? a few things try: on mousedown , call windows.setfocus(handle) . in experience, winapi function setfocus works better vcl's setfocus method. in response wm_getdlgcode message, reply message.result := message.result or dlgc_wantchars or dlgc_wantarrows or dlgc_wanttab or dlgc_wantallkeys ;

Find sets of disjoint sets from a list of tuples or sets in python -

here problem: have list of tuples (could sets if needed). instance: a = [(1, 5), (4, 2), (4, 3), (5, 4), (6, 3), (7, 6)] what want find list r = [(1, 5, 4, 2, 3, 6, 7)] because intersection not empty once sets put together. for example a = [(1, 5), (4, 2), (4, 3), (5, 4), (6, 3), (7, 6), (8, 9)] the result should be r = [(1, 5, 4, 2, 3, 6, 7), (8, 9)] hope problem clear. elegant way in python, if any? cheers an interesting problem! here's attempt, i'm sure it's not efficient way a = [(1, 5), (4, 2), (4, 3), (5, 4), (6, 3), (7, 6), (8, 9)] # = [(1, 5), (4, 2), (4, 3), (5, 4), (6, 3), (7, 6)] d = {tuple(t): set(t) t in a} # forces keys unique while true: tuple_, set1 in d.items(): try: match = next(k k, set2 in d.iteritems() if k != tuple_ , set1 & set2) except stopiteration: # no match key - keep looking continue else: print 'merging', tuple(set1),

Find an specific element in a MongoDB document from C# -

i trying access mongodb c# asp.net application. let's assume, i've document below- { "_id" : objectid("546c776b3e23f5f2ebdd3b03"), "name" : "test", "values" : [ { "name" : "one", "value" : 1 }, { "name" : "two", "value" : 2, "parameters": [{"type": "type a"}, {"type": "type b"}] } ] } please note that, _id , name elements fixed; other elements dynamically created user both key , value defined user. now, search element type value type a . how can mongodb c# driver? you can use code: var query = query.eq("values.parameters.type", "type a"); var items = collection.find(query).tolist(); if data has structure use this: var items = collection.findas<item>(query).

ruby on rails - Customizing devise controller -

i trying change behaviour of 1 devise controller method. here says can running rails generate devise:controller users. however doing generated commented code bunch of super calls. if don't know super methods do, how supposed edit lines of code want change? the modification want simple: if there no admin user yet (none role=admin found), user's role set admin, else, normal user. thought in case after_filter solution, did this: class usercontroller < devise::registrationscontroller after_filter :set_role, only: [:create] protected def set_role admin_user = user.find_by_role(user::admin_role) if admin_user.nil? @user.role = user::admin_role else @user.role = user::default_role end @user.save end end my routes: devise_for :users, controllers: { users: "users" } however, method not being executed. why? can do? i think need overriding registrations controller: devi

android - getting checkboxId for dynamically created checkbox? -

i have dynamically created checkbox.i want id of selected checkbox.but getting id of last checkbox. eg. if 5 checkboxes created showing id of 5th checkbox when clicked.i want id of 5 checkbox. here dynamic created checkbox class. private void getcheckbox() { int cnter; linearmain = (linearlayout) findviewbyid(r.id.linearlayout2); alphabet = new linkedhashmap<string, string>(); (cnter = 0; cnter < str_arr;) if (!optionsarray.get(cnter).isempty()) { cnter++; } else break; alphabet.put("1", option_a_new); alphabet.put("2", option_b_new); alphabet.put("3", option_c_new); alphabet.put("4", option_d_new); alphabet.put("5", option_e_new); alphabet.put("6", option_f_new); alphabet.put("7", option_g_new); alphabet.put("8", option_h_new); alphabet.put("9", option_i_new); alp

java - Data transmission during ipojo reconfiguration -

i have problem relating data transmission between ipojo components during reconfiguration. here's example: a component calcul_1 provides calculation service return value (a+b) (ex: f(a,b)=> (a+b) ) a component calcul_2 provides calculation service return value (a*b) (ex: f(a,b)=> (a*b) ) these 2 components implement same calculation service (ex: f ). now, have component callcalcul uses calculation service of calcul_1 . component callcalcul calls f(5,6) in component calcul_1 . then, callcalcul component receives value of 11. problem: when calcul_1 receives value (5,6) (not yet calculate) callcalcul , callcalcul reconfigure changing connector calcul_2 , i.e., binds calcul_2 . in case, how can transmit (5,6) calcul_1 calcul_2 , return (5*6=30) callcalcul ? when calcul_1 receives value (5,6) (and calculate their, i.e. 5+6=11) callcalcul , callcalcul reconfigure. in case, how can transmit 11 calcul_2 , return value callcalcul ?

want to write background location tracking application android -

hi want create location tracking application in android runs in background after user terminates application left swipe recent application. till have used intent service started main activity gets killed when terminate application. other idea implement this? have tried registering location updates , doing work of service in onlocation changed event. listener gets unregister after application exists. don't need full code need approach this. have tried track in service ? without reference activity. have start service activity first time. note: service isn't killed swiping recent apps, rather killed os when more ram required. restart after killed have return start_sticky onstartcommand i.e: @override public int onstartcommand(intent intent, int flags, int startid) { return start_sticky; } also, here should register locationlistener , perform whatever action need. , always, remember add permissions.

Clear cookies with javascript -

i ask here. have update form , when submit need send 2 values main page. (they contains combobox index , table rowindex trigger them , show me selected item have choose before submit. otherwise selects first items) im using cookies , works well. problem cant clear cookies. after update loads previous values when document load. i have following: document.cookie="data1="+variable1+"; path=/"; document.cookie="data2="+variable2+"; path=/"; //they holds variables// and when page loads data back: $(document).ready(function() { var x = document.cookie.split(';'); if ( x !== null) { var x1 = x[0].split('=')[1]; var x2 = x[1].split('=')[1]; }; //i need cookie clear function here next time page loads select first items again// i tried none of them works: 1st: function clearlistcookies(){ var cookies = document.cookie.split(";"); (var = 0; < cookies.length; i++){

proper use of 'this' in Java -

i'm beginner java programmer , wanted on code i'm writing please can confirm if right use of this keyword public class readfile { private string path; // string store filename , path. public readfile(string path){ this.path; } } within instance method or constructor, this reference current object — object method or constructor being called. can refer member of current object within instance method or constructor using this as answers above suggest, can this pointing member variable , use invoke constructor within constructor. see below example public class rectangle { private int x, y; private int width, height; public rectangle() { this(0, 0, 1, 1); } public rectangle(int width, int height) { this(0, 0, width, height); } public rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ... } refer here more information. hope helps

android - Check if NFC tag is near -

is possible force android check if nfc tag near? i'm able read tag when android detects it, force check if tag near @ specific moment what want in general not possible. if can live dirty hack following work (thanks unspecified behaviour): first disable reader-mode of supported tag types. brings nfc subsystem clean state, e.g. makes sure nfc controller have no connection tag. once done restore reader-mode again. if tag present @ moment usual discovery action intent. may take second or 2 though. control of reader-mode possible using nfcadapter.enablereadermode , nfcadapter.disablereadermode

json - need to json_encode a PHP array in a particular way -

ok, have php array looks this: array ( [0] => array ( [label] => 1 [value] => value example ) [1] => array ( [label] => 10 [value] => value example 2 ) [...] ) now, if json_encode() array, is: [ object { label="1", value="value example" }, object { label="10", value="value example 2" }, ... ] but use in jquery autocomplete need array this: [ { label="1", value="value example" }, { label="10", value="value example 2" }, ... ] i've read tons of pages without finding solution...can help? update peter: here's code: $results = array(); foreach ($temp $tmp) { $results[] = array( 'label' => $tmp['id'], 'value' => $tmp['it'] ); }; echo json_encode($results); if may useful, $temp array gen

Consume and output SOAP web service using Drupal 7 Web service client and Rules -

i need data wsdl service , output existing drupal 7 cck fields. how can output information wsdl existing cck fields or php in templates without or within rules module? i attentively learned , repeat example described in consume soap web service using web service client , rules also learn question in wsdl, xml, soap, php, , drupal.... oh my! never have worked before soap , wsdl , have idea how can fulfil process of working drupal 7 , cck fields.

jquery ui - Bootstrap validation is not working? -

i have form open in new mode , in edit mode in jquery ui popup validation works me when form open in new mode when same form open in edit mode validation not works stuck here , can't figure out way out. help?? frmspecialtydetail form: <div id="specialtydetail"> <div class="fadeoutpatch0"></div> <div class="fadeoutbackground" id="fbspecialtydetail"></div> <div id="tblspecialtydetail" class="col-md-12"> <form method="post" id="frmspecialtydetail" onsubmit="return false"> <!--start - contents--> <div class="form-group"> <div class="col-md-6"> <label class="control-label">short name <span class="required">*</span></label> <input class="form-control size100" name="shortname" id=&q

xslt - Apply transforms to XML attribute containing escaped HTML -

i have xml looks this: <?xml version="1.0" encoding="utf-8"?> <root> <issue xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <comment text="&lt;div class=&quot;wiki text&quot;&gt;&lt;h4&gt;tom fenech&lt;/h4&gt;here comment&lt;/div&gt;&#10;"/> </issue> </root> as can see, text attribute in comment node contains escaped html. contents of attribute xhtml, inside template using: <xsl:value-of select="@text" disable-output-escaping="yes" /> that gets me html in final output: <div class="wiki text"><h4>tom fenech</h4>here comment</div> but want able extract contents of <h4> tag use elsewhere. in general, nice able manipulate contents of once has been escaped. how apply further templates output of <xsl:value-of /> ? i using php built-in xslt processor , suppor

ruby on rails - NoMethodError (undefined method `authenticate_admin_user!' for #<Admin::DashboardController -

we using ruby 2.1 rails 3.2 , active admin 0.6.3. our site , running on front end when trying access admin panel, says: "nomethoderror (undefined method `authenticate_admin_user!' admin::dashboardcontroller" i've tried searching on net solutions none of them worked out.! any suggestions? edit : admin user model activeadmin.register adminuser #menu :priority => 2 menu false index :title => 'admin users'+sitesetting.site_title column :email column :role |show| if show.role=="superadmin" status_tag('super admin', :ok) elsif show.role=="subadmin" status_tag('sub admin', :ok) elsif show.role=="customeadmin" status_tag('custom admin', :ok) else status_tag('normal admin', :ok) end end column 'current login', :current_sign_in_at

json - how to convert JString to Int with json4s -

we switched jerkson json4s, discovered default de-serialization behavior of these 2 libraries far same. one of issues we're having receive json input number field represented string instead of number //example json object string representation of "id" { "id" : "12545" } //example json object number representation of "id" { "id" : 12345 } these needs deserialized following class case class example(id:int) this our general setup deserializing json arbitrary classes import org.json4s.native.serialization._ import org.json4s._ import org.json4s.native.jsonmethods._ object json { implicit val formats = defaultformats def parse[t](json:string)(implicit mf: manifest[t]):t = { org.json4s.native.jsonmethods.parse(input).extract[t] } } but whenever attempt parse json object string representation of id throws , exception message: no usable value offers no usable value id not know how con

File renamed when git rm and git add done on different files -

i did git rm file1.c after git status shows on branch master branch ahead of 'origin/master' 2 commits. (use "git push" publish local commits) changes committed: (use "git reset head <file>..." unstage) deleted: file1.c untracked files: (use "git add <file>..." include in committed) dir/file2.c dir/file3.c all , far. if git add dir/file2.c get on branch master branch ahead of 'origin/master' 2 commits. (use "git push" publish local commits) changes committed: (use "git reset head <file>..." unstage) renamed: file1.c -> dir/file2.c untracked files: (use "git add <file>..." include in committed) dir/file3.c is bug or doing wrong? expect new file listed new file. file1.c , file2.c in no way have similar content [edit] besides short copyright notice [\edit]. this not bug, feature. when remove file, , add file of code sa

c# - The name "xx" does not exist in the current context -

my program keeps getting error "the name "ok" not exist in current context." doing wrong? namespace game { class program { static bool selftest() { bool ok = gamemodel.selftest(); if (ok) system.diagnostics.debug.writeline("succeded"); else system.diagnostics.debug.writeline("failed"); return ok; } static void main(string[] args) { bool ok = selftest(); } } } namespace game { class gamemodel { public static bool selftest() { ok = true; return ok; } } } change public static bool selftest() { ok = true; return ok; } to public static bool selftest() { bool ok = true; return ok; } or perhaps just public static bool selftest() { return true; }

AngularJS loading message/please wait -

Image
how can achieve following in angularjs: if have page show widgets , each widget has button called refresh. when button clicked content of widget reloaded server. while content reloaded want show user message within widget, please wait ... possible fading effect. how can achieve in angularjs? i kind of taught having common service purpose , somehow each widget controller use service or that, maybe directive show actual loading/please wait message? what advise? p.s. there should loading/please wait message fading whole page, when route changing ... switching between pages. in recent project i'm using https://github.com/cgross/angular-busy very nice thing, have put promise $scope, , add cg-busy attr element should have spinner (beside registering module obviously): controller: $scope.mypromise = restangular.get('something',12).then(function(response) { ... }) html: <div cg-busy="mypromise"></div> you can customize temp

How compare SQL Server Datetime from C# -

i've got make query c# , compare datetime . datetime stored in database this: 2014-11-09 00:00:01 and i'm using query: select * table datetimevar = '19/11/2014 0:00:01' , othervar = 1 but it's not in same format. there way convert system.datetime in c# dates in sql server, or way cast sql server datetime in format?? should check like instead of = in where clause. thanks. if generating query datetime object, date.tostring("yyyy-mm-dd hh:mm:ss") convert format in query.

c# - How can I test/debug the update process of my app from WP8 to WP8.1? -

i release big update app, wp8 , don't want users lose local app data. 1) right local data of wp8 app still available in local folder afterwards? 2) can use update background task prepare upgrade? or apply wp8.1 → wp8.1 upgrades? 3) there way besides providing wp8 app beta app , updating wp8.1 version there? can test locally on device/in emulator? know there's /update flag application deployment tool how work wp8 → wp8.1? i'd appreciate help, maybe of have done this. in advance! 1) correct. user data persists through update. user data removed when app uninstalled. 2) wp8.1 feature. need have background task registered before upgrade. isn't useful initial install. 3) try test app, expect work fine wp8 wp8.1

ios - Xcode6 - Swift: How to detect which object is touched and move/drag/drop? -

i'm trying have more 1 off these types: @iboutlet weak var objecttomove1: uiimageview and want able detect when 1 of them touched... if held down on object , moving finger, want object follow.. when dropped, want see if interfere object of same type... i found example: override func touchesmoved(touches: nsset, withevent event: uievent) { var touch : uitouch! = touches.anyobject() uitouch location = touch.locationinview(self.view) objecttomove1.center = location } this works, specific object (here: "objecttomove1")... , moves position first put finger (don't matter put finger)... so, how can tweek able detect if i'm touching object , follow finger + detect if interfere (collide) object when lifting finger? thanx! kjetil use uitouchgesturerecognizer. can create general 1 uses delegate call handle touch. can add views create programatically or in viewdidload type methop can attach there.

html - Color overlay on shape -

i've got small problem. i want create overlay effect on picture in following jsfiddle. http://jsfiddle.net/39gud4bh/1/ <div> <img id="bubble" src="http://png-1.findicons.com/files/icons/2711/free_icons_for_windows8_metro/128/speech_bubble.png"> <img src="http://s30.postimg.org/lptvfyod9/speech_bubbleorange.png"> </img> </div> #bubble { } i want overlay have color #ff9f2d how possible? been trying litterally find. problem image (might not in jsfiddle) shape transparent background. causes attempts background/foreground filter color recolor whole square instead of shape. really need help. in advance - thank you! edit - fiddle has been updated entail desired outcome of css on grey bubble. this may not exact answer you're looking for, maybe can consider using font awesome. it'll clean, sharp bubble , can resize , color anyway want css. route use svg . http://jsfiddle.net/wilchow/39gud4bh/5/

java - Removing dynamically Objects from JPanel -

via jspinner want add , remove object "porta" a jpanel , works fine adding , when remove 1 object if try remove 2 or more objects doesn't work properly. code think issue related last element of vector on add object "porta": import javax.swing.jframe; public class preparagara extends jframe { public jspinner spinner; private jpanel panel_1,panel_2; private int spin; private int nporta = 1; private portap scorriporta,porta; final vector<portap> vp = new vector<portap>(); /** * launch application. */ /** * create application. */ public preparagara() { initialize(); } /** * initialize contents of frame. */ private void initialize() { final jframe frame = new jframe(); frame.setvisible(true); frame.setbounds(100, 100, 1000, 400); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.getcontentpane().setlayout(new gridlayout(4, 1, 3, 3)); jmenubar menubar = new jmenubar(); frame.getcontentpane()

how to split xml using xpath in perl? -

i have input xml have split based on doc , delt wise , save in format delt_0001.xml this code #!/usr/bin/perl use xml::xpath; $file = 'file.xml'; $xp = xml::xpath->new(filename=>$file); foreach $entry ( $xp->findnodes('/xml/service/main/doc') ) { $filename = $entry->findvalue('./delt/@id'); foreach $entry1( $entry->findnodes('//delt')){ $filename = $entry1->findvalue('/delt/@id'); $content = $entry1->tostring; open(wr,">delt_$filename.xml"); print wr "$content\n"; close wr; } when run program delt portion prints in 1 xml. input xml delt.xml <xml> <service> <title>split xml</title> <main> <doc id="001"> <title>doc1</title> <delt id="0001"> <title>delt1</title> <text>num1</text>`` <text>num1</text> </delt>

javascript - Select latest selected value of a dropdown -

is there way select latest user's selected value of dropdown? eg: <select id="data" name="data" class="data" multiple="multiple"> <option value="100">foo</option> <option value="101">bar</option> <option value="102">bat</option> <option value="103">baz</option> </select> if use bellow example, last index, it's not want. var latest_value = $("option:selected:last",this).val(); what want like: if select "bar", 101, if select "foo" 101 instead of 100. obs: examples considering user selecting multiple values, not one. use simple js code: var is_now_selected = document.getelementbyid('data').value; // or jquery var is_now_selected = $('#data').val() maybe don't know option -value accually value of select . if click <option value="something&qu

TSQL Cannot create index on view - the view uses an implicit conversion from string to datetime -

sql server 2008 r2 i'm trying create indexed view i'm getting following error cannot create index on view '' because view uses implicit conversion string datetime or smalldatetime. use explicit convert deterministic style value. the issue int column [gpstime] records number of seconds '1970-01-01 00:00:00' , i'm trying convert/cast datetime, eg cast(dateadd(ss,[gpstime],'1970-01-01' ) datetime) or convert(varchar,dateadd(ss,[gpstime],'1970-01-01' ),113) or convert(datetime,dateadd(ss,[gpstime],'1970-01-01' ),113) each of 3 options above gives me error mentioned earlier. is way around this? going make guess issue on '1970-01-01' , try this: dateadd(ss, gpstime, convert(datetime, '1970-01-01', 101)) or keep datetime value in table (as datetime avoid convert) or write deterministic function return datetime such: create function [dbo].[unixepoch] () returns datetime schemabinding

r - Ignoring NAs in a dataframe when finding unique rows -

i have dataframe 20 columns , 200 rows, , find unique rows. problem every row has few nas mixed in: missing data , nas treated "wildcard", not used match other nas. the following 2 rows should recognized match (ie non-unique) t, s, na, z na, s, g, z i've tried incomparables argument unique function, doesn't seem implemented. lot. put in double loop: all(na.omit(x[1,] == x[2,])) replacing 1 , 2 , j cycle through comparisons need check.

java - Using HTTPClient to connect to site on same server - getting Connection refused -

i have tomcat 5.0 server running various applications on unix server. on same server, have shell script uses org.apache.commons.httpclient , connect url on 1 of applications. has worked years. i have moved applications virtual linux server , tomcat 6.0. when run shell script, get: java.net.connectexception: connection refused when update url application on different server, shell scrip completes successfully. why can’t run shell script , access website running on same server? , can make work?

amazon dynamodb - Running AWS commands from commandline on a ShellCommandActivity -

my original problem want increase dynamodb write throughput before run pipeline, , decrease when i'm done uploading (doing max once day, i'm fine decreasing limitations). they way found through shell script issue api commands alter throughput. how work ami access_key , secret_key when it's resource pipeline creates me? (i can't log in set ~/.aws/config file , don't want create ami this). should write script in bash? can use ruby/python aws sdk packages example? (i prefer latter..) how pass credentials script? have runtime variables (like @starteddate ) can pass arguments activity key , secret? have other way authenticate either commandline tools or sdk package? if there way solve original problem - please let me know. i've got shellactivity solution because couldn't find else in documentations/forums. thanks! ok. found - http://docs.aws.amazon.com/datapipeline/latest/developerguide/dp-concepts-roles.html resourcerole in default obje

c++ - How to call a function when a work item is finished in Boost.Asio? -

i implement command queue handles incoming commands concurrently thread pool (so queue grows temporarily when threads working). post callback callers when command worker started , finished. implementation based on this example asio website. is there way hook these events , signal somehow? avoid command functors knowing callbacks (since call callbacks inside command functors). pseudocode illustrate (initialization , error handling omitted brevity): class commandqueue { public: void handle_command(cmdid id, int param) { io_service.post(boost::bind(&(dispatch_map[id]), param)); // pseudocode: // when 1 of worker threads start item, want call callback_site.cmd_started(id, param); // when command functor returns , thread finished callback_site.cmd_finished(id, param); } private: boost::asio::io_service io_service; asio::io_service::work work; std::map<cmdid, commandhandler> dispatch_map; // comm

windows - Access Azure Storage from VS server explorer -

i'm trying view blob data vs2013 every time i'm trying expand arrow of blobs, got:"the current storage account key invalid. please provide new storage account key." doesn't matter try again , again recreate/regenerate key , insert "account key" text box nothing help https://drive.google.com/file/d/0b3hwovf_jqt0yxlcv0zydxpznwm/view?usp=sharing the solution problem posted on over thread: vs2012 server explorer - cannot access windows azure storage tl;dr make sure local pc's date , time set correctly.

dynamics crm - how can i send email to team members after assigning record in crm 2011? -

i need send email team members.the mail record assigned you.using either workflow or plugin.which means if assigned record particular team need  send mail notification  particular team members ...how ??? what type of object talking about? for that's owned user, can create workflow triggered whenever object changes owners, send e-mail new owner. not tricky. sending e-mail entire team tricker. there couple different ways accomplish this. distribution list. edit team entity contains team e-mail. create distribution list has members of team on it. create workflow user, , send e-mail distributon list address if there change in ownership the disadvantage of have manage dl list , teams in crm separately. it's quick. plug in. create plug in fire when ownership of object changes. make linq query grab e-mail addresses of users in team. create foreach loop send out e-mail users. this more difficult , time consuming of options, it's right way it.

php - Process stats from big table -

i have advertising site , i'm struggling find efficient way process statistics. goal show unique visitors , clicks per day. this how works: publishers can add website , add unlimited adspaces it, can have multiple banners running on same page or different pages. websites id | url adspaces id | website_id | info views id | adspace_id | ip | date (yyyy-mm-dd) adspaces_stats id | adspace_id | views | date (yyyy-mm-dd) websites_stats id | website_id | views | date (yyyy-mm-dd) the script update views , clicks adspaces done: $getviewsbyadspace = $db->query('select count(*) views, adspace views date="'.date('y-m-d').'" group adspace order id asc'); while($getviewsforadspace = $getviewsbyadspace->fetch(pdo::fetch_assoc)) { $adspaceid = $getviewsforadspace['adspace']; $adspaceviews = $getviewsforadspace['views']; if( $db->query('update adspace_stats set views='.$adspaceviews.' adspace='.

ontouchlistener - Slide Up an image using EventMotion in Android -

i trying slide layout in android using touch listener. expecting motion_up should intercepted when user touches screen , drags finger screen. , motion_down other way. when debug, both , down called. i trying slide layout when drag using animation. don't understand doing wrong. did had situation before? hints helpful, thank you. this code: @targetapi(build.version_codes.honeycomb) public class mainactivity extends activity implements animationlistener, ondraglistener { // animation private animation animslideup; private imageview img; private rect rect; @targetapi(build.version_codes.honeycomb) @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); img = (imageview) findviewbyid(r.id.interstitialimg); img.setondraglistener(this); img.setontouchlistener(new view.ontouchlistener() { @override

qt - How to be notified when the user clicks in the tableview below the last row? -

when user clicks in tableview on row, events (clicked, activated, pressed, etc) fired. far good. when user clicks below last row (when tableview bigger required display rows) don't know how notified: selectionmodel()->currentchanged() not fired. visually, currentrow seems lose focus, @ time tableview->currentindex() indicates last clicked row.

c# - How to apply an NUnit Attribute to An Assembly -

according documentation can apply nunit timeout attribute assembly: the attribute may specified on fixture or assembly, in case indicates default timeout subordinate test cases. the challenge running give no indication of how apply attribute assembly on page or anywhere else can find in documentations. i tried using [setupfixture] , decorating attribute did not seem take. has had success in making work? to apply timeout attribute assembly, first add directive using nunit.framework; assembly's assemblyinfo.cs . add line specifying timeout: [assembly: timeout(1000)]

ngroute - What's the most concise way to read query parameters in AngularJS? -

i'd read values of url query parameters using angularjs. i'm accessing html following url: http://127.0.0.1:8080/test.html?target=bob as expected, location.search "?target=bob" . accessing value of target , i've found various examples listed on web, none of them work in angularjs 1.0.0rc10. in particular, following undefined : $location.search.target $location.search['target'] $location.search()['target'] anyone know work? (i'm using $location parameter controller) update: i've posted solution below, i'm not entirely satisfied it. documentation @ developer guide: angular services: using $location states following $location : when should use $location? any time application needs react change in current url or if want change current url in browser. for scenario, page opened external webpage query parameter, i'm not "reacting change in current url" per se. maybe $location isn't

arrays - Using php, how to get return object data into variable? -

i have read number of answers on not getting something. have object retrieves data file , puts array format , trying data variable in calling file can work data. calling.php $x = new obj(); $x -> method_y(); objectfile.php public function method_y(){ ..... code stuff ..... print_r($array); } array( [0] => array ( [key1] => value1 [key2] => value2 [key3] => value3 ) [1] => array ( [key1] => value1 [key2] => value2 [key3] => value3 ) ) is better use echo, return, or print method , should use json_encode return it. how returned data out of object can work with. instance using json_encode in method json json_decode wants string. again have read number of answers on not getting it. thanks in advance. you can return array itself

linq - C# Filter List of Objects With a Simple List -

quite new linq here , wondering how achieve this. have following codes: var allorgs = (from org in this.context.organizations select org).tolist(); var childorgs = (from oc in this.context.organizationchild select oc).tolist(); var parentorgs = (from op in this.context.organizationparent select op).tolist(); the return values each variable follows: allorgs = [{id=1}, {id=2}, {id=3}, {id=4}]; childorgs = [{id=2}]; parentorgs = [{id=3}]; i want filter allorgs such items not in childorgs or parentorgs returned, i.e. filteredlist = [{id=1}, {id=4}]; i have following linq filter (which need with): var filteredlist = allorgs.where(a => childorgs.any(c => c.id != a.id)); filteredlist = filteredlist.where(f => parentorgs.any(p => p.id != f.id)); return filteredlist.tolist(); for reason, still end getting values... appreciate insight. thanks! just merge 2 conditions: filteredlist = allorgs.where(a => !childorgs.any(c => c.id == a.id)

javascript - AngularJS pass variable through to a template -

i want pass variable or text through template shows value inside template. i come across jsfiddle shows working uses ng-repeat . there simplere way without using ng-repeat ? <div ng-repeat="name in ['john']" ng-include="'partial.html'"></div> <div ng-repeat="name in ['jack']" ng-include="'partial.html'"></div> <script type="text/ng-template" id="partial.html"> <div>the name {{ name }}</div> </script> http://jsfiddle.net/f97keutl/ <div ng-controller="ctrl"> <div ng-include="'partial.html'"></div> </div> <script type="text/ng-template" id="partial.html"> <div>the name {{ name }}</div> </script> js: var myapp = angular.module('myapp',[]); myapp.controller('ctrl', function($scope) { $scope.name = "j