Posts

Showing posts from March, 2011

shell - Is trap EXIT required to execute in case of SIGINT or SIGTERM received? -

i have simple script trap 'echo exit' exit while true; sleep 1; done and behaves differently in different shells: $ bash tst.sh ^cexit $ dash tst.sh ^c $ zsh tst.sh ^c $ sh tst.sh ^cexit so i'm not sure how should operate , whether specified @ all. the exit trap isn't working same way in every shell. few examples: in dash , zsh it's triggered regular exit within script. in zsh, if trap signal quit execution, need restore default behaviour explicitly calling exit . i'd suggest catch signals , exit, should portable across shells: $ cat trap trap 'echo exit; exit' int term # , other signals while true; sleep 1; done $ bash trap ^cexit $ dash trap ^cexit $ zsh trap ^cexit $ ksh trap ^cexit $ mksh trap ^cexit $ busybox sh trap ^cexit

c# - Use Linq to iterate over ConfigurationManager.ConnectionStrings? -

is possible this? var strings = configurationmanager.connectionstrings; var names = (from d in strings select new connectionname(d.name)); yes, because connectionstrings not implement typed ienumerable , have tell linq type collection contains. use either from connectionstringsettings d in strings or configurationmanager.connectionstrings.cast<connectionstringsettings>() .

javascript - How to get Chosen and FastClick to work on mobile device -

i'm trying add fastclick site uses chosen jquery plugin selects. fastclick, selection boxes stop responding taps on mobile browsers. can replicated chrome device emulation. you can test on simple jsfiddle : <select id="foo"> <option>bar</option> <option>asdf</option> </select> $("#foo").chosen() steps replicate chome canary: load http://fiddle.jshell.net/7ftdo0j3/3/show/ open developer tools , emulate google nexus 7 or apple ipad 1/2 (others might work well) try use select. the main problem have try use 2 libraries together, both either manipulate or interpret touch event weirdly. wanted use phrase "which both black magic touch events", have none experience in using libraries in question, felt perhaps it's not appropriate ;) joking aside, solution problem add fastclick's needsclick class dom elements dynamically created chosen: $("#test").chosen(); $(".

How can I run this JavaScript snippet only once when a user logs in? -

i have simple javascript snippet. <script> window.onload = function(){ swal("hello!", "welcome portal", "success"); }; </script> how can run if page url http://portal/?init i.e. not run when page url http://portal or http://portal/?something_else ? check location.search of page. <script type="text/javascript"> if(location.search == "?init"){ window.onload = function(){ swal("hello!", "welcome portal", "success"); }; } </script>

angularjs - Form not adding to array and clearing -

in controller, have simple array , function: $scope.newguarantor = ''; $scope.guarantors = [ {guarantor: 'peter parker'}, {guarantor: 'bruce wayne'} ]; $scope.addguarantor = function(){ $scope.guarantors.push({ guarantor: $scope.newguarantor }); $scope.newguarantor = ''; }; in view have simple list , form: <tr ng-repeat="pg in guarantors"> <td>{{pg.guarantor}}</td> </tr> <tr> <td> <form ng-submit="addguarantor()"> <input type="text" ng-model="newguarantor"/> <button type="submit"> <span class="glyphicon glyphicon-plus"></span> </button> </form> </td> </tr> according read, should able type value input , click button , value of input should added listed array , form cleared. instead, getting empt

jquery animation scrollTop dont work in ie or firefox -

a simple scroll top effect...the code doesn't work in ie or firefox works fine in chrome. html this : <a href="#" class="scrolltop"><i class="glyphicon glyphicon-chevron-up"></i></a> and script this : $(document.body).animate({ 'scrolltop':'0' },2000); i have tried replace $(document.body) $("body") ,nothing happen... i posted similar answer on post: jquery add ids paras make them linkable. i tested following code on firefox , ie 10 , works fine. $('html, body').animate({ scrolltop : 0 }, 500);

excel - AutoHotkey's ComObjActive handle to specific Worksheet -

the simplest way create handle active excel sheets in .ahk script is: xl := comobjactive("excel.application") nonetheless, if 1 switches workbook, becomes new " currently active sheet " , autohotkey tries use methods sheets , cells on new workbook through com: of course scripts designed work specific sheets , cells don't work anymore on different workbook. do know how create com handles specific workbooks instead of active sheet? the goal should allow user loop between workbooks without xl object losing previous handle , going new one. example open excel workbook scratch , type 1234 in cell a1 of sheet named " sheet1 "; create new .ahk script following content: #persistent xl := comobjactive("excel.application") settimer, xlread, 5000 return xlread: { value := xl.sheets("sheets1").range("a1").value msgbox, %value% } return script above should display "1234" in message box every 5 secon

Can not use subtract operator with Double.MAX_VALUE Java -

i'm trying following code: double = double.max_value - (1000000000 * 100000000 * 1000000); system.out.println(a); however, result still 1.7976931348623157e308 (max value of double) can explain me? 1000000000 * 100000000 * 1000000 multiplication of 3 integers, results in overflow. even if avoid overflow writing : double = double.max_value - (1000000000.0 * 100000000.0 * 1000000.0); you still see no difference since number subtracting double.max_value negligible compared double.max_value (~1.797*10^308, 275 orders of magnitude larger trying subtract it).

