Posts

Showing posts from February, 2012

javascript - Angularjs 1.5x: How to call a function only once in a template and reuse the result in multiple places -

i have count of questions left in each section , count displayed user unless there 0 left in case display check mark. <p class="list-group-item-heading">{{section.title}} <i ng-show="questionsleft(section)==0" class="fa fa-check"></i> <span ng-show="questionsleft(section)>0" class="label"> {{questionsleft(section)}}</span> </p> the function questionsleft() called 3 times - how can called once , result reused? have tried both ng-init , {{x = questionsleft(section); ""}} trick both of initialize variable not update when value changes. create variable inside section component controller. put variable instead of function inside template. update variable value each time number of questions changed questionsleft function. can inside $onchanges hook, instance. p.s. easier if provide controller code

Issue related to import excel file in rails -

i following ryan bates railscast website tutorial importing excel file rails application. , have done it. want perform bit more complex operations excel data. able import whole content of excel file database table. want each row of excel file before inserting database. need perform operations on each row of excel file. don't know how achieve this. my model name employee , table name employees. model is:- class employee < activerecord::base def self.import(file) spreadsheet= employee.open_spreadsheet(file) header=spreadsheet.row(1) (2..spreadsheet.last_row).each |i| row=hash[[header,spreadsheet.row(i)].transpose] em=find_by_id(row["id"])||new em.attributes=row.to_hash.slice('firstname') em.save end end def self.open_spreadsheet(file) case file.extname(file.original_filename) #when ".csv" roo::csv.new (file.path nil, :ignore) when ".xlsx" roo::excelx.new (file.path) #whe

javascript - PHP create filename in hebrew -

i'm trying create new filename in hebrew displaying in special characters "שש_שש_שש.php" php: $page = mysql_real_escape_string(htmlspecialchars($_post['page'])); $fh = fopen('../pages/'.$page.".php", 'w') or die("can't create file"); fclose($fh); thanks. have tried hebrev() ? $page = mysql_real_escape_string(htmlspecialchars($_post['page'])); instead try this $page = hebrev($_post['page']); this might work.

centos - How to install yum repository key with ansible? -

i tried two ways : - name: add repository yum_repository: # https://oss-binaries.phusionpassenger.com/yum/definitions/el-passenger.repo name: passenger description: passenger repository baseurl: https://oss-binaries.phusionpassenger.com/yum/passenger/el/$releasever/$basearch repo_gpgcheck: 1 gpgcheck: 0 enabled: 1 gpgkey: https://packagecloud.io/gpg.key sslverify: 1 sslcacert: /etc/pki/tls/certs/ca-bundle.crt - name: add repository key (option 1) rpm_key: key: https://packagecloud.io/gpg.key - name: add repository key (option 2) command: rpm --import https://packagecloud.io/gpg.key - name: install nginx passenger yum: name={{ item }} with_items: [nginx, passenger] but work, need ssh machine, confirm importing key (by running yum command, e.g. yum list installed ), , continue provisioning. there way automatically? upd here's ansible says: task [nginx : add repository key] ****************************************

c++ - How to make cv::setMouseCallback function work -

i've seen few questions same. still unable make code work after reading answers. sorry in advance if repeating posts. i managed write code : #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <string> bool leftbuttondown = false, leftbuttonup = false; cv::mat img; cv::point cor1, cor2; cv::rect rect; void mousecall(int event, int x, int y, int, void*) { if (event == cv::event_lbuttondown) //finding first corner { leftbuttondown = true; cor1.x = x; cor1.y = y; std::cout << "corner 1: " << cor1 << std::endl; } if (event == cv::event_lbuttonup) { if (abs(x - cor1.x)>20 && abs(y - cor1.y)>5)

An error occurred creating push for user scripts: azure.notificationHubService could not be created -

