Posts

Showing posts from August, 2012

formatting - Toggle Visual Studio setting matching brackets -

how turn on vs setting shows matching brackets. looking straight line helps matching items up. if (true) { | foreach (var item in collection) | { |<--|----looking | |<----- looking | | | } }

python - Slow insert into MongoDB Replica Set, with pymongo -

i'm doing project university have perform tests check times insert , find in replica set of mongodb changing number of members (nodes). 1 member plus 1 arbiter 3 member plus arbiter. i have instantiated , configured correctly 4 instances t2.micro (with aws ec2) ubuntu server os , mongodb installed , configured on each instance. have initialized replica set 1 node. after programmed tests in python, realized insert of 1,000 items in mongodb collection took 23 s perform it, seems strange since make insert query replication set 4 nodes , arbiter. this code wrote test, , takes 23 seconds execute queries: import timeit pymongo import mongoclient time import sleep _connection = mongoclient('84.93.90.12', 27017) _dbmongodb = _connection.test start_time = timeit.default_timer() # inizio contare il tempo d'esecuzione in range(1000): _dbmongodb.test.insert({"test":1}) elapsed = timeit.default_timer() - start_time print(elapsed) is there specific driv

java - I need to make my JPanel resize dynamically as new components are being added to it -

i need let users add more text fields jframe once size of frame has exceeded original value scroll pane step in. since cannot add jscrollpane jframe in order enable scrolling decided put jpanel on jframe , pass jpanel object jscrollpane constructor. scrolling works fine until has reached borders of jpanel. thing size of jpanel stays , not stretching dynamically. happens buttons in code using space of jpanel being size of 300x300 want have jpanel stretch once these controls have used original space. please advise. import java.awt.dimension; import java.awt.flowlayout; import java.awt.gridlayout; import java.awt.rectangle; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jpanel; import javax.swing.jscrollpane; import javax.swing.jtable; import javax.swing.scrollpaneconstants; public class skrol { public static void main(string[] args) { jframe f = new jframe(); f.setlayout(new flowlayout()); f.setdefaultcloseoperation(jframe

c# 4.0 - I get an Amazon.S3.AmazonS3Exception: A provisioning code must be provided Exception When I try to create a new Bucket, AWSSDK 3.1.6 C# AmazonS3 -

i trying connect amazon s3 + cleversafe c# , using awssdk 3.1.0.0. want create new bucket. have provisioning code = "my provisioning code" , host="my host", accesskey="my access key", secretkey="my secret key" tried following code : servicepointmanager.servercertificatevalidationcallback += (sender, cert, chain, error) => { return true; }; basicawscredentials basiccredentials = new basicawscredentials("my access key", "mysecretkey"); amazons3config configurationclient = new amazons3config(); configurationclient.forcepathstyle = true; configurationclient.serviceurl = "https://###.##.###.###";// host ipadress configurationclient.usehttp = false; try { using (amazons3client clientconnection = new amazons3client(basiccredentials, configurationclient)) { putbucketrequest newbucket = new putbucketrequest(); newbucket.useclientregion = true; newbucket.bucketname = "newbucketcl

php - what is the difference in ajaxForm between success: and complete: -

this question has answer here: difference between .success() , .complete()? 3 answers i using several forms deleting files, renaming files, uploading files in filemanagement form: <form class="sfmform" action="" method="post"> ....... </form> and ajaxform: $(".sfmform").livequery(function() { $(this).ajaxform({ success: function(data) { status.html(data); $('.myfiles').load(document.url + ' .myfiles'); }, /*complete: function(data) { status.html(data); $('.myfiles').load(document.url + ' .myfiles'); },*/ }); }); it doesnt matter if use success or complete; both work perfect. wondering: 1 correct use in case? complete fire regardless of error or success success fire if receive http 200 (normal) response. so use compl

Should we do a bulk insertion operation in mongodb ?? will this block other Read / Write Operations? -

i using mongodb our application . we have high usage of mongodb usage , know seeing mongostat output insert/s query/s update/s delete/s getmore/s command/s flushes/s mapped vsize res faults/s locked % idx miss % q t|r|w conn time 0 4 1 0 0 3 1 10396 11347 591 0 0.1 0 0|0|0 70 10:57:28 0 65 31 0 0 35 0 10396 11347 591 1 3.7 0 0|0|0 70 10:57:29 0 76 37 0 0 41 0 10396 11347 591 0 3.5 0 0|0|0 70 10:57:30 0 85 42 0 0 44 0 10396 11347 591 1 4.7 0 0|0|0 70 10:57:33 0 52 25 0 0 29 0 10396 11347 591 0 2.9 0 0|0|0 70 10:57:34 0 26 11

php - Group By 2 Columns with similar info to link with a 2nd table -

i have two columns similar info: column 1 = item 1, item 3, item 5 column 3 = item 3, item 5, item 8 i want display how many of each item in total both columns. i have this: $sql = mysql_query("select firsttypeid, secondtypeid, thirdtypeid, designid, count(designid) designs approved = '1' group firsttypeid, secondtypeid, thirdtypeid"); while ($row = mysql_fetch_array($sql)) { $designid = stripslashes($row['designid']); $firsttypeid = stripslashes($row['firsttypeid']); $secondtypeid = stripslashes($row['secondtypeid']); $thirdtypeid = stripslashes($row['thirdtypeid']); $total = stripslashes($row['count(designid)']); } $result2 = mysql_query("select * types typeid = '$firsttypeid' or typeid = '$secondtypeid' or typeid = '$thirdtypeid'"); while ($row2 = mysql_fetch_array($result2)) { echo "<li><a href='index_type.php?typeid=".$row2{'

php decrypt string with MCRYPT_RIJNDAEL_256 -

<?php function encrypt ($key,$iv,$str) { $block=mcrypt_get_block_size(mcrypt_rijndael_256, mcrypt_mode_cbc); $padding=$block-(strlen($str) % $block); $str.=str_repeat(chr($padding), $padding); $encryptxt=mcrypt_encrypt(mcrypt_rijndael_256,$key,$str,mcrypt_mode_cbc,$iv); $encryptxt64=base64_encode($encryptxt); return $encryptxt64; } function decrypt ($key,$iv,$str) { $block=mcrypt_get_block_size(mcrypt_rijndael_256, mcrypt_mode_cbc); $padding=$block-(strlen($str) % $block); $str.=str_repeat(chr($padding), $padding); $decryptxt=mcrypt_decrypt(mcrypt_rijndael_256,$key,$str,mcrypt_mode_cbc,$iv); $decryptxt64=base64_decode($decryptxt); return $decryptxt64; } echo encrypt("1234567890123456","12345678901234561234567890123456","test")."\n<br/>"; echo decrypt("1234567890123456","12345678901234561234567890123456","xhqkvrq6fxehoggmrkoek04146m2l9bv1scp6c1qcyg=")."\n<

javascript - RemoveEventListener not removing event -

the code below supposed add event listener each playing card in players hand while it's turn, , remove events while it's different player's turn. it isn't working. player's cards remain clickable once event set on first turn. taketurn ( playerindex ) { console.log(this.name); let handcards = document.getelementbyid(this.name).queryselector('.handcards'); let thecards = handcards.queryselectorall('.handcards .card'); let = this; ( let h = 0; h < thecards.length; h++ ) { thecards[h].addeventlistener("click", function onplaycard (){ let thesecards = handcards.queryselectorall('.handcards .card'); let discarded = that.playcard(thecards[h], thesecards, handcards); that.gameinstance.discardpile.push(discarded); console.log(that.gameinstance.discardpile); ( let e = 0; e < thesecards.length; e++) { thesecards[e].removeevent

Netbeans Tomcat Server Issue -

i trying hook tomcat netbeans , run web project on it. have set server username , password, keep getting error message. have added server log below more details. : starting tomcat process... waiting tomcat... tomcat server started. in-place deployment @ c:\ryan drive\web development\java\netbeans\projects\webapplication5\build\web deploy?config=file%3a%2fc%3a%2fusers%2frmhaa%2fappdata%2flocal%2ftemp%2fcontext8651336917198990861.xml&path=/webapplication5 fail - failed deploy application @ context path /webapplication5 c:\ryan drive\web development\java\netbeans\projects\webapplication5\nbproject\build-impl.xml:1045: module has not been deployed. see server log details. build failed (total time: 4 seconds) here server log below. looks access denied possibly? have no idea why happening. same server log error every time run server, independent of project. 13-jun-2016 18:14:22.419 info [localhost-startstop-1] org.apache.jasper.servlet.tldscanner.scanjars @ least 1 jar sca

android - Eclipse library path error after moving project to git repository -

im trying myself github. after moved project local repository, there error occured in libraries paths, seems remembering former path in workspace? ideas? says library missing, in project's folder. appreciated. there screenshot: library error when your library project source , not jar: right click on project dir - properties choose android on left side in lower "library" section reference old library red cross remove it add library new location enjoy when your library jar : right click on project dir - properties choose java build path on left side choose libraries tab remove old libraries add new external jars location enjoy or: do steps 1-4 , then: copy jar library libs dir of android project right click on newly copied jar in libs choose build path -> add build path menu enjoy hope helps , else ;)

ruby - How to mount Rails Engines automatically/dynamically? -

when using mountable engine in rails application necessary, mount engine in parent apps config/routes.rb file this: mount myengine::engine, at: "/my_engine" but, possible somehow mount engine in parent app dynamically e.g. in initializer call during installation of engine bundle install ? that's easy. can . tested , works. hope helps. module myengine class engine < ::rails::engine isolate_namespace myengine config.my_engine = activesupport::orderedoptions.new initializer 'my_engine.configuration' |app| if app.config.my_engine[:mounted_path] app.routes.append mount myengine::engine => app.config.my_engine[:mounted_path] end end end end end and in main application in config/application.rb, can set config.my_engine.mounted_path = "/some_path_here"

jxls - JXLS2, XLSCommentBuilder and row overwrite white iterating over the passed collection -

i have rather simple xls template, , 1 of rows annotated comment on cell a10 : jx:each(items="obj.reportrows" var="reportrow" lastcell="h10") it works - takes collection , adds data it, overwrite static cell data below row a , instead of inserting generated rows. looks there's no attribute each command controls whether rows should inserted or overwritten. am missing something? try include static cells jx:area tag. in case should shifted down expected.

python - Django - No Post matches the given query -

Image
ive been building blog via tutorial in book 'django example'. im working on part blog post can shared via email, works fine when run until click 'share post' link under entry , following 404 page not found (404) request method: request url: http://127.0.0.1:8000/blog/1/share/ raised by: blog.views.post_share no post matches given query. my understanding telling me post can't found db right? have 3 test posts visible in django admin , published , when login via django shell can see 3 posts there too. ive gone on code multiple times , have code came book , cannot see amiss, here forms, views, models , urls files app of project https://github.com/davejonesbkk/mysite/blob/master/mysite/blog/forms.py https://github.com/davejonesbkk/mysite/blob/master/mysite/blog/views.py https://github.com/davejonesbkk/mysite/blob/master/mysite/blog/urls.py https://github.com/davejonesbkk/mysite/blob/master/mysite/blog/models.py ive read other threads here people had

url - Mixing Named params with standard params Phalcon -

i have url loads fonts such: /templatename/fonts/helvetica?weights=regular,bold,light in php dynamically generate css file appropriate font referencing. we moved on to phalcon , broke. i'm trying figure out how tell router use the font name named param use standard param style. question marks. this router looks right now: ... "fonts"=>[ "pattern" => "/fonts/{file:[\w\w]}", "route" => [ "controller" => "asset", "action" => "fonts" ] ] ... when use dispatcher loop, this: $params = $this->dispatcher->getparams() the array not show weights param: array ( [template] => templatename [file] => helvetica ) how can without changing url structure? array ( [template] => templatename [file] => helvetica [weights] => regular,bold,light ) if ha

java - How to send oauth details in httpclient -

i want implement single sign on in web application. i'm using http client service provider twitter . my question how set oauth details via http client. don't want twitter4j . want done via httpclient

permissions - How can I run this Powershell script as a user? -

Image
i trying run following script upon startup of machine because cannot service start on startup. can schedule run. problem facing seems user vs administrator issue. this windows 7 machine powershell 4.0. have set execution policy unrestricted. when try run script user designated have administrative privileges see following error. when right click powershell icon, run administrator command works fine. command get-service -name "*vmauthd*" |start-service is possible run user account? solution able script run on startup desired. turned off uac , set execution policy unrestricted. not sure if uac issue before script runs now. created cmd file in code. set cmd file run @ startup using windows task scheduler , set task run whether logged in or not. powershell -command "set-executionpolicy unrestricted" powershell -command "get-service -name " vmauthd " | start-service" pause here image of cmd file

c# - How to assign a negative exponent value to double variable? -

d double; f float; d = 4.4e38;//±3.4e38 maximum value of float f = (float)d; console.writeline("f = (float)d " + f);//op infinity d = -2.5e−45; f = (float)d; console.writeline("f = (float)d " + f);//expected op 0 my query: d = -2.5e−45;this loc giving compile error, please tell me right way assign value in double variable edit: yes, right, once corrected minus sign code starts running.;±1.5e−45 minimum value of float. when i'm assigning value -2.5e-45 d, outside lower range, casting double float should have given me result zero, result -2.802597e-45, why? msdn.microsoft.com/en-us/library/yht2cx7b.aspx in page remarks number 4 states if double big fit float, casting results infinity, , if small results zero. here in code sample i'm trying checking these 2 conditions, taking such values creates case of infinity , 0 after casting. please correct me if have not taken appropriate value of variable d create case zero, outcome.

How to solve Ax=b with matlab where A is a large unsymmetric sparse matrix? -

i'm doing ax = b large (over 1m*1m size), non-symmetrical sparse matrix in matlab . build a in sparse way. however, using a\b directly slow. tried gmres . however, without pre-conditioner cannot right answer , pre-conditioner ( ilu instance) it's slow. how can solve problem efficiently? thx. it's difficult give definitive answer, since depends on particulars of system solving. unfortunately involves lot of trial , error on side , there no guaranteed method work system. here few things consider: how sparse system , how slow too slow ? 1m x 1m large system, work depends on number of non-zeros; if system has many nonzeros, yes, take while run; aspect lead long running time poor numerical conditioning of system (see 1 , 2 ); preconditioning should this, long use effective preconditioner try different iterative method: example bicg method or bicgstab , should work unsymmetric systems try tweak ilu pre-conditioner or use different preconditioner: incre

r - dplyr arrange() function sort by missing values -

i attempting work through hadley wickham's r data science , have gotten tripped on following question: "how use arrange() sort missing values start? (hint: use is.na())" using flights dataset included in nycflights13 package. given arrange() sorts unknown values bottom of dataframe, not sure how 1 opposite across missing values of variables. realize question can answered base r code, interested in how done using dplyr , call arrange() , is.na() functions. thanks. we can wrap desc missing values @ start flights %>% arrange(desc(is.na(dep_time)), desc(is.na(dep_delay)), desc(is.na(arr_time)), desc(is.na(arr_delay)), desc(is.na(tailnum)), desc(is.na(air_time))) the na values found in variables based on names(flights)[colsums(is.na(flights)) >0] #[1] "dep_time" "dep_delay" "arr_time" "arr_delay" "tailnum" "air_time" ins

javascript - Can't keep elements from overlapping when using GSAPs stagger method -

so trying stagger letters using tweenmax.staggerto. here js: tweenmax.staggerto(letter, 2, {bottom:0, opacity: 1, delay: 2}, 1); the html: <div class="middle"> <p class="letter">p</p> <p class="letter">p</p> <p class="letter">p</p> <p class="letter">p</p> </div> and css: .letter { display: inline; margin-right: 100px; opacity: 0; position: absolute; } .middle { text-align: center; padding-top: 100px; height: 100vh; margin: auto; } one of official tutorials watched explains position on element being animated needs have position property of either absolute or fixed. i confused though, how can animate these objects without have them overlapping each other. example of going for: gsap staggered animated elements thanks! i got same problem and, please consider i'm beginner too, staggerto method not appropriate example. l

ruby on rails - How do I model Child belongs to class -

create_table "children", force: :cascade |t| t.string "name" t.date "dob" t.string "child_class" t.string "section" t.integer "parent_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end this schema have child model . child_class values getting stored "1", "2" .. "12". should need create 12 different models, class1 class12 , have belongs_to child class? there efficient way to this?

Android code for using google custom search API -

can please share java codes getting response google search. stuck on "result=403" , "connect failed:network unreachable".please check coding below. i'll thankful if can me.(i have obtained api key , custom search engine id). thanks. public class mainactivity extends appcompatactivity { private string searchurl = "https://www.googleapis.com/customsearch/v1?key=aizasybypqz3jzg5kosg7emxsgthhp3sil7dyik&cx=012845902157700116531:oqktayhycq4&q="; private string searchitem = "android"; private string searchquery = searchurl + searchitem + "&alt=json"; textview searchresult; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); searchresult = (textview) findviewbyid(r.id.result); new jsonsearchtask().execute(); } private class jsonsearchtask extends asynctask<void, void

C program to convert input string of space separated ints into an int array -

question: i want make c program takes string of space separated ints input (positive , negative, variable number of digits) , converts string int array. there question on reading ints string input array on stack overflow doesn't work numbers of digit length more 1 or negative numbers. attempt: #include <stdio.h> int main () { int arr[1000], length = 0, c; while ((c = getchar()) != '\n') { if (c != ' ') { arr[length++] = c - '0'; } } printf("["); ( int = 0; < length-1; i++ ) { printf("%d,", arr[i]); } printf("%d]\n", arr[length-1]); } if enter following terminal: $ echo "21 7" | ./run $ [2,1,7] this array get: [2,1,7] instead of [21,7] if enter following: $ echo "-21 7" | ./run $ [-3,2,1,7] i get: [-3,2,1,7] instead of [-21,7] makes no sense. however, if enter: $ echo "1 2 3 4 5 6 7" | ./run $ [1,2,3,4,5,6,7] note: assuming input

javascript - New to AngularJS: Trying to make a directive and using it via a comment in the HTML -

Image
when write following code <div ng-app="myapp"> <input type="text" ng-model="$scope.firstname""> <input type="text" ng-model="$scope.lastname"> <p>{{ $scope.firstname + ' ' + $scope.lastname }}</p> <!-- directive: test-directive --> </div> <script> var app = angular.module("myapp",[]); app.controller("myctrl", function($scope) { $scope.firstname = "shadab"; $scope.lastname = "khan"; }); app.directive("testdirective", function() { return { restrict : "m", replace : true, template : "made in directive" }; }); </script> the directive doesn't seem work: when make following change template property, directive sta

node.js - node mysql insert and select count not working -

i'm using 2 function function1 , function2 consequetivly in node.js . function1 using insert data table. for(var j=0; j < length; j++){ connection.query('insert testtable set ?', { row_name : name }, function(err, res){ if(err) throw err; }); } function2 using select count of inserted name, count. connection.query('select row_name, count(*) count testtable row_name = ?', name , function (err, rows){ console.log(rows); }); where log gives me name : null, count : 0 what i'm doing wrong? first of all, running mysql queries in loop bad practice. second, miss basics of asynchronous flow in javascript. here article the basic concepts of asynchronous programming in javascript explained. connection.query asynchronous, if want code work, should run counting query in callback of insert query on last iteration. but mentioned, bad practice run them in loop. advice build query string in loop multiple inserts, run once i

c# - How to refresh gridview when I use sqldatasource in asp.net -

i developing asp.net website .this web site multilangual. section of website static , of them dynamic , data database.so in project have master page , have default page filled gridview feed sqldatasource.so when change language english want gridview refresh , retrive english data database , display in gridview .i dont know how please me string language = "fa-ir"; thread.currentthread.currentculture = new cultureinfo(language); thread.currentthread.currentuiculture = new cultureinfo(language); httpcookie langcookies = new httpcookie("language"); langcookies.value = language; langcookies.expires = datetime.now.addhours(1); response.cookies.add(langcookies); <li style="text-align:center; width:130px;vertical-align:top"> <div> <asp:linkbutton id="linkbutton1" runat="server" onclick="linkbutton1_click">فارسی</as

javascript - .load start new path -

in project im trying add modal bootstrap 1 of views , use .load() load view, thing when try load view appears black, tried use console.log() watch errors , saw http://localhost:38212/desafios/details/solucoes/details?id=14 when click div trigger modal, in /desafios/details , , want go /solucoes/details , not url, don't want add .load() url previous url had. how can that? here jquery function $("#visualizarsolucao").click(function (event) { var id = $(this).attr("data-id"); $("#modal").load("../solucoes/details?id=" + id, function () { $("#modal").modal(); }) event.preventdefault() }); i loading js in external file, here visualizarsolucao id called on click event <div class="col-md-10" style="border-left:2px solid black"> <p style="text-align:left;padding-top:5px"> <a href="" id="visualizarsolucao" data-id="@

Populating ComboBox from SQL in C# -

i trying populate combobox sql when assign value member it, gives me following error cannot explicitly convert int string could me understand , correct mistake? void fillcombo() { string query_select = "select * department"; datatable dt = dataaccess.selectdata(query_select); sqldatareader dr = dataaccess.selectdatareader(query_select); while (dr.read()) { string dpt_name = dr.getstring(1); int dpt_id = (int)dr.getvalue(0); combobox1.datasource = dt; combobox1.valuemember = dpt_id; // error here combobox1.displaymember = dpt_name; } } you must assign name of column in datasource ( datatable ) valuemenmber , displaymember string, , don't need use while loop, : void fillcombo() { string query_select = "select * department"; datatable dt = dataaccess.selectdata(query_select); comb

php - Laravel eloquent how to get the minimum value that is not NULL? -

this code in product model minimum price value (one product can have multiple price) public function getlowestattribute () { return $this->prices->min('price'); } but return null rather smallest integer if there null . basically want achieve this: [1, null, 2] returns 1 [1, null, 0] returns 0 any suggestion appreciated. have tried maybe public function getlowestattribute () { return $this->prices->where('price','>=',0)->min('price'); }

c++ - Is a member function allowed to explicitly call its class destructor -

does following code have defined behavior ? if not, part of code ub , section(s) of standard states ub ? if code ub, there [minor] change can fix ? if nothing can fix it, other code scheme/pattern used implement same feature ? class c { public: virtual ~c() {} virtual void switch_me() = 0; }; class c1 : public c { public: c1() : b(true) { std::cout << "c1\n"; } ~c1() { std::cout << "~c1\n"; } private: void switch_me(); bool b; }; class c2 : public c { public: c2() : i(1) { std::cout << "c2\n"; } ~c2() { std::cout << "~c2\n"; } private: void switch_me(); int i; }; void c1::switch_me() { this->~c1(); // lifetime of *this ends here std::cout << "blih\n"; // execute code // not attempt access object new(this) c2(); // create c2 instance in-place } v

java - Automatically get items from observable when an event is fired without an eventbus -

what best way automatically retrieve new items observable when have external event tells you should? for example , lets have , itemrepository implements getallitems() method (which returns observable<list<item>> webservice) , , then, external event (like push notification) tells application data needs refreshed. (also itemrepository used in presenter , presenter has called getallitems , on it's onnext , it's data s refreshed.) i know can done event bus (listen event , when fired, fetch again) , i'm wondering if it's possible automatically. thanks. edit this solution came , of sqlbrite library , not sure if best or cleanest way it. have publishsubject events sent to: publishsubject<object> updateevent; and in getallitems() method , check events subject: public observable<list<item>> getall() { observable.onsubscribe<list<item>> subscribe = subscriber -> { updateevent.subscribe(s -> {

web services - CXF interceptors only for client using configuration -

i have added interceptor in cxf_client.xml same interceptor invoking incoming apis well(i.e cxf_server). below changes. can 1 please tell me why interceptor invoking incoming apis? is because same bus use both server , client? cxf_client.xml <bean id="xcustominterceptor" class="com.test.xcustominterceptor"/> <cxf:bus> <cxf:ininterceptors> <ref bean="xcustominterceptor"/> </cxf:ininterceptors> <cxf:outinterceptors> <ref bean="xcustominterceptor"/> </cxf:outinterceptors> </cxf:bus>* because using <cxf:ininterceptors> <ref bean="xcustominterceptor"/> </cxf:ininterceptors> check documentation http://cxf.apache.org/docs/bus-configuration.html ininterceptors interceptors contributed inbound message interceptor chains. list of s or s you can use specific interceptors inbound c

java - Edittext change Border Color always onclick -

have edittext , want change border color after onclick. after click on it shows me red border color. after try again nothing happens. still red. first click red -> second click black -> third click red , on how can fix it? ... boolean focus = false ... private void setonfocuschangelistener(final edittext edittext) { edittext.setonfocuschangelistener(new view.onfocuschangelistener() { @override public void onfocuschange(view view, boolean hasfocus) { if (!hasfocus) { edittext.setbackgroundresource(r.drawable.black); focus = false; } else if (hasfocus) { edittext.setbackgroundresource(r.drawable.red); focus = true; } else if ((hasfocus) && focus) { edittext.setbackgroundresource(r.drawable.black); focus = false; }

ios - Cannot assign Generic value to protocol associatedType variable in an extension -

i have been struggling mind problem i trying create bindings structure on swift, bind viewmodels , controllers in easy way. have created protocol defines variable stored on controller. protocol dva_movver_viewcontrollerprotocoldelegate { associatedtype delegatetype : dva_movver_viewmodelprotocol var dva_viewmodeldelegate : delegatetype? { set } } as can see, variable restricted fulfill protocol, one: protocol dva_movver_viewcontrollerprotocol { func dva_tellviewmodel() // other methods } i want controller classes implement variable, can stored variable. cannot accomplish using extension. so, have extension second protocol implement bindings , create common method bind variable controller extension dva_movver_viewcontrollerprotocol self:dva_movver_viewcontrollerprotocoldelegate { mutating func dva_bindviewmodel<t:dva_movver_viewmodelprotocol>(parameter:t) { typealias delegatetype = t self.dva_viewmodeldelegate = parameter

Transform XML using XSLT - Root Node not present -

i have 1 xml file : <?xml version="1.0" encoding="utf-8" standalone="no"?> <file> <customer> <lastname>mylastname</lastname> </customer> <cars> <car> <color>blue</color> <model>car2</model> <year>1988</year> <speed>250</speed> </car> <car> <color>green</color> <model>car3</model> <year>1989</year> <speed>350</speed> </car> </cars> </file> i want transform using xslt have : <?xml version="1.0" encoding="utf-8"?> <file> <purchaser> <name>mylastname</name> </purchaser> <vehicles> <vehicle> <vehiclecolor>blue</veh

javascript - What does each of the following codes in a HTML file mean? -

<button type="button" onclick="document.getelementbyid('msg').innerhtml = 'gone!'"> click me!</button> <button type="button" onclick="document.getelementbyid('msg').innerhtml = 'back again!'"> bring me back!</button> can explain each line means? on click of buttons search element id="msg" , set inner html i.e. content of element. https://jsfiddle.net/night11/qs3sl6qt/1/ <p id="msg">my first paragraph</p> <button type="button" onclick="document.getelementbyid('msg').innerhtml = 'gone!'"> click me!</button> <button type="button" onclick="document.getelementbyid('msg').innerhtml = 'back again!'"> bring me back!</button>

r - Delete rows in Data table -

i have twitter dataset , delete whole row if word lee in tweet. have code, still same amount of entries. dt.cleaned <- dt.tweets.filtered[body != "lee",] what code need in order remove whole row if word lee in body? thank much!! we can use grep dt.cleaned <- dt.tweets.filtered[!grepl("lee", body)] assuming 'dt.tweets.filtered' data.table object. if data.frame , either convert data.table setdt i.e. setdt(dt.tweets.filtered) or use base r methods, dt.cleaned <- dt.tweets.filtered[!grepl("lee", body), ]

visual studio 2015 - how to update my textbox total price which is in listbox -

Image
what want added item listbox textbox auto update. have done can added in price add quantity 1 if add 1 item more 1 quantity count quantity 1 item price how solve? count = math.round(qty_of_item, 2) * (product_price) lblprice.text = (" rm " & count) listbox1.items.add(product_name) listbox4.items.add(product_class) listbox5.items.add(product_size) listbox3.items.add((" " & math.round(qty_of_item))) listbox2.items.add(formatcurrency(count)) caculate = count total = 0 dim price decimal = 0 price = total + caculate integer = 0 listbox2.items.count - 1 'get item count inside listview price = (cdec(listbox2.items(0).tostring())) 'get value of item of each item in each listbox row total += price 'add price total next txtsubtotal.text = formatcurrency(total) gst = total * 0.06 txtgst.text = forma

sql server - Dynamic pivot table insert -

i have created dynamic pivot table concatenating column names , executing string. table results this productid b c d in future additional field may entered (e. f... ect) hence need piviot query dynamic. need insert data existing table has columns z. how can create insert query dynamic when new field added insert query doesn't need changed in code? a stored proc (listed below) pivot data few options. can have multiple group by's. following take results #temp table , pivot based on parameters. should note. columns can expressions. select year=year(tr_date),day=day(tr_date),month=right(concat('00',month(tr_date)),2),tr_y10 #temp [chinrus-series].[dbo].[ds_treasury_rates] tr_date>='2000-01-01' exec [prc-pivot] 'select * #temp','month','sum(tr_y10)[]','year,day' returns year day 01 02 03 04 05 06 07 08 09 10 11 12 2000 1

javascript - when component complete render then change route in angular 2 -

i have whatsnew component , route config: @routeconfig([ { path: '/whatsnew', name: 'whatsnew', component: whatsnew }, ]) i'm in other route , component. problem want whatsnew rendered, route change , navigate whatsnew . don't want user see rendering page, how in angular 2? you can implement canactivate lifecycle callback. way can either return promise completes true when call server returns going route fine or redirect route. one problem canactivate decorator , di doesn't support decorators need reference service make server call. this comment contains link plunker demonstrates how di can used canactivate there few issues lifecycle callbacks don't wait promise resolve before continue navigation. don't remember if applies canactivate . there again new router on way , unlikely issues fixed old routers.

ios - How to use More menucontroller in View controller -

can me, i'm having problem uimenucontroller.in here, have use 2 menucontroller in single viewcontroller. first menu "paste",for other menu "copy","select","select all" when i'm using shared menucontroller affects other menu. my code first menu follows: override func canbecomefirstresponder() -> bool { return true } override func canperformaction(action: selector, withsender sender: anyobject?) -> bool { //actions } uimenucontroller.sharedmenucontroller().menuitems = nil let select: uimenuitem = uimenuitem(title: "select", action: selector("select")) let selectall: uimenuitem = uimenuitem(title: "selectall", action: selector("selectall")) let copy: uimenuitem = uimenuitem(title: "copy", action: selector("copy")) let menu: uimenucontroller = uimenucontroller.sharedmenucontroller() menu.menuitems = [select,selectall,copy] menu.se

javascript - Parse promises and loop of query -

i cannot figure out how ca apply promise paradigm code. code doesn't work out how should. last 2 queries not performed... first (mainquery) limited <=5 items should fast enough. pipeline should be: query1.find()->for elements found->if element of type 1 -> query2.count()->if count == 0-> save new object could please me fix it? thank in advance, michele mainquery.find().then( function(items){ (var = 0; < items.length; i++) { if(items[i].get("type") == 1){ var query = new parse.query("invites"); //query.equalto("userid","aaaaaaaa") query.count().then(function(count){ console.log("why don't see in logs...??"); if (count == 0){ var invite = new parse.object("invites"); /

symfony - symfony2 + javascript framework -

my quick question is, should begin using javascript framework @ same time build project symfony or can later without major troubles? i have small project of 1 page app written in flat php , jquery. i'm trying port project symfony , use javascript framework too. after 1 month of learning symfony think begin understand how works, have mess in head javascript frameworks available. think better focus attention symfony , once understand how works try use framework javascript. but i'm afraid of using javascript framework implies changing lot of symfony code , twig templates. right now, i'm using repositories , services data controller , return javascript in json format. understand shouldn't change (at least part data) read articles of people using bundles fosrestbundle , jmsserializerbundle return data , using templates javascript mustache render it, i'm little confused , don't know if big change or if needed between symfony , javacript framework. edit: wh

java - Mule scatter gather custom aggregation get message processor -

im using scatter gather with custom aggregationstrategy. several web service consumers in scatter gather. , need retrieve information consumers such message processor name, original payload, outbound address, etc events.. something that: public class customaggregation implements aggregationstrategy { @override public muleevent aggregate(aggregationcontext context) throws muleexception { (muleevent event : context.collecteventswithoutexceptions()) { ...get message processor name event... ...get message processor payload event... } (muleevent event : context.collecteventswithexceptions()) { ...get message processor name event... ...get message processor payload event... } } } but cant find message processor in events. how this? the message processor payload can found in mulemessage of each muleevent ( event.getmessage().getpayload() ). i'm not sure message processor name or

paypal - Enhanced Recurring Payments with Website Payments Standard Issue -

problem: trying pass along variable monthly subscription cost paypal based on user-selected options on form created more values anothers standart products. working within website payments standard enhanced recurring payment option. details: user visits "shop" page, form 4 line items, each line item consisting of 2-7 options, each option associated price. for example, line item 1 "size of business" options being: a) 1-10 employees - $ 20 b) 11 - 20 employees - $ 30, c) 20+ employees - $40 bought item fixed value $ 25, out recurring payment. is possible? what correct way solve problem api paypal? possible attach signature , normal purchase in same shipment? what adaptative payments solve problem? thanks. paypal website payments standard recurring payments lets define trial periods; use such trial period include higher one-off charge. for details, please take @ html variables page product. for example; $50 / recurring $100 / one-off a

node.js - Error: Cannot find module 'gulp-webserver' -

when running node.js project gulp. i'm getting "error: cannot find module 'gulp-webserver'". re-wrote connection below still same. $ npm install --save-dev gulp-webserver issue existance of web server. solution: go gulp location within solution , use below..solved! $ npm install --save-dev gulp-webserver usefull.. enter link description here

Read the echo output of php file in python -

i have database on backendless cloud service has no support python. so i'm establishing connection between python code , database using php files. the insertion working fine there no response php file python. however in retrieving need php file echo output , python script read echo value. how can this? thanks. use subprocess module execute php code python. assuming php script write standard output subprocess.check_output() easiest, or use subprocess.popen() if need better control of child process. if using python >= 3.5 can use subprocess.run() .

logging - Rails | How to see live server log in production? -

Image
how see live server log in production shown in development? my app on digitalocean, if helps. using unicorn production server. when tail -f log/production.log , can see migration info this, not live requests info along sql queries being run. also in production.rb, changed config.log_level :debug