android - How i can get ActionBarActivity from a Calss that extends from Fragment? -

how can actionbaractivity class extends fragment . this class : public class email_fragment extends fragment{ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); actionbaractivity activity ; activity = this; } public email_fragment() { super(); } @override public void onattach(activity activity) { super.onattach(activity); } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.email_fragment, container, false); return rootview; } } i need : actionbaractivity activity ; activity = this; and need use clicklistener . notice : using import android.support.v7.app.actionbaractivity; in fragment can call getactivity() "parent" activity. if fragment lives inside of actiobaractivity can cast follow

java - Configuring Spring + Hibernate JPA Transaction Manager through JTA -

i had config hibernate using resource-local transaction type: persistence.xml: <persistence-unit name="mypu" transaction-type="jta"> <provider>org.hibernate.jpa.hibernatepersistenceprovider</provider> </persistence-unit> applicationcontext (dataaccess bit): <bean class="org.springframework.orm.jpa.support.persistenceannotationbeanpostprocessor" /> <bean id="transactionmanager" class="org.springframework.orm.jpa.jpatransactionmanager" p:entitymanagerfactory-ref="entitymanagerfactory"></bean> <bean id="entitymanagerfactory" class="org.springframework.orm.jpa.localcontainerentitymanagerfactorybean"> <property name="datasource" ref="datasource" /> <property name="jpavendoradapter" ref="jpaadapter" /> <property name="persistenceunitname" value="mypu"/>

C++ How to loop through set in map? -

i stuck on 1 problem in school project: need set of numbers mapped key number. zz class big integers ntl library, that's not important. program fails on inner loop message it_set2 can't iterable. std::map<zz, std::set<zz>> mapa; std::map<zz, std::set<zz>>::iterator it_map; std::set<zz>::iterator it_set1, it_set2; (it_map = mapa.begin(); it_map != mapa.end(); ++it_map) { (it_set1 = it_map->second.begin(); it_set1 != it_map->second.end(); ++it_set1) { (it_set2 = ++it_set1; it_set2 != it_map->second.end(); ++it_set2) { /* function uses *it_set1, *it_set2 */ } } } thanks help. i suppose problem in inner loop. if want it_set2 point next element it_set1 pointing (but not incrementing it_set1 ) should change third loop following: for(it_set2 = it_set1; ++it_set2 != it_map->second.end(); ) . this make sure you're not going out of bounds , not

functional programming - Implicit class in Scala -

i have following piece of code.i have confirm whether way how works..can provide explanation this object implicits { implicit class richseq[a](val xs:seq[a]) { def mapd[b](function:a => b):seq[b] = xs.map(function) } } this abstraction on map can use sequence. if import implicits.richseq can use methods on seq[a] convert seq[a] richseq[a]. import implicits.richseq._ val xs:seq[int] = seq(22,33) val output:seq[int] = xs.mapd(_+22) i want know how works because when use mapd on type seq[a] search implicit conversion seq[a] richseq[a].where find implicit conversion implicit class? does expand implicit class like: implicit def richseq[a](val xs:seq[a]) = new richseq(xs) i think might doing stuff inside.does ne1 know this? an implicit class shorthand for class foo(a: a) implicit def pimpmya(a: a) = new foo(a) you can annotate class implicit if constructor takes 1 non-implicit parameter. here's relevant doc can read more it: http://docs.scal

java - PlayFramework Result with Ajax -

according : playframework document 2.0 & playframework document 2.1 i know in play can return: ok() badrequest() created() status() forbidden() internalservererror() todo etc... i send ajax response information in it. unfortunatelly play sends status information, , kind of object not understand. method ok("test message") sends status , message information. rest of dosnt work. how deal it? -- edit -- i have ajax method: $.post($("#assignmentsubmitaddress").text(), { 'units' : submittedunits }, function(response, status, xhr) { shownotyfication(status, response); }) when return ok("test"); in java script variable response have string test when return badrequest("test"); in java script variable response have java object. when print variable response getting object object . to send response in json format client send ok containing string : /** * translate json object json string. */ public

Python if-elif statements order -

i've encountered problem seems pretty basic , simple , can't figure out proper , elegant way how solve it. the situation is: there's player can move - let's upward. while moving can encounter obstacles - let's trees. , can bypass them using pretty simple algorithm one: if <the obstacle has free tile on right>: move_right() elif <the obstacle has free tile on left>: move_left() else: stop() well, works perfectly, there's drawback: if obstacle has free tiles both right , left can bypassed both sides, player bypasses right. it's pretty explainable, still not cool. the idea add variety , randomize somehow order in player checks availability of tiles if both free move not right, in random direction. , must admit cannot come idea how in simple , beautiful way. basically, solution should this... if random(0, 1) == 0: if <the obstacle has free tile on right>: move_right() elif <the obstacle has free tile on le

add on - MailApp limit from Google appscript trigger -

