Posts

Showing posts from May, 2013

excel - Compare two list of values A and B, if there any value equal to B in the list A -

how compare 2 list of values a , b , if there value in b equals value in list a , write row number of column a in front of value in column b using excel/macro/vba. use vba: sub test() dim ws worksheet dim long, j long, k long dim strvalueb string, strvaluea string set ws = activesheet = + 1: j = 0 strvalueb = ws.cells(i, 2).value '2 -> column b if (strvalueb = "") exit j = j + 1 strvaluea = ws.cells(j, 1).value '1 -> column if (strvaluea = "") k = 0 exit elseif (strvalueb = strvaluea) k = j exit end if loop if (k > 0) ws.cells(i, 3).value = k '3-> column c end if loop end sub

javascript - Bundling a durandal single page application into one HTML page -

i have strange requirement need bundle in 1 html page durandal single page application. can make away dependencies defining them name: define("models.mapper", [], function() { }); however, seems not possible bundle durandal stuff defines modules without names: define(['require', 'jquery'], function(require, $) { // .... } this fine when want make work path references seems make hard inline html. ideas or suggestions on this? require.js requires have 1 anonymous define per file can use file path+name relative base path give name. if have durandal source inline on page you'll need update define lines give them appropriate names (i.e. define('durnadal/system', ......). an easier approach may build source code in structure of normal durandal project , use requirejs optimizer ( http://requirejs.org/docs/optimization.html ) build them single js file - if configure correctly without minification can paste file contents script t

constructor - Java Object Construction and Enclosing Method -

i've been looking book or document better explain what's going on here: system.out.println(">constructor>" + new object().getclass().getenclosingconstructor()); output:: >constructor >null however, system.out.println(">constructor>" + new object(){/**/}.getclass().getenclosingconstructor().tostring()); output:: >constructor >packageinformation.classconstructor() i know has ... ... static initialization sequence. my question is: how work , can read more this? thanks. you can read in javadoc class.getenclosingconstructor : if class object represents local or anonymous class within constructor, returns constructor object representing enclosing constructor of underlying class. returns null otherwise. since object isn't anonymus class, null returned in first case. new object(){/**/} creates instance of anonymus class extending object , why non- null value returned, if new object(){/**/}.ge

deployment - When deploying to maven the upload hangs forever -

i'm deploying library remote maven repository. when run mvn -u deploy or mvn deploy looks fine apart when uploading artifact. hangs in there forever . just this: uploading: http://maven.mycompany.com/server-product/com/mycompany/product/server/common/common/3.0/common-3.0.jar 213/213 kb i've read here , here , here , here related downloading, not uploading. can download fine, uploading artifact hangs. links related bug on previous maven versions, i'm using apache maven 3.3.3 the remote server running artifactory 3.6.0 (rev. 30178) anyone know problem? doing wrong? here settings.xml file: <?xml version="1.0" encoding="utf-8"?> <settings xsi:schemalocation="http://maven.apache.org/settings/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd" xmlns="http://maven.apache.org/settings/1.1.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <servers> <server>

c# - Download and save image into Application.persistentDataPath hangs the app -

i wrote game can download images server , store them inside application.persistentdatapath. my problem when saving few images scene hangs , when done saving, executes rest of code. how can solve issue? saving image device local storage: if (file.exists (application.persistentdatapath + "/layoutimages/")) { debug.log (imagespathprefix + " exists."); return; } file.writeallbytes (application.persistentdatapath + "/layoutimages/abc.jpg", image); you can create thread performing operation on side. here example : class filedownloader { struct parameterobject { public string url; public string savepath; } static void downloadfunction(object data) { parameterobject obj = (parameterobject)data; if (file.exists(obj.savepath)) return; using (webclient client = new webclient()) { client.downloadfile(obj.url, obj.savepath)

Integrating a ruby program w/ GUI in a Rails application -

this hard me explain properly, sorry in advance if question unclear! new both ruby , rails framework i'm working on rails application in want able run self-made program gui. the question whether or not possible "have" program running otherwise in page in rails application, , if so, how? yes, can (if app can run in multiple instances). whatever gui stuff on server won't of use webclients, it'll needlessly strain resources little bit (or lot--depending graphical operations does). web apps, you're better off using non-gui programs or better yet, libraries can use inside ruby without needing spawn separate processes. launching app incurs little bit of overhead, multiplies number of web clients have.

magento - How to change the invoice price manually? is it possible or not? -

magento generated invoice order. client asking change invoice price in manually possible or not? try following, module's config.xml <sales_order_invoice_save_after> <observers> <sales_order_invoice_save_after> <class>your_module/observer</class> <method>invoicesaveafter</method> </sales_order_invoice_save_after> </observers> </sales_order_invoice_save_after> your observer.php public function invoicesaveafter(varien_event_observer $observer) { $invoice = $observer->getevent()->getinvoice(); if ($invoice->getbasedonateamount()) { $order = $invoice->getorder(); //do stuff here } return $this; } more information

java - How to convert a String ( ArrayList of HashMap ) to ArrayList -

here code create hashmap , arraylist . hashmap wbsmap = new hashmap(); arraylist<hashmap<?, string>> list = new arraylist(); arraylist<hashmap<?, string>> listchildnew = new arraylist(); now have stored values correspondent keys wbsmap.put("component_"+i, bom.getstring("component")); wbsmap.put("comp_qty_"+i, bom.getstring("comp_qty").replaceall("\\s+","")); wbsmap.put("comp_unit_"+i, bom.getstring("comp_unit")); wbsmap.put("ns_left_"+i,string.valueof(ns_left)); listchildnew=generatebomstructurelatest(wbsmap,bom.getstring("component"),ns_right,string.valueof(i)); if(listchildnew.size() >0){ wbsmap.put("ns_child_"+i,listchildnew); } wbsmap.put("ns_right_"+i,string.valueof(ns_left)); list.add(wbsmap); now key ns_child_ consist of arraylist of hashmap listchildnew . stored in wbsmap hashmap string object. not

Too slow to connect to Cassandra cluster with datastax java driver 2.1.4 -

i have set cassandra cluster 2 nodes on 2 servers identical hardware configuration in same internal network recently. works cqlsh, seems perfect. followed code example in datastax's website write java code work cluster , problems comes. program works, connects cluster , writes , reads data it. however, connection way slow! deployed code in same machine 1 of cluster node resides , takes on 5 seconds connect. more precisely, it's line session = cluster.connect() takes of time. i tried setup cassandra cluster 1 node in same network, similar hardware configuration. takes around 1 second connect. think it's missed configurations when writing code. spend quite time searching answer not any. given 5 seconds connection time, hard me consider use replacement current database. in addition, ping time among these machines within 1ms, don't think it's network's problem. using cqlsh connect cluster fast too. the cassandra version 2.1.4 , maven dependency datastax

laravel - I am so new to Lavarel/PHP and I cant find the error -

i have crm system designed lavarel. trying selecting contacts, clicking on save button (i have save before exporting csv). however after when click on download button contacts not export csv , receive error: symfony \ component \ debug \ exception \ fatalerrorexception (e_error) call undefined method symfony\component\httpfoundation\binaryfileresponse::withcookie() open: /home/mirjamro/public_html/mr-admin.com/app/filters.php auth::logout(); return redirect::to(url::route('adminshowlogin')); } if(auth::check()){ $ckname=auth::getrecallername(); //get name of cookie, remember me expiration time stored $ckval=cookie::get($ckname); //get value of cookie return $response->withcookie(cookie::make($ckname,$ckval,1440)); //change expiration time } }); i cant download server. change code from: return $response->withcookie(cookie::make($ckname,$ckval,1440)); to: return response::make($response)->withcookie(cookie::make($ckname,$ck

javascript - Logging in and getting the data from the cross domain for calculations using Java Script -

i have searched regarding question , haven't found satisfying answer. may related doesn't have satisfying answer. how log in remote website , read data logged in page using javascript/jquery/ajax? firstly want develop web app college academics website. can see website here now, want create web app takes in register number, username , password (date of birth, phone number) input , send academics site , gets data site , returns web app calculations , display data. webapp should written in javascript , frameworks , of course html , css. should noted data in website of academics gets data in iframe. to brief, 1) go website 2) capatcha 3) go website 4) fill in username, passwords, captcha etc. 5) login 6) data 7) return values calculations. i appreciate if cite code examples, tutorials.