in azure mobile service javascript backend ,trying send notification calling notification hub through custom api. giving me notification , everytime giving time out error too. observed logs , showing "an error occurred creating push user scripts: azure.notificationhubservice not created" . instead of using azure.createnotificationhubservice method , there way import created notification hub service ?how rid of time out error. pasting function below. function sendnotification() { var azure = require('azure'); var notificationhubservice = azure.createnotificationhubservice('disapphub','endpoint=sb://xxx.servicebus.windows.net/;sharedaccesskeyname=defaultfullsharedaccesssignature;sharedaccesskey=my_key_here=;'); var payload = { data: { "type":"newthread", } }; var mytags ='admin'; notificationhubservice.gcm.send(mytags, payload, function(error){ if(!error){ //notificat

javascript - Protractor.js test case for Horizontal Scrolling and vertical Scrolling in angular2 -

how write test case identify whether view has horizontal or vertical scrolling through protactor angularjs2? here reusable jasmine matcher use check if element has vertical scroll (reference: expect element have scroll ) (cannot guarantee work in or of cases, of course - works though): beforeeach(function() { jasmine.addmatchers({ tohavescroll: function() { return { compare: function(elm) { return { pass: protractor.promise.all([ elm.getsize(), elm.getattribute("scrollheight") ]).then(helpers.spread(function (size, scrollheight) { return scrollheight >= size.height; })) }; } }; } }); }); usage sample: expect(loginpage.license).tohavescroll(); fyi, here 1 - checking if there scr

html - How do I show menu list below hamburger icon? -

how show menu list below hamburger icon? css: @media screen , (max-width:680px) { ul.topnav.responsive {position: relative;} ul.topnav.responsive li.icon { position: absolute; right: 0; top: 0; } ul.topnav.responsive li { float: none; display: inline; } ul.topnav.responsive li { display: block; text-align: left; } .container { width: auto; } } jsfiddle: https://jsfiddle.net/xkp0p7vc/ thanks in advance. just add display: block; clear: both; ul.topnav.responsive li , remove float: right; .topnav-right . ul.topnav.responsive li { float: none; display: block; /*change inline*/ clear: both; } .topnav-right { /* float: right; */ } demo

php class private property access outside class -

class { private $x=100; private $y=200; } $a=new a(); $x=(array) $a; foreach($x $key=>$val) { echo $x[$key]; } i have issue private variable of class a . class private variable access outside class when typecasting object array. should not access outside class. above example can access private variable of class a. here result 100200 how can resolve issue? you're not accessing private members there. you've got array holding state of object. encapsulation preserved, you're not allowed private member manipulation outside class blocks. now you're allowed bend on backwards , object state can use whatever, that's poorly written client. there's language can do, should free write good/bad code in language.

SQlite Swift unexpected result group -

i using swift sqlite. want retrieve 'flights' in groups switch 'departuredate' if let flightquery = self.flightquery, let database = self.db { let flightgroupbydeparturedate = flightquery.group(self.departuredate) { let flightfromdb = try database.prepare(flightgroupbydeparturedate) let flightgroups = array(flightfromdb) applog.i("flightgroups count \(flightgroups.count)") // print 2 : // have 2 groups of flight // each group got 2 flights // simulate result static values flighgroup in flightgroups { applog.i("flightgroups count \(array(arrayliteral: flighgroup).count)") // print 1 : wrong ! } }catch{ applog.e("fail findflightbydeparturedate" ) } } when print flightgroups, found 2 flights instead of 2 arrays of flight

python - Table does not exist on testing a read-only table (Django) -

i have django project. there 2 databases in project , i've written router make 1 of them readonly . i've written unit tests use readonly database, when run python manage.py test says programmingerror: (1146, "table 'test_arzesh-db.company' doesn't exist") here settings of databases: databases = { 'default': { 'engine': 'django.db.backends.mysql', 'name': 'broker-website', 'user': 'root', 'password': '', 'host': 'localhost', 'options': { "init_command": "set foreign_key_checks = 0;", }, }, 'arzesh-db': { 'engine': 'django.db.backends.mysql', 'name': 'arzesh-db', 'user': 'root', 'password': '', 'test_database': 'default'

javascript - Boostrap css doesn't work -

i installed npm install bootstrap --save , added (below) index.html styles doesn't change. <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css"> my code (in other file): <button type="submit" class="btn btn-default">submit</button> only when add (below) index.html, works first web's load slow: <!-- latest compiled , minified css --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mtjoasx8j1au+a5wdvnpi2lkffwweaa8hdddjzlplegxhjvme1fgjwpgmkzs7" crossorigin="anonymous"> update: (more details) the file bootstrap.min.css exsist console says cant find it. folders strucure: there main folder ang2project , inside there node_modules folder , src folder contain index.html -angular2_projects -node_modules -bootstrap -dist

node.js - convert rss encoding from windows 1255 to utf 8 node js -

i trying parse hebrew rss one: http://rss.walla.co.il/?w=/3/0/12/@rss.e i using feedparser , request, , problem encoding windows-1255 , not utf-8 so see text like: ����� ������� , , not regular hebrew text. i tried converts (like iconv-lite) did not succeed. this code: function getall(url) { var request = require('request'); request(url, function (error, response, body) { if (!error && response.statuscode == 200) { var allxml = body.substring(body.indexof('<title>') + ('<title>').length, body.indexof('</title>')); var text = iconv.decode(new buffer(allxml), 'win1255'); console.log("text = ", text); } }) } and print: text = ן¿½×Ÿ¿½×Ÿ¿½×Ÿ¿½×Ÿ¿½! ן¿½×Ÿ¿½×Ÿ¿½×Ÿ¿½×Ÿ¿½ - ן¿½×Ÿ¿½×Ÿ¿½×Ÿ¿½×Ÿ¿½ you can use module such iconv or iconv-lite convert between encodings, since node natively supports utf8, utf16le, latin1/binary, ascii, hex, , base64.

php - Yii2 multiple models loop save error -

i've table in have save multiple data, in controller i've implemented action: public function actionupdateorder($id){ /*da testare*/ //$result = 0; $result = true; $s = new session; $model = new slidersimages(); if ($new_order = yii::$app->request->post('order')) { //$s['us_model'] = 0; foreach ($new_order $key => $value) { if ($model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()) { $s['image_'.$key] = $model; $model->display_order = $value; //$result = ($t = $model->update()) ? $result + $t : $result; $result = $model->save() && $result; } } } return $result; } the data received right not result, thing action add new table row slider_id , image_id equal null , why model doesn't save correctly? thanks the thing whe

Updating a sqlite database from Java -

i trying update sqlite db javafx. perform following query database in order update it: try { int savespeed = gui.savespeedint - gui.savespeedtimer; string query2; if(gui.textanswerq.equals(gui.saveanswer.gettext()) || gui.textanswertofq.equals(gui.saveanswer.gettext()) || gui.sanswertextfield.gettext().equals(gui.saveanswer.gettext())){ string answer = "1"; query2 = "update studentsquestions set time = '"+savespeed+"' set answer = '"+answer+"' username = '"+gui.saveuser.gettext()+"' , question = '"+gui.question.gettext()+"'"; } else{ string answer = "0"; query2 = "update studentsquestions set time = '"+savespeed+"' set answer = '"+answer+"' username = '"+gui.saveuser.gettext()+"' , question = '"+gui.question.gettext()+"'"; } preparedstatement pst2

ios - appDelegate managedObjectContext spread across codebase -

when using core data. find myself writing code appdelegate *delegate = [[uiapplication sharedapplication] delegate]; nsmanagedobjectcontext *context = [delegate managedobjectcontext]; // code here [context save:nil]; everywhere in codebase. normal or antipattern? use 1 context. if using core data on several places in app, use singleton class handles basic core data logic , holds persistentstorecoordinator , managedobjectmodel , of course wanted managedobjectcontext . @interface datamanager : nsobject @property (readonly, strong, nonatomic) nsmanagedobjectcontext *managedobjectcontext; @property (readonly, strong, nonatomic) nsmanagedobjectmodel *managedobjectmodel; @property (readonly, strong, nonatomic) nspersistentstorecoordinator *persistentstorecoordinator; + (datamanager *)sharedmanager; - (void)savecontext; @end then can use context anywhere this #import "datamanager.h" ... nsmanagedobjectcontext *managedobjectcontext = [[datamanager share

build.gradle - Android Studio - Cannot find symbol class -

when run app, android studio notifies me error in gradle build. could me understand how fix problem? mapsactivity public class mapsactivity extends fragmentactivity implements onmapreadycallback { private googlemap mmap; databasehelper mydb; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_maps); // obtain supportmapfragment , notified when map ready used. supportmapfragment mapfragment = (supportmapfragment) getsupportfragmentmanager() .findfragmentbyid(r.id.map); mapfragment.getmapasync(this); addmarkers(); } @override public void onmapready(googlemap googlemap) { mmap = googlemap; // add marker in sydney , move camera latlng sydney = new latlng(-34, 151); latlng ruvo = new latlng(-45, 123); mmap.addmarker(new markeroptions().position(sydney).title("marker in sydney")); mmap.addmarker(new markeroptions().position(ruvo)

matlab - Save extracted video frames as images -

i wish take screen grab of video frame , save each frame image in folder on desktop. there frames want capture however, written in text document. my question is, how read in frame numbers stored in text document , extract these frames png files? thanks can provide. if need clarify anything, please ask. frames = dlmread('frames.txt'); %getting no of frames numframes = mov.numberofframes; %setting current status of number of frames written 0 numframeswritten = 0; t = frames: numframes currframe = read(mov, t); %reading individual frames opbasefilename = sprintf('%3.3d.png', t); opfullfilename = fullfile(opfolder, opbasefilename); imwrite(currframe, opfullfilename, 'png'); %saving 'png' file progindication = sprintf('wrote frame %4d of %d.', t, numframes); disp(progindication); numframeswritten = numframeswritten + 1; end if understand question correctly: ... how read in frame numbers stored in te

JNDI @Resource not found in Wildfly 10 -

i'm trying access jndi oracle datasource through @resource annotation in resteasy webservice on wildfly 10, null returned. works initialcontext.lookup method. java code: @path("/rest") public class servicetest { @resource(name = "jdbc/oracleds") datasource source1; @resource(name = "java:/jdbc/oracleds") datasource source2; @resource(lookup = "java:/jdbc/oracleds") datasource source3; @get @path("/test") @produces(mediatype.text_plain) public string testjndi () { try { javax.naming.context initctx = new initialcontext(); datasource source4 = (datasource)initctx.lookup("java:/jdbc/oracleds"); initctx.close(); return "" + source1 + " / " + source2 + " / " + source3 + " / " + source4; } catch (exception error) { e.printstacktrace(); } } this standalone.xml datasource defi

c++ - cuda convolution mapping -

Image
i'm trying copy each block of threads patch of image , relative apron shared memory. after data copyied(i used matrix ) shared memory, want relations map center of mask in shared memory consider convolution , center of mask in image buffer. i want because if try convolution of image seems center of mask in shared memory doesn't correspond center in image buffer stored in global memory . in code below write example of simple image black , white erosion algorithm , when put result of convolution output image seems center not corresponds. i write sample using 512x512 px image my settings are: //block , grid size dim3 block(16,16); dim3 grid(512/(block.x),512/(block.y),1); this kernel: #define strel_size 5 #define tile_w 16 #define tile_h 16 #define r (strel_size/2) //size of tile image + apron #define block_w (tile_w+(2*r)) #define block_h (tile_h+(2*r)) __global__ void erode_multiple_img_sm_v2(unsigned char * buffer_in, unsi

Node js server on Amazon S3 & Cloudfront -

i'm trying create simple node js server on amazon aws (s3 & cloudfront). here step followed : created aws account created bucket on s3 created cloudfront web distribution everything working well, next step install node js server , run ? any appreciated thanks s3 not server, it's storage static files. you need setup ec2 , install node server it. if want serve static js lib clients, can use s3 bucket , cloudfront. https://aws.amazon.com/cloudfront/webinars/

python - Find model object that encompasses another in Django -

given unsaved/local model object, how can find list of objects have information of unsaved object without having keep list of fields in sync? for example, have model: class person(models.model): name = models.charfield(max_length=100) job = models.charfield(max_length=100, null=true) hands_lost = models.integerfield(null=true) and have created data in past this: person.objects.create(name='luke', job='trainee') person.objects.create(name='yoda', job='master') person.objects.create(name='yoda', job='force ghost') and 'hands lost in universe' db event telling me "set luke's hands_lost 1", like: luke = find_my_object(person(name='luke')) if luke: luke.hands_lost = 1 luke.save() else: luke = person.objects.create(name='luke', hands_lost=1)[0] where: def find_my_object(person): return **magic here**.first() expected results might be: find_my_object(person

python - Referencing columns in Pyspark DataFrame -

suppose have word list converted data frame ----- | word | ----- | cat | | bird | | dog | | ... | ----- and tried letter count: from pyspark.sql.functions import length letter_count_df = words_df.select(length(words_df.word)) i know results dataframe single column only. how refer column of letter_count_df without using alias ? ------------- | length(word) | ------------- | 3 | | 4 | | 3 | | ... | ------------- with name: >>> letter_count_df.select(c) dataframe[length(word): int] or col , name: >>> pyspark.sql.functions import * >>> letter_count_df.select(c)) with c being constant: >>> c = "length(word)" or >>> c = letter_count_df.columns[0]

postgresql - Ruby TCP server - ERROR:PG::ConnectionBad: FATAL: remaining connection slots are reserved for non-replication superuser connections -

i have written tcp server receives packets terminal device. tcp server interprets data , saves in database using postgres. the tcp server multi-threaded. sample of code of moment open db connection , save data looks this; conn = sequel.connect('postgres://xxxxx:xxxxxxxxxx@127.0.0.1:xxxxx/xxxxxxxxx',:max_connections => 100) # requires pg transactions = conn.from(:transactions) if transactions.insert(serial_number: card_serial, balance_before: balance_before, amount: transaction_amount, balance_after: balance_after, transaction_time: time, terminal_number: terminal_number, terminal_type: terminal_type, created_at: time.now, updated_at: time.now) response = {message: "tt01000080", status: "success" } return response else response = {message: "", status: "failed" } return response end after few packets, db creates error this; error:pg::connectionbad: fatal: remaining connection slots reserved non-replication superuser co

emacs - How to make org-mode not to highlight Sunday (in bold) as weekend? -

is there way make org-mode and/or calendar not highlight sunday (in bold/red) weekend in weekly agenda/3 months calendar views? you can customize org-agenda-weekend-days . documentation says: which days weekend? hide these days special face ‘org-agenda-date-weekend’ in agenda , timeline buffers.

git - How to pull in changes from skeleton sub-repository into production super-repository -

i using aurelia skeleton contains various project setups different purposes, more of general question of how git discribed below. i able merge in updates published in github skeleton repository project working on. how that? at moment initialized new local repository in skeleton-typescript project (which using) , connected private remote repo push changes. setup, polluting parent repository (remote pointing aurelia-skeleton on github) project-specific changes. it perfect have kind of one-way tracking going aurelia-skeleton remote repository used pull changes in. as second step, interesting how create pull request such setup. in case, use changes made in sub-repository merged fork of aurelia remote... my usual workflow create dedicated branch track upstream project. can cherry pick want onto branch , create pull request without muddying template project specifics. first thing, go ahead , fork aurelia/skeleton-navigation can issue pull request through github'

hibernate - How to get collection by left join that is fetched by sub select via Spring data(JPQL)? -

is possible collection via sub-select , set entity? need find entities restriction , after that, need join them entity. for example, need find company employees worked in company given date from pure sql need that: select * company c left join ( select * employee hiredate > 10.5.2015 , departuredate < 10.12.2015 ) e on c.id = e.companyid i tried via query in spring data doesn't work @query("select c company c left join fetch (c.employees e e.hiredate > ?1 , e.departuredate < ?1)) c.id = ?2) list<company> findcompanywitemployes(long salary, long companyid); entities: public class employee{ long id string name; date hiredate; date departuredate; @manytoone @joincolumn(name = "companyid", insertable = false, updatable = false) company company; } public class company{ long id string name; @onetomany(mappedby="company", cascade=cascade

android - AdMob mediation reward video ads are not loading -

i trying implement admob reward video ads. far understanding error log ads being loaded device not being played in system. have read , write permission in android manifest file still not playing video ad. plus showing me error @ function onrewardedvideoadfailedtoload ref #2 in codes. can 1 read , point me mistake? here error log getting ad not being displayed. 06-29 15:54:05.021 1548-1548/test.my.app d/viewrootimpl: viewpostimeinputstage processpointer 0 06-29 15:54:05.071 1548-1548/test.my.app d/viewrootimpl: viewpostimeinputstage processpointer 1 06-29 15:54:05.111 1548-1548/test.my.app d/cr_ime: [inputmethodmanagerwrapper.java:59] isactive: true 06-29 15:54:05.111 1548-1548/test.my.app d/cr_ime: [inputmethodmanagerwrapper.java:68] hidesoftinputfromwindow 06-29 15:54:05.131 1548-1548/test.my.app i/ads: ad closing. 06-29 15:54:05.191 1548-1548/test.my.app i/timeline: timeline: activity_launch_request id:test.my.app time:476669498 06-29 15:54:05.221 1548-1548/test.my.app w

html - Pseudo element goes on top and not on the bottom of element -

Image
i have :after pseudo element create border bottom animation (border coming in left right), used technique several times time border comes on top , not on bottom reason, cant figure out. tried using float , chaning display type makes no different. html: <div class="search"> <svg viewbox="0 0 485.213 485.213"> <path d="m471.882,407.567l360.567,296.243c-16.586,25.795-38.536,47.734-64.331,64.321l111.324,111.324 c17.772,17.768,46.587,17.768,64.321,0c489.654,454.149,489.654,425.334,471.882,407.567z"/> <path d="m363.909,181.955c363.909,81.473,282.44,0,181.956,0c81.474,0,0.001,81.473,0.001,181.955s81.473,181.951,181.955,181.951 c282.44,363.906,363.909,282.437,363.909,181.955z m181.956,318.416c-75.252,0-136.465-61.208-136.465-136.46 c0-75.252,61.213-136.465,136.465-136.465c75.25,0,136.468,61.213,136.468,136.465 c318.424,257.208,257.206,3

css - setting padding depending on number of child elements -

i have div element may contain 1 or 2 child divs is there way of there 1 child element padding should 15px otherwise 5px it may like <div class="container"> <div><strike>7.00</strike></div> <div>5.00</div> </div> or <div class="container"> <div>7.00</div> </div> you can trick using margin in children same effect: .container div:only-child { margin: 15px; } div { border: solid 1px red; } div div { margin: 0 5px; border-color: green; background: #ccc; } div div:first-child { margin-top: 5px } div div:last-child { margin-bottom: 5px } <div class="container"> <div><del>7.00</del></div> <div>5.00</div> </div> <div class="container"> <div>7.00</div> </div> ps use del tag instead strike deprecated

algorithm - How to answer find duplicates in array extension questions? -

i @ technical interview, given question "find duplicates in array" , solved in o(n) time hashtable no problem, given barrage of follow questions. orig: determine if array contains duplicate entries. f1: if array large, , had distributed across multiple machines. f2: if network connection between these machines prone failure? f3: if hardware not 100% reliable , may give off wrong answers? f4: design system multiple simultaneous users may need update array, while need maintain uniqueness of entries. i thought f1 , said wouldn't wise use huge hashtable , trade runtime o(n²) compensate o(1) memory, wasn't sure rest. help? f2: have duplicate data on different machines, can chose data or part of data. f3: use checksum values when transferring data between machines. f4: use kind of synchronisation (like semaphores) make sure updating not done simultaneously.

c# - Make my program wait for a second before performing an action -

i have : private void form1_load(object sender, eventargs e) { hide(); string ngdx = "*ngdx"; string atdx = "*atdx"; (;;) { try { string[] convertngdx = directory.getfiles("d:\\folder", ngdx); string[] convertatdx = directory.getfiles("d:\\folder", atdx); foreach (var convertngd in convertngdx) { file.move(convertngd, path.changeextension(convertngd, ".ngd")); } foreach (var convertatd in convertatdx) { file.move(convertatd, path.changeextension(convertatd, ".atd")); } } catch { } } } i start app , every time .ngdx , .atdx fil

git - Adding changes from another commit except for some files -

i have broken commit adding many files, reverted previous commit, created new branch out of it, , have new branch old commit on it. i want add changes commit after reverting except redundant files. how this? there's no need revert, git rm on files didn't want, git commit --amend alter bad commit doesn't include files. alternatively, git cherry-pick -n <bad-commit-id> apply bad commit current branch, edit removing unwanted parts, commit.