it seems limit of 100/day mailapp applied add-on script (even of store). there way increase it, on add-on or @ user side? yes, limits apply scripts, add-ons. there's 1 way increase it, use google apps business . can see quota dashboard under 'quota limits', limit google apps business users 1500 email recipients/day. alternatively, recipient limit, if you're sending same message several recipients, utilize service such google groups business limit amount addresses send to, avoiding hitting quota. slight edit: answer below query, believe it's domain installing script needs upgrade higher quota, i've never confirmed. can check how quota user has left using https://developers.google.com/apps-script/reference/mail/mail-app#getremainingdailyquota() in script, might troubleshooting.

c - Linked list issue with ARM processor -

i'm trying create linked list in c run on arm processor (not sure exact processor specs, -mcpu=arm7tdmi passed compiler) using gcc. here's code: #include <posapi.h> #include <posapi_all.h> const appinfo appinfo={ "pos-simple example", "app-test", "1.0", "pcteam", "demo program", "", 0, 0, 0, "" }; typedef struct st_dllnode { struct st_dllnode * next; struct st_dllnode * prev; void * data; } dllnode; typedef struct { dllnode* first; dllnode* cur; uchar size; } listcontainer; typedef listcontainer* list; list createlist(void) { list listcontainer; listcontainer = (list) malloc(sizeof(listcontainer)); listcontainer->first = null; listcontainer->cur = null; listcontainer->size = 0; // exception occurs here return listcontainer; } int event_main(st_event_msg *msg) { systeminit(); return

xml - How to change maven outputdir value during run time? -

my maven pom.xml file looks below, <configuration> <!-- output directory testng xslt report --> <outputdir>\target\testng-xslt-resultsreports</outputdir> <sorttestcaselinks>true</sorttestcaselinks> <testdetailsfilter>fail,skip,pass,conf,by_class</testdetailsfilter> <showruntimetotals>true</showruntimetotals> </configuration> my question is, during every run create folder , need update path "outputdir" ? can done? use maven property (with default value) , pass command line. in pom.xml: <properties> <customoutput>\target\testng-xslt-resultsreports</customoutput> </properties> ... <configuration> <outputdir>${customoutput}</outputdir> .... now simpley run maven command parameter override default value of customoutput : mvn install -dcustomoutput=\target\newoutputdir i hope helps

when drawing a filled circle, gnuplot gives different output between x11 terminal and latex terminal, why? -

Image
i switched tikz gnuplot drawing math diagrams recently. find them different. i want draw circle, created .gpi file: set terminal latex set out 'gp.tex' set xrange [-5:5] set yrange [-5:5] set object 1 circle @ 0,0 size char 1 fillcolor rgb "black" fillstyle solid plot nan set out set terminal x11 plot nan and loaded in gnuplot. the circle in x11 terminal filled, expected: http://i.imgur.com/xdmlta4.png but 1 compiled gp.tex hollow circle: http://i.imgur.com/7lnzvmw.png why? how can produce filled circle in tex file well? the latex terminal old , doesn't support filled circles. should use 1 of other latex-related terminals epslatex , cairolatex or tikz support filled circles. see output of test command see features supported terminal. filled circles, filled polygons must supported. latex get:

function - Sass extend with pseudo selectors -

i using compass manage sass files on mac osx. have these files: sass/ screen.scss partials folder/ ... _fonts.scss _functions.scss ... in fonts have rule reuse @extend. //fonts.scss .icon-ab-logo, { font-family: 'icomoon'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; } .icon-ab-logo:before { //i want reuse this. content: "\e000"; } in functions have screen.scss: .logo { position: absolute; top: 0; bottom: 0px; z-index: 500; width: 9.5em; background: $logo; @include transition(all 0.2s); &:after{ @include icon( ".icon-ab-logo" ); } } finally in functions.scss call this: @mixin icon( $icon ){ font-family: 'icomoon'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line

Haskell - parse error on input "=" -

i have following problem: we can cycle list fixed amount taking given number of items off front , adding them of list. write function called rotor rotor 6 "abcdefghijklmn" produces "ghijklmnabcdef". give type definition rotor. make sure returns error message if offset number less 0 or bigger or equal length of list. and following haskell code: rotor :: (ord a) => -> [a] -> [a] rotor (x:xs) | if < 1 = error "error" | [] = [] | otherwise = rotor a-1 xs ++ [x] but when compile following error: parse error on input "=" i don't understand i'm doing wrong. ideas? rotor :: (ord a) => -> [a] -> [a] rotor (x:xs) this line matches non-empty lists x:xs , only. | if < 1 = error "error" no if needed here. | [] = [] this should have been pattern: after | boolean expression expected. an amended version of code: rotor :: (ord a) => -> [a] -> [a] rotor

rails joins with select returns nil as id -

why joins query returns id null in last haven't query id. how should prevent that? 2.1.3 :038 > foo.select('bars.comment_1, bars.comment_2, foos.rating').joins(:bars).each |b| 2.1.3 :039 > p b.to_json 2.1.3 :040?> end foo load (0.3ms) select comment_1, comment_2, rating `foos` inner join `bars` on `bars`.`foo_id` = `foos`.`id` "{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"good\",\"id\":null}" "{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"good\",\"id\":null}" "{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"fair\",\"id\":null}" "{\"comment_1\":\"xyz\",\"comment_2\":\"uvw\",\"rating\":\"poor\",\"id\":null}&q