mongodb - mongo 3 duplicates on unique index - dropDups -

in documentation mongodb says: "changed in version 3.0: dropdups option no longer available." is there can (other downgrading) if want create unique index , destroy duplicate entries? please keep in mind receive 300 inserts per second can't delete duplicates , hope none come in time i'm done indexing. yes dropdupes deprecated since version 2.7.5 because not possible predict correctly document deleted in process. typically, have 2 options : use new collection : create new collection, create unique index on new collection, run batch copy documents old collection new 1 , make sure ignore duplicated key error during process. deal in own collection manually : make sure won't insert more duplicated documents in code, run batch on collection delete duplicates (and make sure keep 1 if not identical), then add unique index. for particular case, recommend first option trick : create new collection unique index, update code insert

c# - Specific ListBox value always selected -

i using listboxfor user can select multiple values ,a user wants should 1 value selected ex: listbox contains: id category 1 2 b 3 c 4 d 5 general here general category should selected , user should not able change selected value listbox. @html.listboxfor(model => model.selectedcategory, viewbag.listcategories multiselectlist, new { }) i using asp.net mvc 5 actually can rare scenario,one approach can use use jquery.if has solution in mvc helpers plz tell me other wise using jquery. try using jquery $(document).ready(function () { $('#selectedcategory').find('option[value="5"]').attr('selected','selected'); }); this works fine.

javascript - How to used html tag in json data? -

hi m using 1 json file in angualr js { "rohit":[ {"p":"i m john <strong> smith</strong> "}, {"p":" hi m rohit<span> azad</span> ."}, {"p" : "hi m rakesh singh "} ] } if call json data called show result . m john <strong> smith</strong> hi m rohit<span> azad</span> . hi m rakesh singh why show html tag , how solve want used html tag in json format html tag . the strings strings. interprets them html depends entirely on you're doing them. if use them html, html used; if use them text, won't be. since you've said you're using angular, here's example of ng-bind-html (interprets html; requires $sanitize service) vs. ng-bind (doesn't): // json (i'm assuming comes somewhere, otherwise // literal in code, not json) var json = '{' + '"rohit":[' + '{&quo

java - How synchronize in JNI? -

i'm trying develop android app uses accelerometer of device. want read first 5 events of accelerometer , save accelerations, , after stuff on that. my jni code is: asensoreventqueue* sensoreventqueue; asensormanager* sensormanager; vector<double> xx, yy, zz; static int get_sensor_events(int fd, int events, void* data) { asensorevent event; while (asensoreventqueue_getevents(sensoreventqueue, &event, 1) > 0) { //logi("accelerometer x = %f y = %f z=%f t=%lld", event.acceleration.x, event.acceleration.y, event.acceleration.z, event.timestamp); xx.push_back(event.acceleration.x); yy.push_back(event.acceleration.y); zz.push_back(event.acceleration.z); } if (xx.size() > 5) { asensormanager_destroyeventqueue(sensormanager, sensoreventqueue); return 0; } return 1; } extern "c" { jniexport jint jnicall java_com_example_sensor_mainactivity_sensor(jnienv *env,jclass clas,job