how to enable settings and developer section in umbraco? -

i'm newbie in umbraco development. enable "settings" , "developer" section in dashboard. don't know how enable them. checked in web.config file didn't find here. appreciated ! thanks ! log in admin in umbraco (must admin account). go users > [username] > select settings , developer in sections.

c# - unable to download file from server in asp.net application -

i having exception when try download file server in asp.net application : this code : try { response.appendheader("content-disposition", "attachment; filename=" + "toto"); response.transmitfile(server.mappath("fda//toto.txt")); response.end(); } catch (exception ex) { var exception = ex; } and exception when debug code , put breakpoint @ "catch exception": ex = {unable evaluate expression because code optimized or native frame on top of call stack.} when run code without debuging , no breakpoints, getting : my code stop in "scriptresource.axd.....acab[dynamic] page @ line "throw error" following visual studio pop : sys.webforms.pagerequestmanagerparsererrorexception: and have 3 buttons on pop : break, continue, ignore.

android - Jsoup selector syntax for div having same class -

<div class="row"> <div id="content"> <div class="textdata"> </div> <div class="textdata"> </div> </div> </div> i want text second div class=textdata. did parsed div id=content. here doinbackground try { document document = jsoup.connect(url).get(); elements myin = null; myin = document.select("div.horoscopetext:eq(1)"); desc = myin.text().tostring(); } catch (ioexception e) { e.printstacktrace(); } try this div#textdata:eq(1) eq(n) accepts zero-based index of matched elements. btw, shouldn't have multiple elements same id, use class that. check out selector syntax documentation more examples. edit for class instead of id, use div.textdata:eq(1)

ruby on rails 3.2 - Nginx configuration resulting in too many connections -

in attempt implement upload progress module , following server configuration resulting in too many open files error 2014/11/19 12:10:34 [alert] 31761#0: *1010 socket() failed (24: many open files) while connecting upstream, client: 127.0.0.1, server: xxx, request: "get /documents/15/edit http/1.0", upstream: "http://127.0.0.1:80/documents/15/edit", host: "127.0.0.1" 2014/11/19 12:10:34 [crit] 31761#0: *1010 open() "/usr/share/nginx/html/50x.html" failed (24: many open files), client: 127.0.0.1, server: xxx, request: "get /documents/15/edit http/1.0", upstream: "http://127.0.0.1:80/documents/15/edit", host: "127.0.0.1" the following relevant part of server bloc generating conflict passenger_enabled on; rails_env development; root /home/user/app/current/public; # redirect server error pages static page /50x.html error_page 500 502 503 504 /50x.html; location

java - SNAPSHOT and RELEASE versions are not getting update at Maven Local Repository -

i had set nexus repository link-up 2 separate projects. building , deploying release , snapshot versions on nexus when trying use changes in other project using maven update changes not getting updated. so did in a_project.jar in 1 project got updated in nexus repository. but when trying updated jar @ b_project, getting old jar there in maven's local repository. now, if manually delete a_project.jar, apparently gets updated code. for achieving updated version of snapshot , released version had tried following ways. i had used -u mvn clean build. i have changed update policy in setting.xml , pom.xml follows. in settings.xml <pluginrepository> <id>deployment</id> <name>internal nexus repository</name> <url>http://server/nexus/content/groups/public/</url> <layout>default</layout> <snapshots> <enabled>true</enabled&g

java - Arrays should not be statically initialized by an array initializer. Why? -

this 1 of rules googles static analyser codepro analytix: summary arrays should not statically initialized array initializer. description this audit rule checks array variables initialized (either in initializer or in assignment statement) using array initializer. example the following array declaration flagged because of use of array initializer: int[] values = {0, 1, 2}; now, can disable if don't it, that's not problem. i'm wondering why problem, , solution keep code being flagged audit rule? it's interesting question, , decision groundless imho. (i hope else answer thread if there legit reason behind design decision). moreover, google shows how format static initializers in practice formatting guide https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.8.3.1-array-initializers without saying how bad use constructs ... i guess person behind rule had tooth against style of programming :)

excel - With VBA how to apply conditional formatting to the last column of a pivot table according specific cell values -

i have below pivot table : risk impact high low medium grand total aa 2 7 3 12 ab 10 10 ac 2 1 2 5 ad 2 1 3 ae 1 1 ba 3 1 4 bb bc 1 1 and apply specific cell colour according value of each cells describe below: no risk findings : "grand total cell colour" = green 1 2 low risk findings; or 1 medium risk finding : "grand total cell colour" = orange as of more 2 low risk findings; or of 1 low risk finding , 1 medium risk finding;or of more 1 medium risk finding; or of 1 high risk finding : "grand total cell colour" = red the approach tried define each "pivot item" , apply if s

web - Does ST(State Transfer) in REST mean that state must be held by client? -

i read what “state transfer” in representational state transfer (rest) refer to? , several post or videos rest, , know 1 of constraint of rest stateless. according many posts http://www.restapitutorial.com/lessons/whatisrest.html ,to make architecture stateless, client must hold enough information server right thing, means server not have client state. mean build rest application through putting user state in client cookie? but according many posts pros , cons of sticky session / session affinity load blancing strategy? , can make stateless application storing user data in database or memcache, avoid storing session in application server. if try approach, can make rest architecture? the idea of honest rest service allow easy communication client, client not in web browser: mobile or desktop application or else. so, each request service must provide necessary information process request. keeping state on server complicate task, because clients not control it. so,

c# - Background worker runs doWork multiple times -

private void button_uploadtopi_click(object sender, routedeventargs e) { this.newfilepath = this.textbox_input_filepath.text; this.label_status.content = ""; if (bgworker.isbusy != true) { bgworker.runworkerasync(); } } here click event. public mainwindow() { initializecomponent(); this.progressbar.minimum = 0; this.progressbar.maximum = 100; this.bgworker = new backgroundworker(); this.bgworker.workerreportsprogress = true; this.bgworker.workersupportscancellation = true; reader.isopen = false; this.bgworker.dowork += bgworker_dowork; this.bgworker.progresschanged += bgworker_progresschanged; this.bgworker.runworkercompleted += bgworker_runworkercompleted; } main window method. public partial class mainwindow : window { private backgroundworker bgworker; bgworker initialized here. void bgworker_runwo

android - Eclipse Giving me the R cannot be resolved to a variable error, have tried every fix -

i getting typical "r cannot resolved variable error" have tried feel every "fix" , still can't work. think has many errors getting res folder: res\values\styles.xml:7: error: error retrieving parent item: no resource found matches given name 'theme.appcompat.light'. res\values-v11\styles.xml:7: error: error retrieving parent item: no resource found matches given name 'theme.appcompat.light'. res\values-v14\styles.xml:8: error: error retrieving parent item: no resource found matches given name 'theme.appcompat.light.darkactionbar'. and many other similar errors xml files in appcombat_v7 folder. i have tried cleaning project, building project, have updated android sdk tools , adt eclipse newest version, using android 4.4 target of project. any nice edit: error: warning: unable write jarlist cache file h:\workspace\appcompat_v7\bin\jarlist.cache , on activity_main.xml in layout folder: project target (android 5.0) not load

javascript - Want to get the div object that is currently visible -

on window scroll end want know div current visible user? how can name of div on screen or can div visible user through jquery? check visibility of div using it's id. retrieve name of div. if($('#divid').is(':visible')) { alert($('#divid').attr('name')); }

java - Tyrus server endpoint @OnMessage method not triggered -

i attempting run simple websocket example using tyrus 1.8.3 , javax.websocket api, following https://blog.openshift.com/how-to-build-java-websocket-applications-using-the-jsr-356-api/ guide. using annotations, have created simple server endpoint , client endpoint triggers method annotated with@onopen correctly. however, when send message client, method @onmessage not triggered on server side. interestingly, session id created @ onopen differs between client , server. don't understand why , think may problem? should session ids not same - there 1 session... i have written simple javascript client connect same server endpoint , not trigger @onmessage method, suspecting there issue on server side. i have raised log level fine nothing reported @ info level. logs looks websocket upgrade successful , connection opened ok. javax.naming.noinitialcontextexception thrown on both client , server i'm not sure if relevant... i have uploaded of code github here: https:/

javascript - View template compilation in Angular JS -

i writing frontend app in angularjs. using lot of custom directives include templates, f.ex. <body> <my-header></my-header> <site-information></site-information> </body> defined in angular app: var app = angular.module('myapp'); app.directive('myheader', function() { return { 'restrict': 'e', 'templateurl': '/partials/template.html' } }); and on. however, useful me, if template include 2 different parts, or "sub-templates", without doing 2 more ajax-requests. in other words, template "compiled" before being shown. <!-- template.html --> <div class="row"> <div class="col-md-6"> {{ content_one }} </div> </div> <div class="row"> <div class="col-md-6"> {{ content_two }} </div> </div> is there easy way achieve th

vi - Vim Undo command (the one with the with capital U) -

i don't understand how undo line command works. the documentation says undo latest changes on 1 line. what definition of all latest changes here. one behaviour have noticed u undoes writes after first write on line. not consistent. example when open new file edit first line, writing multiple times, u command undoes every single change. i haven't been able find concrete google searches either.. in understanding all latest changes means going change history until change in different line encountered, , stop there. if start empty buffer , edit 1 line (repeatedly), additions wiped u . vim merges near changes occurring in same line; these appear single entry in :changes .

php - OpenCart Call Different Controller -

i have custom module, , want call add() function checkout/cart . how call controller , function? i have tried $this->load->controller('checkout/cart'); returns fatal exception. i using opencart v 1.5.6.4 to solve same issue, use $this->load->controller("checkout/cart/add"). if use getchild, exception thrown : "call undefined method loader::getchild()". what difference between 2 methods? getchild better?

if statement - How can I change Image on switch case in android? -

i building android application user enter fix thing in edit text filed , value of edit text parse second activity using singleton class. now need when text on second activity ice-cream there ice-cream image available in project need in image-view image of ice-cream display. let take second case if user enter value food image of food should display in image-view. i think can if..if else..else case. if right please me. i new android. here code - imageview imgsport = (imageview) convertview.findviewbyid(r.id.sportimageevent); textview title = (textview) convertview.findviewbyid(r.id.title); title.settext(m.gettitle()); let me more clarify if title ice-cream set image-view ice-cream image. try below code: string value=m.gettitle(); if(value.equalsignorecase("icecream")){ imageview.setimageresource(r.drawable.icecream); }else if(value.equalsignorecase("food")){ imageview.setimageresource(r.drawable.fo

android - Wrong backgroundcolor on ListView inflate -

so have listview uses custom adapter. want background color of item either red or green, depending on value out of database getdbvalue(); (this works). the problem is, when activity first opened, , listview inflated, listview items have same (not correct) green background color. when start scrolling though, background set correctly. how right background color when listview inflates , program "error"? i have debugged , dbvalue returning correct value. this code: public view getview(int position, view convertview, viewgroup parent) { return createviewfromresource(position, convertview, parent, mresource); } private view createviewfromresource(int position, view convertview, viewgroup parent, int resource) { view v; if (convertview == null) { // first time views created v = minflater.inflate(resource, parent, false); } else { v = convertview; } string dbvalue = getdbvalue(); if(!dbvalue.equals("

mysql - Determine where function was called from in php -

i trying call method this: <?php getalluser($catid);?> and there select query in getalluser() method: function getalluser($query) { $sql = "select * user catid='".$query."'"; } in page, call same method , pass user id instead of category id so: <?php getalluser($userid);?> now, how can identify if there category id or user id in $query, can change in condition base on $query. add parameter, called from. options should be: users categories function getalluser($query, $calledfrom = '') { if ($calledfrom == 'users') { $sql = "select * user catid='".$query."'"; } if ($calledfrom == 'categories') { // sql fetching categories. } } and call function like: <?php getalluser($catid, 'users');?> <?php getalluser($catid, 'categories');?>

ios - UICollectionView, cells are overlapped by Navigation bar -

Image
want remove space below collectionview cells: uicollectionviewflowlayout *flowlayout = [[uicollectionviewflowlayout alloc] init]; [flowlayout setitemsize:cgsizemake(300, 435)]; [flowlayout setminimuminteritemspacing:0.0f]; [flowlayout setminimumlinespacing:20.0f]; [flowlayout setsectioninset:uiedgeinsetsmake(0, 10, 0, 10)]; [flowlayout setscrolldirection:uicollectionviewscrolldirectionhorizontal]; [self.collectionview setcollectionviewlayout:flowlayout]; try adding in -viewdidload : if ([self respondstoselector:@selector(edgesforextendedlayout)]) self.edgesforextendedlayout = uirectedgenone;

java - How to output an error message in my JSF page, related to my httpresponse error -

i have logic code (putting error response): public modelandview resolveexception(httpservletrequest request, httpservletresponse response, object handler, exception ex) { boolean maxsizeex = true; if (ex instanceof maxuploadsizeexceededexception) { logger.debug("tried upload file exceeded capacity", ex); } else { logger.warn("caught unexpected exception", ex); maxsizeex = false; } final boolean fmaxsizeex = maxsizeex; view view = new view() { public void render(map model, httpservletrequest request, httpservletresponse response) throws exception { map<string, string> data = new hashmap<string, string>(); if (fmaxsizeex) { data.put("error", "limit size exceeded"); } else { data.put("error", "internal error"); } jsonapicontroller.maptojsonandoutput(resp

scripting - How do I execute Maya script without lauching Maya? -

for example, want launch script creates poly cube, export .stl or .fbx command line. i can in python using maya standalone cannot handle exporting other formats .ma apparently why of course can. here's how you'd (for fbx): from os.path import join maya.standalone import initialize import maya.cmds cmds import maya.mel mel initialize("python") cmds.loadplugin("fbxmaya") my_cube = cmds.polycube() cmds.select(my_cube[0], r=true) my_filename = "cube2.fbx" my_folder = "c:/somefolder/scenes" full_file_path = join(my_folder, my_filename).replace('\\', '/') mel.eval('fbxexport -f "%s"' % full_file_path) hope useful.

java - NullPointerException org.hibernate.cfg.OneToOneSecondPass.doSecondPass -

i using hibernate 3.0 i have following tables , corresponding entries, table a: integer aid; integer bid; table b: integer bid; @entity @table(name="a") public class { @id @generatedvalue(strategy=generationtype.auto) @column(name="aid") integer aid; @onetoone(targetentity=b.class) @joincolumn(name="bid", referencedcolumnname="bid") b b; } @entity @table(name="b") public class b { @id @generatedvalue(strategy=generationtype.auto) @column(name="bid") integer bid; @onetoone(targetentity=a.class, mappedby="b") @joincolumn(referencedcolumnname="bid") a; } when try run spring application above configuration, following error, caused by: java.lang.nullpointerexception @ org.hibernate.cfg.onetoonesecondpass.dosecondpass(onetoonesecondpass.java:135) @ org.hibernate.cfg.configuration.secondpasscompile(configuration.java:1163) @ org.hibernate.cfg.annotationconfiguration.secondpasscompile

python - Combine threads -

i'm making program reads udp socket decodes information steim1 function, want plot information on pyqwt when try upload information graph error (core dumped) appears. searched information on web support, part of graph. #!/usr/bin/env python import random, sys pyqt4 import qtgui, qtcore import socket import threading import queue datetime import datetime, date, time import milibreria pyqt4.qwt5 import * host = '0.0.0.0' port = 32004 buffer = 1024 my_queue = queue.queue()#################################################### my_queue1= queue.queue() class readfromudpsocket(threading.thread): def __init__(self, my_queue): threading.thread.__init__(self) self.setdaemon(true) self.my_queue = my_queue def run(self): while true: buffer1,addr = socketudp.recvfrom(buffer) self.my_queue.put(buffer1) print 'udp received' class process(threading.thread): def __init__(self, my_queue,my_qu

Rails and devise: model attribute not being persisted -

i edited devise's registrationscontroller::create method modify behaviour. i'm trying if there no admin users in database, 1 first signs going assigned admin role, else regular user. however, role, though assigned correctly object (tested), it's not being persisted database. model: class user < activerecord::base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessor :role roles = [ :admin, :default ] def is? requested_role self.role == requested_role.to_s end def self.admin_role return roles[0] end def self.default_role return roles[1] end end modified devise method: def create build_resource(sign_up_params) admin_user = user.find_by_role(user.admin_role) if admin_user.nil? resource.role = user.admin_role else resource.role = user.default_role end # here puts resource.role shows what's expected indeed being assigned object

jsf 2.2 - Change Skin of Richfaces Application without reloading the page -

i have jsf 2.2 , richfaces 4 application , in application have à h:selectonemeun have a4j:ajax event: on change , listner et status attribute. want when change value of selectonemenu change them or skin of page whitout reloading page (ajax). <h:selectonemenu value="#{managcontroller.selectedprodgroup}" class="validate[required] text-input" requiredmessage="#{messages['group.product.required']}" style=" width : 285px;" converter="omnifaces.selectitemsconverter"> <f:selectitem itemlabel="#{messages['productgroup.noselection']}" itemvalue="" /> <f:selectitems value="#{bmanager.productgrouplist}" var="productgroupvar&quo

javascript - AngularJS dependencies: constant / controller etc. not loaded in a module -

i've stumbled upon this question here looking reason, defined factory not loaded. wondered terms "defined in angular module". if have kind of service this: angular.module('d3', ['underscore']) .factory('d3', ['$window', 'underscore', function($window, _) { if (!_.isobject($window.d3)) { throw "services.d3: moment library missing!"; } else { return $window.d3; } } ]); and when try load service in module this: angular.module("widgets.d3widget", ['underscore']) .controller("widgets.d3widget.d3widgetctrl", [ "$scope", "d3", function( $scope, d3 ) { console.log(d3.select('body')); //work goes here } ]); the service not loaded. rather angular error like: "error: [$injector:unpr] unknown provider: d3provider <- d3 .

module - AngularJS ckEditor, multiple instances -

i have app drag , drop functionality. also, possible drop ckeditor in it. how possible create new instance of ckeditor, problem have instances have same "ng-model". i saw answer "ng-repeat" here: jsfiddle.net/thesharpieone/cptr7/ app not have such repeater. thank you had similar problem, don't know if can you, solved problem. var app = angular.module('app', []); app.directive('ckeditor', [function () { return { require: '?ngmodel', link: function ($scope, elm, attr, ngmodel) { var ck = ckeditor.replace(elm[0]); ck.on('pastestate', function () { $scope.$apply(function () { ngmodel.$setviewvalue(ck.getdata()); }); }); ngmodel.$render = function (value) { ck.setdata(ngmodel.$modelvalue); }; } }; }]) function myctrl($scope){

groovy - TJWSEmbeddedJaxrsServer and ContainerRequestFilter -

i writing integration test based on spock test our rest api using jax-rs client api , tjwsembeddedjaxrsserver . work smooth far write test integrating server request filter. since @provider classes implementing containerrequestfilter interface not discovered , called @ runtime wanted ask how have register filter class manually? can give me hint on one? @contextconfiguration("classpath:applicationcontextrestintegrationtest.xml") @activeprofiles(['local', 'compliance']) @testexecutionlisteners([dependencyinjectiontestexecutionlistener.class, dirtiescontexttestexecutionlistener.class]) class restspec extends specification implements jaxrsinterceptorregistrylistener { @autowired applicationcontext applicationcontext @autowired ksdapischemarequestfilter filter @override void registryupdated(jaxrsinterceptorregistry registry) { println "xxxx" } void "test rest api"() { given:

R merge multiple XML files -

i unfamiliar xml have 700 xml files have code extract right data , put them in csv. merge xml files not know function have use. extraction use xml library. all xml files same in structure. can me out? couldn't find answer here. thanks in advance.

javascript - How do I remove the default Alert that comes up with invalid format on AjaxFileUpload? -

i have ajaxfileupload control, , using jquery popup error wrong file type. ajaxfileupload, however, apparently has default, not-so-pretty alert comes when incorrect file type added. results in default alert showing, modal showing. cannot remove allowedfiletypes property because when unwanted file gets added anyway. know how rid of default alert ajaxfileupload throws? <div class="upload-photos-add" id="q0012_00" runat="server"> <asp:ajaxfileupload enableviewstate="false" id="ajaxfileupload2" contextkeys="0012.00" runat="server" allowedfiletypes="jpg,jpeg,png" onuploadcomplete="ajaxfileupload_uploadcomplete" onclientuploadcomplete="onclientuploadcomplete" onclientuploadcompleteall="onclientuploadcompleteall" onclientuploadstart="onclientuploadstart"> </asp:ajaxfileupload> </div>

how to sort array according to index of key in php -

this array: $arr = array("pic0", "pic1", "pic2", "pic3", "pic4"); how can following strings: $str1 = "pic1,pic2,pic3,pic4,pic0"; $str2 = "pic0,pic2,pic3,pic4,pic1"; $str3 = "pic0,pic1,pic3,pic4,pic2"; $str4 = "pic0,pic1,pic2,pic4,pic3"; $str5 = "pic0,pic1,pic2,pic3,pic4"; i'd use array, not 5 strings: $arr = array ("pic0", "pic1", "pic2", "pic3", "pic4"); $final = array (); for($i=1, $c = count($arr); $i <= $c; ++$i) // loop n times { $tmp = $arr; // tmp array $x = $arr[$i-1]; // element put in end unset($tmp[$i-1]); // unset tmp array $final[$i] = implode(",", $tmp) . "," . $x; // concatenate array $x in end } print_r($final); /* array ( [1] => pic1,pic2,pic3,pic4,pic0 [2] => pic0,pic2,pic3,pic4,pic1 [3] => pic0,pic1,pic3,pic4,pic2 [4] => pic0,

ios - How to have multiple image paths in array? -

i need display both .png's , .jpg's, unsure of how display both. code below works: nsarray *imagepaths = [[nsbundle mainbundle] pathsforresourcesoftype:@"png" indirectory:@"carseats"]; but doesn't: nsarray *imagepaths = [[nsbundle mainbundle] pathsforresourcesoftype:@"png, jpg" indirectory:@"carseats"]; get png , jpg paths separately , combine arrays: nsarray *pngpaths = [[nsbundle mainbundle] pathsforresourcesoftype:@"png" indirectory:@"carseats"]; nsarray *jpgpaths = [[nsbundle mainbundle] pathsforresourcesoftype:@"jpg" indirectory:@"carseats"]; nsarray *imagepaths = [pngpaths arraybyaddingobjectsfromarray:jpgpaths];

javascript - Rails + simple_form + remote_true + custom controller: how to handle different form actions for 'new' and 'edit'? -

i'm following tutorial: http://www.gotealeaf.com/blog/the-detailed-guide-on-how-ajax-works-with-ruby-on-rails variation: after creating scaffold 'tasks' (controller, model, views...) i've created new controller, named ' demo ', test ajax way. 'demo' controller has following actions: index, new_task, create_task, edit_task, update_task. routes adjusted. when render form (app/views/demo/_form.html.erb) <%= simple_form_for @task, remote: true |f| %> <%= f.input :description %> <%= f.input :deadline %> <%= f.button :submit %> <% end %> the form 'action' '/tasks', corresponds 'controller:tasks, action:create', controller "old html" way, while ajax stuff in 'demo' controller. so, following answers found on web i've added 'url' parameter: <%= simple_form_for @task, remote: true, ur

Toggle show/hide divs if data.entities.length > 0, tertiary operator doesn't work on Javascript/jQuery? -

i need toggle visible/hidden 2 different divs if data.entities.length > 0 , i'm doing: if (data.entities.length > 0) { var toggle = data.entities.length ? true : false; // if condition true show otherwise hides $('#resultadonorma').toggle(toggle); // reversal process // if condition true goes hide otherwise goes show $("#sinresultadosbuscarnormas").toggle(!toggle); } but it's not working since none div show/hide not matter happen condition, wrong? can use tertiary operator in javascript? your use of conditional operator inside if() statement, succeeds if there's positive .length , toggle true . you should remove if() statement. var toggle = data.entities.length ? true : false; $('#resultadonorma').toggle(toggle); $("#sinresultadosbuscarnormas").toggle(!toggle); or rid of conditional, , pass .length directly. idea coerce boolean though. $('#resultadonorma').toggle

jquery - MVC4 & IClientValidatable - Automatic AJAX calls to server side validation -

i'm looking implement custom client side validation in mvc4. have working standard attributes, such in model public class uploadedfiles { [stringlength(255, errormessage = "path long.")] [required(errormessage = "path cannot empty.")] [validpath] public string sourcedirectory { get; set; } } so stringlength , required both automatically translated jquery client side validation. "valid path" works server side. validation required server side server can validate if path valid, couldn't client side. the server side code looks like public class validpathattribute : validationattribute, iclientvalidatable { public string sourcedirectory; protected override validationresult isvalid(object value, validationcontext validationcontext) { string path = value.tostring(); string message = string.empty; var filesystemsupport = new filesystemsupport(settings, new wrappedfilesystem(new filesystem())