sql server - Combine row after used group by in SQL -

Image
i have created query select count(currentslideid) attempts, currentslideid, userlessonprogressid, ishint useranswers (userid = 169494) , userlessonprogressid=218629 group userlessonprogressid, currentslideid, ishint order userlessonprogressid, currentslideid and output of above query looks like now want combine last 2 row in 1 row attempts=2 currentslideid=19328 userlessonprogressid=218629 , ishint=1 keep query, max(ishint) , remove column group by : select count(*) attempts, currentslideid, userlessonprogressid, max(ishint) useranswers userid = 169494 , userlessonprogressid = 218629 group currentslideid, userlessonprogressid order currentslideid, userlessonprogressid

java - Multi-user test approach for wicket application -

we developing wicket application users can log in , perform searches on lucene index. can modify own, small index. we have great test coverage single-user scenarios. however, application intended run on server , have multiple, concurrent users, able set-up test covers scenario (e.g. 1 application, 10 concurrent users). i have experience using jmeter , prefer wickettester -style approach if possible. does have expercience setting such test? or pointers? we use wicket concurrent users not main focus (no end-users). need check cookie-behaviour, session-management etc. , use sahi exists open source imo , demo. use pro version in other projects. perspective easy learn , handle. _navigateto("http://myapp/login.html"); // login first user ... // launch new browser instance var $instanceid = _launchnewbrowser("http://myapp/login.html"); _wait(5000); // wait , select new browser instance using instanceid _selectbrowser($instanceid); // log in second us

javascript - How to create a batch file to add pull info from a txt doc -

currently looking tot speed manual task. i have several web urls in .txt file i'm hoping add line of code each url. the code is: <tr> <td><a href=""></a></td> </tr> basically automate batch file add url in both between commas"" , <> give output file such as: <tr> <td><a href="http://www.test1.com/">http://www.test1.com/</a></td> </tr> read file. explode array loop foreach through array string replace stub found values. <?php $stub = '<tr><td><a href="%__link__%">%__link__%</a><td></tr>'; $links = []; $filedata = file_get_contents("filename.txt"); $lines = explode( "\n", $filedata ); // \n unix, \r windows. foreach( $lines $line ) { $links[] = str_replace( "%__link__%", $line, $stub ); } $newfile = join("\n", $links); file_put_cont

c# - Get the index of Array List -

i have question array list in c# i have array following elements: - lqi request - 0123456 - lqi request - 456789 - lqi request - 6789 ..... now want is, find strings lqi request , , string next it, that's i've tried far:(index global variable) if(mystring.contains("lqi")) { index= stored_data.indexof(mystring); } messagebox.show(index.tostring()); messagebox.show(stored_data[index+1].tostring()); verytime run code, index stays same. should be: 0,2,4 please help list<string> data = new list<string> { "- lqi request", "- 0123456", "- lqi request", "- 456789", "- lqi request", "- 6789" }; var result = data.select((x, i) => // x element, index { if (x.contains("lqi")) if(i + 1 < data.count) // index inside bounds o

kendo ui data grid - firebase -

i'm using kendo ui data grid firebase (rest json response). structure can contain multiple objects. however, these objects not in standard array format. see json file below: { "users": { "contactdetails": { "email": "johnlittle@email.com" }, "firstname": "john", "id": 1, "surname": "little" } } i able read firstname , surname onto grids column cannot email object. this schema definition: schema: { model: { fields: { id: {type: "number"}, firstname: {type: "string"}, surname: {type: "string"}, email: {type: "string"} } } } as far know, u can not specify nested object schema model definition. 1 way can use column template email column. columns: [ { field: "firstname", titl

ruby on rails - how to dynamic create a mongoid class? -

i want dynamic create mongoid model , search. at first, create file named daily_pageview.rb class dailypageview include mongoid::document include mongoid::timestamps field :path, type: string end then, run these commands in $ rails c dailypageview.create!(path: '/') dailypageview.where(:path => '/').count correctly, got result: 1. then try refactor code, delete daily_pageview.rb also, run these commends in rails c c = class.new include mongoid::document include mongoid::timestamps field :path, type: string end object.const_set 'dailypageview', c dailypageview.where(:path => '/').count but, time, got 0. why? i'm not sure related issue mongoid failing dynamic collections or problem.

Nested query with spring data jpa and eclipselink -

i working spring ,spring data jpa ,and eclipselink using repository define queries , have nested query , working in mysql directly not in repository @query("select don donnee don don.rownumber in " + "(select distinct(do.rownumber) donnee do" + " char_length(do.valeur) > 14 , substring(do.valeur, 7, 4) = ?1 )" ) public list<donnee> donnespardate(string date); i error : [101, 164] expression not valid conditional expression. any please try entity manager string query = "select don donnee don don.rownumber in " + "(select distinct(do.rownumber) donnee do" + " char_length(do.valeur) > 14 , substring(do.valeur, 7, 4) = ?1 )"; entitymanager em = this.emf.createentitymanager(); query result = em.createquery(query); list results = result.getresultlist(); and autowire entitymanager : @autowired private entitymanagerfactory emf;

css - WordPress : Stretched Background Image in IE8 -

i badly need help. background image overly stretched in ie8. i used wordpress's functionality on background image in edit appearance. chrome, firefox , other ie versions, background appearing okay. when checked in ie8, overly stretched. instead of seeing garden background, saw tip of tree part of garden. i wondering on can tweak code or can make fit nicely how other browsers show it. i tried : background-size:cover background-size:1024px 100%; thanks! use https://github.com/louisremi/background-size-polyfill download backgroundsize.min.htc .selector { background-size: cover; -ms-behavior: url(css/backgroundsize.min.htc); behavior: url(css/backgroundsize.min.htc); }

difference between methods and public_methods in Ruby -

i curious know difference between methods , public_methods in ruby? rubymonk analysis section the methods method on object allows tap list of public methods available on object , ancestors. equivalent using public_methods. return instance methods , class methods belonging object , ones accessible on object's ancestors. if want ignore ancestors , restrict listing receiver, can pass in false public_methods(false). for curiosity, call methods(false) return different output public_methods(false) my sample code , output: p string.methods.size p string.public_methods.size p string.methods(false).size p string.public_methods(false).size p string.public_methods(false) - string.methods(false) stdout: 235 235 3 19 [:json_create, :yaml_tag, :const_missing, :allocate, :new, :superclass, :cattr_reader, :cattr_writer, :cattr_accessor, :class_attribute, :superclass_delegating_accessor, :descendants, :subclasses, :duplicable?, :json_creatable?, :to_yaml] f

html5 - How do I stop video autoplay in Firefox 37? -

i need controls, don't want video autoplay. code below, doesn't work. <video id="video1" poster="assets/img/bg-header.jpg" autoplay="false" controls autostart="false"> thanks, sabin html5 videos don't autoplay default. remove autoplay="false" . js bin

java - Retrieve JSON attachment and its attributes -

background: have stored json document (id: 160d7237a5fd00501f4654a6c8b42f38) in cloudantdb , put attachment against document. can see below json structure has 1 attachment (i.e. rajiv.jpg) associated it. i want retrieve json attachment object (jpeg). can me how can transform below json structure java pojo class , retrieve attachment using same ? definition of pojo class. in advance. i want show jpeg file in ui screen via webservice retrive jpeg cloudantdb , pass ui. { "_id": "160d7237a5fd00501f4654a6c8b42f38", "_rev": "3-695e52989827cd9e203ff9f506eaf7df", "customer_id": "2", "_attachments": { "rajiv.jpg": { "content_type": "image/jpeg", "revpos": 2, "digest": "md5-/78izjpuu7nkbvbsxbf2xg==", "length": 39712, "stub": true } } } the json you've got doesn't include ac

Is it possible to refresh a Access database automatically at a fixed interval? -

i'm making database comprised of 2 basic forms. form used input data, , form b split form shows records filled in using form a. problem right is not updating data automatically. have manually refresh pressing refresh button @ top of page. have tried 'click microsoft office button office button image, , click access options. in left pane of access options dialog box, click advanced. in right pane, under advanced, specify value refresh interval (sec)' not helping me. is there other way can update automatically?

regex - php preg_match with multiple patterns -

i have 2 patterns , want search them in string. this: $pattern = '/,3$/' $pattern = '/^1,/'; actually want find strings start 1, or end ,3 my strings in format: a => 1,2 b => 31,2 c => 4,3 for example , c matches! how can use preg_match check patterns? tanks helps. try way preg_match("/^1,|,3$/", $string)

python - AttributeError: 'list' object has no attribute 'readline'? -

def read_grade(gradefile): ''' (file,'r') ---> list of floats in case return grade file, fution meant use given grade file''' line = gradefile.readline() print(line) while line != '\n': line = gradefile.readline() print(line) grades = [] line = gradefile.readline() print(line) while line != '': grade = line[line.rfind(' ') + 1:] grades.append(float(grade)) line = gradefile.readline() print(line) return grades def range_grade(grades): ''' (list of int) ---> list of int return list each index indicates how many grades in these ranges ''' grade_range = [0] *11 grade in grades: which_range = int(grade // 10) grade_range[which_range] = grade_range[which_range] + 1 return grade_range #main body starts file_path = 'c:/users/user_name/desktop/python/

css - Rails - Difference between @import and *= require? -

so i've got relatively simple rails app, , wanted add material design styling through bootstrap. i've added following gems gemfile: gem 'bootstrap-sass' gem 'bootstrap-material-design' now both work, question why seem have add them app in different ways. vanilla boostrap import view specific (i think that's right term) scss file normal. @import "bootstrap-sprockets"; @import "bootstrap"; but material design gem have 'require' root application.css file instead *= require bootstrap-material-design why difference, , require syntax doing? the include , require methods different things. the require method include in other programming languages: run file. tracks you've required in past , won't require same file twice. run file without added functionality, can use load method. the include method takes methods module , includes them current module. language-level thing opposed f

lua - Using luac file on Nginx -

i have been experimenting using lua in nginx - quite neat little capability can use effectively. however, 1 of concerns relates ip protection thought use online tool compile my, tested, lua script. tried https://luac.mtasa.com/ . uploaded file server, changed /etc/nginx/sites-available/default file use *luac** instead of orginal lua , reloaded nginx. however, when attempt browse resource being serviced lua(c) error log message *70 failed load external lua file... : bad byte code header . how should interpreted? options are that particular online compiler not generating valid luac. the nginx/lua combo not understand particular luac. i should mention using nginx 1.6.2 on ubuntu 14.10 (64 bit). installed lua enabled nginix via apt-get install nginx-extras . i newbie here. i'd appreciate help. compiling lua nginx has specifics. see details on official lua module page http://wiki.nginx.org/httpluamodule#lua.2fluajit_bytecode_support

jpa - SQL Group by one column and decide which column to choose -

let's have data : | id | code | name | number | ----------------------------------------------- | 1 | 20 | | 10 | | 2 | 20 | b | 20 | | 3 | 10 | c | 30 | | 4 | 10 | d | 80 | i group rows code value, real rows (not aggregate function). i know select * table group code won't work because database don't know row return code same. so question how tell database select (for example) lower number column in case | id | code | name | number | ----------------------------------------------- | 1 | 20 | | 10 | | 3 | 10 | c | 30 | p.s. i know how partition allowed in oracle databases , can't created in jpa criteria builder (what ultimate goal). why don't use code this? select id, code, name, number ( se

c++ - How can I link cpufeatures lib for a native android library? -

i'm trying link android's cpu_features native library. i'm using android's gcc compiler directly cross compiler. ( not ndk-build ). i've included header ( $ndk_path/sources/android/cpufeatures/cpu-features.h ), don't see prebuilt libcpufeatures.a file anywhere under ndk folder. how can build library? or can found can link properly? you can include source file cpu-features.c in project, or build manually gcc: arm-linux-androideabi-gcc -c cpu-features.c -o cpu-features.o --sysroot=$sysroot arm-linux-androideabi-ar rcs libcpufeatures.a cpu-features.o it shouldn't require special compiler flags or defines, when linking it, may need add -ldl since uses dlopen .

unity3d - Cannot publish my Android Unity app: APK in debug mode -

i'm trying publish app created unity 4 appstore, it's still blocking me uploading saying app in debug mode. i've checked checkbox development build under build settings , have signed through publish settings under player settings. around internet says change system variables jdk , did well. the checkbox development build under build settings should not checked when making release build.

amazon web services - How to log EC2 operations on AWS? -

we operating large amount of instances , elb on aws. experienced strange behaviors. don't know whether our boto scripts responsible or aws has malfunction. might human mistake. we not able know did on ec2 instances, that's issue. this implies : ec2 instance creation/termination ec2 instance start/stop/reboot register/deregister ec2 instance elb is there way start logging ec2 operations in aws ? alternatively, ec2 events sent on sqs or sns ? can listen events rather reading logs ? the cloudtrail service place start. here link documentation: logging amazon ec2 api calls using aws cloudtrail

Coffeescript and Rendering SVG in an If condition -

i'm trying create battery checker application interprets coffeescript. i'm new coffeescript , googling didn't help. below code tried: if charge <= 100 render: ->""" <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewbox="0 0 24 24"> <path d="m0 0h24v24h-24z" fill="none"/> <path d="m7 17v3.67c0 .73.6 1.33 1.33 1.33h7.33c.74 0 1.34-.6 1.34-1.33v-3.67h-10z"/> <path fill-opacity=".3" d="m17 5.33c0-.73-.6-1.33-1.33-1.33h-1.67v-2h-4v2h-1.67c-.73 0-1.33.6-1.33 1.33v11.67h10v-11.67z"/> </svg> """ charge filled batterypercentage. if try render svg outside of if condition works, sadly not if. thanks in advance! here code compile in coffescript.org 's console : if (charge <= 100) { ({ render: function() { return "<svg xmlns=\"http:/

Inheritance concept in Java -

this question has answer here: a base class pointer can point derived class object. why vice-versa not true? 9 answers this rather basic question. can't understand concept of inheritance. suppose have 2 classes, , b both have test() method returned 1 , 2 respectively, , b inherited class. in main method declare instance such; a a1 = new b(); and call method a1.test() , return 2 . concept of polymorphism. when have method test2() in subclass, can't call method using same instance declaration above. why happen? i can't call method using same instance declaration above. why happen? because type of variable a , , class a not have method test2() . java compiler looks @ type of variable check if can call method, not @ actual object (which in case b ). this easier understand if use more concrete , meaningful names classes, instead of

regex - java remove certain special characters -

sorry, might duplicated post i'm not understand how regex works. had referred others post yet still confuse. trying remove special characters when import file excel. appreciated. below example data excel: string test = "hello~i!am@b#c(d)an`d|opq/hmm\yes^123,.&*$" test = test.replaceall("[^-a-za-z0-9", " "); // not completed regex i have no idea how write full regex replace these characters ` ^ \ / | * empty string you don't need put ^ @ start of char class, since it's special class in regex called negated character class. string.replaceall("[/\\\\|*^`]", ""); in java regex, need use 4 backslashes match literal backslash character. ideone if want remove [ , ] also, need include \\[ , \\] inside character class. string.replaceall("[/\\\\|*^`\\[\\]]", "");

machine learning - RBM for collaborative filtering -

my algorithm rbm collaborative filtering not converge... idea of think rbm for collaborative filtering initial w , b , c , random @ [0,1] for user clamp data -> visible (softmax) hidden = sigmoid(b+w*v) run gibbs on hidden -> hidden_gibbs positive = hidden*visible hidden -> reconstruct -> reconstruct_visible run gibbs on reconstruct_visible -> reconstruct_visible_gibbs negative = hidden_gibbs*reconstruct_visible_gibbs end for update w = w + (positive-negative)/number_user b = b + (visible - reconstruct_visible_gibbs)/number_user c = c + (hidden - hidden_gibbs)/number_user i have seen lots of paper or lecture, , have no idea wrong this not easy problem! description of learning procedure looks fine. but, there's lot of room mistakes description actual code. also, cf, "vanilla" rbm won't work. how did implemented visible "softmax" units? did train rbm "single-user" dataset, recommended in or

c# - Difference between WCF REST VS WEB API -

i think wcf uses soap protocol. webapi uses rest architecture. wcf supports both soap , rest. what difference between wcf rest , webapi? why there general preference webapi? wcf protocol agnostic. can run on http, tcpip, net pipes, etc. web api more suited building rest apis. however, question broad answered here. read more both technologies , come more specific questions.

.net - Retrieve/Upload artifacts from/to maven repository using c# -

i need access maven repository(upload , retrieve artifacts) c# code? available c# libraries done. i think need c# equivalent answers posted here retrieving maven artifact repository using maven java api google/stackoverflow results in java libraries same

.net - Convert string to current culture in c# -

i have instance of "windows firewall" windows service, using servicecontroller service = new servicecontroller("windows firewall"); this works fine in en-us culture, when try in windows portuguese(brazil) pt-pt culture, throws exception service not found. yes, in portuguese there no "windows firewall" instead "firewall windows", if change code below servicecontroller service = new servicecontroller("firewall windows"); it work in pt-pt culture. is there generic way, "windows firewall" instance irrespective of culture? there's no system provided function perform such conversion. you'd have create list/dictionary of possible values in own code, , value.

Uploading files with non-English characters in name to Blobstore in App Engine Java -

i have encountered problem java runtime apparently resolved python - http://code.google.com/p/googleappengine/issues/detail?id=2749 when filename contains non-english characters, getting either blobinfo.getfilename() , fileinfo.getfilename() returns base64-like string (but it's not base64 far figure) starting =?utf-8? this happens in production. in development server string can convert utf-8 encoding. i saw python users able overcome before official fix. tried add accept-charset="utf-8" upload form, didn't seem matter. there workaround this? thought using non-standard way send filename (ie. encode on client , decode on server) prefer cleaner solution.

javascript - Defining functions on scope from a remote controller on the same server -

i working on project, framework renders data defined in layouts (screens) in format of jsons. example, write , { name : "first name", row : "1" , type: "text box" } it render text box label "first name". i have central service root scope of entire framwork. requirement - user/developer write own controller , html on same server outside of framework code. to controller pass $scope , define new methods , provide html need render. this html use functions on scope can either f/w or controller. i have explored - angular ajax - http://tutorials.jenkov.com/angularjs/ajax.html angoose - https://github.com/tjworks/angoose i not sure if design correct. need in different way ? or there way achieve have designed. thanks in advance. if 1 stumbles on question , how solved our application build structure maven related. placed these custom services , html on same server , wrote automation program include th

sql - mysql select rows on comma seperated value in column -

i've product table 3 columns: product_id product_name product_keywords and contains values that: product_id | product_name | product_keywords 1                |computer         |pc, computer, laptop, personal computer, desktop computer ------------------------------------------------------------------------------------------------------------------' 2               |mobile                |smart phone, phone, nokia, sony --------------------------------------------------------------------------------------------------------------------' now need sql query if customer search pc or personal computer return product_name = computer product_id = 1 , on. although first instinct re-design schema have keywords table unique values , mapping table between products , keywords, mysql offers elegant way query comma-delimited strings find_in_set function: select product_id, product_name products find_in_set ('pc', keywords) > 0

c# - Role-Based Access Control to a User -

i have application mvc 4.0 using entity framework. i have user table, role table, type table. role can out of two: administrator , user type can out of 8: none, admin, asst.admin, ...... so want allow different pages accessed based on type below: 1) types defined: none con acc rec st fr admin asad ( <-- types) ---------------------------------------------------------- 1.a) update client: none none none none edit view full full ( <-- roles) 1.b) new client: none none none view view edit full full ( <-- roles) so how achieved ? you can achieve authorizeattribute: [attributeusage(attributetargets.class | attributetargets.method)] public sealed class actionpermissionattribute : authorizeattribute { public override void onauthorization(authorizationcontext filtercontext) { var controllername = filtercontext.actiondescriptor.controllerdescriptor.controller

Navigate on AngularJS + Kendo UI Mobile -

i new angularjs + kendo ui mobile. how can navigate page angular controller? i tried code: var app = $("#app").data("kendomobileapplication"); app.navigate("#menucategories"); but error: "error: [$rootscope:inprog] $digest in progress" and ngroute see: "the mobile application instantiates , maintains own routing mechanism based on router component, automatically matches , instantiates views when navigating. ... note angularjs routing mechanisms not supported" thanks in advance sorry bad english .. naomi. telerik team answer me, solution is: kendo.mobile.application.navigate(viewname) (without '#' sign)

Omitting function arguments in PHP -

i have function saves every user log looks <?php function create_log($action=null, $outcome, $message) { require 'dbc.php'; include 'get_ip.php'; $ip = get_ip_address(); $datetime = date('m-d-y h:i:s a', time()); $query = "insert tbllogs (logorigin, logaction, loguser, logdate, logoutcome, logmessage) values (:origin, :action, :user, :dt, :outcome, :message)"; $stmt = $dbc->prepare($query); $stmt->bindparam(':origin', $ip); $stmt->bindparam(':action', $action); $stmt->bindparam(':user', $_session['id']); $stmt->bindparam(':dt', $datetime); $stmt->bindparam(':outcome', $outcome); $stmt->bindparam(':message', $message); $stmt->execute(); } and when call doing this: create_log('log in', 'failed', ''); my problem is, $message parameter used whenever need only. should call create_log

python - How can I tell if a list or function approaches infinite? -

i trying make function returns true if list/function goes infinite. there simple way accomplish this? http://en.wikipedia.org/wiki/halting_problem this paradoxical question. asking if can potentially solve halting problem in python. if list or function goes infinite means never returns, way know. if function never returns can never determine whether or not never returning. if right, never find out. otherwise it'll return. that said, if looking values closing bound. create cutoff point value acceptably close bound. once you've hit value assuming you've reached fair distance.

nlp - How to iterate through the synset list generated from wordnet using python 3.4.2 -

i using wordnet find synonyms particular word shown below synonyms = wn.synsets('good','a') where wn wordnet. returns list of synsets synset('good.a.01') synset('full.s.06') synset('good.a.03') synset('estimable.s.02') synset('beneficial.s.01') etc... how iterate through each synset , name , pos tag of each synset? you can name , pos tag of each synset this: from nltk.corpus import wordnet wn synonyms = wn.synsets('good','a') synset in synonyms: print(synset.name()) print(synset.pos()) the name combination of word, pos , sense, such 'full.s.06'. if want word, can split on dot '.' , take first element: print(synset.name().split('.')[0]

c# - .NET Word add-in does not run on first execution -

i writing add-in word. add-in work correctly , has no significant issues. problem have when fix bug , give new build users, first time run add-in behaves previous version of add-in before bug fixed. subsequent executions exhibit corrected behavior. my users using visual studio installer , add-in not gac'd. have verified users uninstalling old add-in before installing new one. does know might responsible execution lag?

C++ Awesomium setting up listener problems -

i have odd error can't figure out. using awesomium(latest ver) c++ , want create listener connect js running program. i have included /include , /lib folders correctly, including necessary headers #include <awesomium/webcore.h> #include <awesomium/stlhelpers.h> #include <awesomium/jsobject.h> #include <awesomium/webviewlistener.h> however, visual studio keeps saying there's wrong code class browserlistener : public awesomium::webviewlistener { public: virtual void oncallback(awesomium::webview* caller, const std::wstring& objectname, const std::wstring& callbackname, const awesomium::jsarray& args) { // check starts here if (objectname == l"app" && callbackname == l"settings") { std::cout << "callback called " << args.size() << " args\n"; } } }; it underlines awesomium::webviewl

javascript - Getting multiple checked checkbox labels into an array -

i hoping checked checkboxes form array. here did. $("div.category-panel input:checked").next ('label').text(); gets checked checkboxes shows them 1 text. example, checkbox1 , checkbox2 , checkbox3 (if checked) show checkbox1checkbox2checkbox3 . i hoping these different checkboxes in array can use them. $('.submit').on("click", function(e) { //got checked checkboxes 'children'. children = $("div.category-panel input:checked").next ('label').text(); //put in array. var array = []; var = 0; $.each(children, function(key, value){ array.push($(this).text()); }); //show array. (var = 0; < array.length; i++) { console.log(array[i]); } }); html, in case is:- <div class="category-panel"> <input type="checkbox" name="name_service2" id="tid-46" value="46" checked="

android - How to restart camera efficiently in a fragment - Barcode Scanner -

i have 2 fragments in app , trying implement barcode scanner using zxingscanner library in 1 of them. implementation works fine. question related bad design. when user scans valid code dialog box appears saying code valid. when dismiss dialog (by pressing ok) barcode scanner stops. address issue have following: buttonconfirm.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { popupview.dismiss(); restartcamera(); } }); public void restartcamera(){ mscannerview.stopcamera(); //mscannerview = new zxingscannerview(getactivity()); mscannerview.startcamera(); } the problem approach when switch fragments camera still running behind. how can stop camera when switch first fragment , turn on , address issue. (i using viewpager implement fragments) ok found solution. override setmenuvisibility method in camera fragment. if fragm

shell - how to properly use comparison operators within an if-then statement -

what best way perform check/test output comes query called within shell script? for example, have variable performs query: export chk=`psql -h localhost -p 5432 -u foo foobar --tuples-only -c "select 1 result pg_database datname='foo_bar_1234'";` it return either 1 =exist or empty string=not exist. i tried code, doesn't work expected keeps going db not exist everytime if value empty string. tried "1" still same results. if [ "$chck" = 1 ]; echo "db exists." exit 1 else echo "db not exist." fi how correct and/or better way check this? from comments sounds output of 1 may surrounded whitespace, 1 solution trim leading , trailing whitespace first, using read : #!/usr/bin/env bash export chck=$(psql -h localhost -p 5432 -u foo foobar --tuples-only -c "select 1 result pg_database datname='foo_bar_1234'") # remove leading , trailing whitespace value.

hadoop - Parse custom datetime in Pig -

i have following string "2014-12-15 18:20:48" when parsed datetime: a = load 'input.txt' (mydate:chararray); b = foreach generate todate(mydate) datetime; i error: "2014-12-15 18:20:48" malformed @ " 18:20:48" alternatively, when specify format todate(mydate, 'yyyy-mm-dd hh:mm:ss'); datetime converted "2014-12-15t18:20:48.000z" instead of "2014-12-15 18:20:48" . how can resolve give me "2014-12-15 18:20:48" type datetime? if passing string todate function, string should of iosstring format(ref [1]). todate(iosstring) in first case, input string not of iosstring format (t separator missing, signifies beginning of time element). if input string of iosstring format(ref [1]) work. in second case, calling overloaded method of todate : todate(userstring, format) the return type of todate method datetime object. if getting date in string , need in other format further processsing hav

Grails 3: what is replacement for eventCreateWarStart in _Events.groovy -

i migrating plugin grails 2.4 grails 3. facing following issue. i tried use eventcreatewarstart in _events.groovy . used compile widgetset in our plugin's _events.groovy file . seems approach not allowed in grails 3. i went through specification , have not found replacement. can help? in general cannot use concepts old build 2.x build system , have instead write gradle plugin. for example requirements sound similar asset pipeline plugin modifiers gradle's war task include compiled static assets (see https://github.com/bertramdev/asset-pipeline-core/blob/master/asset-pipeline-gradle/src/main/groovy/asset/pipeline/gradle/assetpipelineplugin.groovy#l91 )

sqlite - R Shiny - unable to find an inherited method for function ‘dbGetQuery’ -

why keep getting error below, unable find inherited method function ‘dbgetquery’ signature ‘"sqliteconnection", "data.frame"’ for, # fetch site names. sitequery <- dbgetquery(db, "select nid, title, description nodes datatype = 'speck' , visible = '1' , nid = 'site' ") # match pattern , replace it. sitequery <- sub("site", as.character(site1), sitequery) # store result in data. sitedata = dbgetquery(db, sitequery) is error in sqlite query or in r script? ideas how can fix this? # fetch site. sitequery <- "select nid, title, description nodes datatype = 'speck' , visible = '1' , nid = 'site' " # match pattern , replace it. sitequery <- sub("site", as.c

javascript - Parse Connection is not working -

i'm trying connect web application parse database , not working. implement code in html , js don't know wrong because not saving form in data base , main.js. think have put in there don't know what. this final project. here code <!docutype html> <html> <html> <head> <title>erp webapp</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script> <script type="text/javascript"> parse.initialise("svw5ons8f0arvhqyp5rzs70ycdmpstshn3dbkodo", "jx8gheyaf2umq2gesgeind7ilywfndcwa5uezwnw"); var parseobj = parse.object.extend('registertable'); //create local parse object parse class //$('#submit').bind("click",function(e)){ $('#register').submit(function(e){ //on fo

ios - Can't call ViewController method from AppDelegate -

in appdelagate call following in method func example() { viewcontroller().test() } and in viewcontroller method is func test() { testview.userinteractionenabled = true buttontapped(uibutton()) restarttimer() } but crashes whenever call method, due nil error testview. testview view in viewcontroller , not in appdelegate, don't know how make method executes how if called in viewcontroller. an iboutlet nil until view controller calls viewdidload . viewdidload did not occur since tried instantiate class directly via call viewcontroller() . thus, testview nil, expected. appdelegate should not responsible viewcontroller logic anyhow.

Android Login Screen after Application enters foreground again. Login Screen is NOT root Activity -

i'm programming voting android application. after user has chosen election wants make vote, user gets redirected login activity has enter password. after that, ballot activity gets started , person can choose candidates. requirement in project is, if application leaves foreground (onpause()) , enters foreground later (onresume()), login screen should return , ask user credentials again. how 1 realize that? saw solutions @ stackoverflow android:cleartaskonlaunch="true", work if login screen root activity, in case not true. can me out? thank you. p.s: i'm sorry bad english, i'm not native speaker. you need call finish() everytime launch loginactivity or ballotactivity. private void go2login(){ intent = new intent (ballotactivity.this, loginactivity.class); startactivity(i); finish(); } void onpause(){ go2login(); } but think not design. user angry if has enter password everytime app pauses. think should store password in preferences i

java - Spring MVC similar setters -

i have 2 classes string title field. have similar setters called settitle() . when use them object parameters in post request, field values rewrite new values in foo , bar. foo populates in controller before request. public class foo{ // ... string title; public void settitle(string title){ this.title=title; // ... } public class bar { // ... string title; public void settitle(string title){ this.title=title; // ... } } @modelattribute public void populatefoo(model model){ foo foo = foo.getfromdb() model.addattribute(foo); } @requestmapping public string somepost(foo foo, bar bar, ...){ bar newbar = new bar(); newbar.settitle(bar.gettitle()); } when i'm invoking settitle() on newbar , method settitle() on foo invoked. there no simple way spring mvc distinguish unfortunately - if submit field name title complex types have setter title set. 1 place dto may help, type encompasses fields both types , instantiates f

javascript - angularjs $watch cannot detect change of Property in an object -

i'm setting watch $scope object not trigger $watch change event unless whole value changed example : //some in .run function set rootscope , set $watch too. $rootscope.config = {date:'11/4/2015',morevalues:'etc'}; //setting $watch $rootscope.$watch('config',function(new,old) { console.log('config value changed :)',new); }); //----->inside controller---------- //now not trigger $watch $rootscope.config.date = 'another day'; //same this, not trigger $watch var temp = $rootscope.config; temp.date = 'another day'; $rootscope.config = temp; //yet work fine :) , trigger $watch var temp = angular.copy($rootscope.config); temp.date = 'another day'; $rootscope.config = temp; can tell me why behavior? there better way trigger $watch on change of object property? you can use $watchcollection, or pass third param true $rootscope.$watch('config',function(value,old) { console.log('config value cha

Spring-Integration XML to Java -

how can convert code java config? <int-kafka:outbound-channel-adapter id="mainoutboundchanneladapter" kafka-producer-context-ref="kafkaproducercontext" channel="mainoutboundtopicchanel"> </int-kafka:outbound-channel-adapter> yes, can. please, find latest spring integration java dsl : your case may looks like: @bean public integrationflow sendtokafkaflow(string serveraddress) { return f -> f.<string>split(p -> fastlist.newwithnvalues(100, () -> p), null) .handle(kafkamessagehandler(serveraddress)); } private kafkaproducermessagehandlerspec kafkamessagehandler(string serveraddress) { return kafka.outboundchanneladapter(props -> props.put("queue.buffering.max.ms", "15000")) .messagekey(m -> m.getheaders().get(integrationmessageheaderaccessor.sequence_number)) .addproducer(test_topic, serveraddress, this::producer); } pr