Posts

Showing posts from September, 2013

java - lwjgl freezes on creation of Font object -

i making simple game of snake, because can, , stumbled across interesting bug. trying use slick-util draw text on screen, whenever try create font object game freezes. here code. highlighted section prints 'a' once. package tlf.snake.main; import tlf.snake.main.game.helper.pos; import tlf.snake.main.game.input.input; import java.awt.font; import java.nio.bytebuffer; import java.nio.intbuffer; import org.lwjgl.bufferutils; import org.lwjgl.glfw.glfwwindowposcallback; import org.lwjgl.glfw.glfwwindowsizecallback; import org.lwjgl.glfw.glfwvidmode; import org.lwjgl.opengl.glcontext; import org.newdawn.slick.truetypefont; import static org.lwjgl.glfw.callbacks.glfwsetcallback; import static org.lwjgl.glfw.glfw.*; import static org.lwjgl.opengl.gl11.*; import static org.lwjgl.system.memoryutil.null; /** * @author thislooksfun */ public class snakegame { private static final game game = new game(); private int width = game.gamewidth*15; private int heigh

java - utf-8 is not working when i am attaching file name using mimeMessageHelper using webLogic -

it's working on tomcat not working on weblogic body can , when trying decode information not getting proper output file name not getting proper output when attaching file name mimemessage message = mailsender.createmimemessage(); mimemessagehelper mh = new mimemessagehelper(message, true, "utf-8"); multipart multipart = new mimemultipart(); mimebodypart messagebodypart1 = new mimebodypart(); mh.setto(to); mh.setfrom(from); mh.setsubject(subject); mh.settext(content, true); string attachmentname = "cây chàm sự kiện.pdf"; if (!stringutils.isempty(attachmentname) && attachmentdata != null) { when coverting string utf - 8 not getting propet when printing value getting proper output attachment file name not getting mh.addattachment(attachmentname, new bytearrayresource(attachmentdata)); } mailsender.send(message);

Read words/phrases from a file, make distinct, and write out to another file, in Java -

i have text file word or phrase on each line. how i: read phrases memory, make distinct (eliminate duplicates), sort alphabetically, write results out file? stackoverflow has answers similar questions in other languages such c , php , python, prolog , , vb6 . cannot find 1 java. you can leverage: nio (non-blocking i/o) api (available since java 7) streams api (available since java 8) …to solve problem elegantly: public static void main(string... args) { path input = paths.get("/users/youruser/yourinputfile.txt"); path output = paths.get("/users/youruser/youroutputfile.txt"); try { list<string> words = getdistinctsortedwords(input); files.write(output, words, utf_8); } catch (ioexception e) { //log error and/or warn user } } private static list<string> getdistinctsortedwords(path path) throws ioexception { try(stream<string> lines = files.lines(path, utf_8)) { return lines.map(string::trim

windows - Undefined subroutine &UUID::generate called at -

i encountering problem following perl script else wrote generate uuid , print stdout. has misconfigured perl setup on windows 7 machine activestate's perl http://downloads.activestate.com/activeperl/releases/5.20.2.2001/activeperl-5.20.2.2001-mswin32-x86-64int-298913.msi . have data::uuid perl module versiion 1.220 installed. #!/usr/bin/perl use uuid; uuid::generate($uuid); uuid::unparse($uuid, $string); print $string . "\n" when script in dos shell run no arguments following error: undefined subroutine &uuid::generate called @ xxx any advice on how debug this?

How can make the width of string the same in Android? -

Image
there 3 strings, each length of string same, there spaces in strings. after fill 3 strings in listview control, find width of 3 row isn't same. how can make width of string same in android? thanks! btw, use android studio. min api 9. string1= "a b" string2= "aa b" string3= "aaa b" listview lv=(listview)findviewbyid(r.id.listview); string[] countries=new string[]{"a b","aa b","aaa b"}; lv.setadapter(new arrayadapter<string>(this, android.r.layout.simple_list_item_1, countries)); unless you're using monospaced font, achieving wanted going quite difficult. non-monospaced fonts has different width each of characters posses. however, there's workaround using layout arrangement. here's example: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orient

ruby - Rails model relation MissingAttributeError -

i have models in application, , i'm trying save data got error: activemodel::missingattributeerror (can't write unknown attribute product_id ): app/controllers/admin_controller.rb:27:in `create_product' i have 3 models category model class category < activerecord::base has_many :features has_many :products end migration: class createcategories < activerecord::migration def change create_table :categories |t| t.string :name, null: false t.boolean :active, null: false, default: false t.timestamps null: false end end feature model class feature < activerecord::base has_and_belongs_to_many :categories has_and_belongs_to_many :products end migration class createfeatures < activerecord::migration def change create_table :features |t| t.belongs_to :category, index:true t.string :name, null: false t.timestamps null: false end end product model class product < acti

python - Does Wokkel (XMPP Library) support following features? -

i want develop xmpp protocol implement rpc communication following features. 1.security authentication between client , server. 2.support null values(send null values server) 3.can able send arbitrary values(xml-rpc support 32 bits) 4.can send method arguments custom.(for eg sum(default,4,default) default values chosen server ) 5.return error if, should arbitrary object i know whether wokkel library support these features or know other libraries support these features.(eg:sleekxmpp or xmpppy) this question seems have 2 parts: 1) there existing xmpp extension protocol supports listed feature? 2) wokkel (or possibly other python xmpp libraries) support this? the xmpp extention protocols generic rpc behaviour xep-0009 (jabber-rpc) , xep-0050 (commands) . xep-0009 uses xml-rpc payloads sent on xmpp. mention xml-rpc doesn't fit use case. xep-0050 uses xep-0004 data forms perform predefined command exchanges server. don't think fits requirements #2,

Python Regex Query -

i started learning regex in python. going through code extracting email address string. str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher' emails1 = re.findall(r'[\w\.-]+@[\w\.-]+', str) emails2 = re.findall(r'[\w.-]+@[\w.-]+', str) is there difference between code emails1 , emails2? tested on 1 string , both giving same output. this first post here. please don't mind if post not according standards.thanks. the difference see . , \. , make difference. . stands "any character except newline" , \. being literal dot. however, in character classes [abcd.] means "any of following" characters . taken literary. since . both in charater class, there no difference between two. you should escape - in character classes though, since stands character range [a-z] . works in case because it's last character in class, don't want forget @ point , later on wonder "what's going wrong"

regex - How to find whether specific number of continuous consecutive numbers are contains in a string using javascript? -

suppose want know whether string contains 5 or more continuous consecutive numbers. var = "ac39270982"; // false var = "000223344998"; // false var = "512345jj7"; // true - contains 12345 var = "aa456780"; // true - contains 45678 is there regex available accomplish this? able work in following situation? var = "5111213141587"; // true this should true because contains 11,12,13,14,15. i'm not sure if possible check provided examples (single-digit, double-digit numbers) larger numbers (triple-digit, etc.). i took time make 100% javascript approach question. made parse each character in string , integer comparison. works not 5 consecutive integers, works checking tenths (10's, 20's, etc). can increase/decrease number of comparisons if wish. a fair warning: despite method being potentially scalable if coded kinds of numeric sizes, you'd still bound computing power , number of comparisons. why provi

c++ - Qt can't assign value to QLabel -

i start out saying i'm noob come. first c++ program built scratch. gotten of bugs ironed out, can't seem able assign value qlabel. want function 'value' called when calculate button pressed. function 'value' should math , return answer assigned qlabel 'results'. here have far. #include <qapplication> #include <qpushbutton> #include <qlabel> #include <qslider> #include <qstring> #include <qspinbox> #include <qhboxlayout> #include <qcombobox> double x; double value(qspinbox *spinner) { int speed; speed = spinner->value(); x = speed/8; return x; } int main(int argc, char *argv[]) { qapplication prog(argc, argv); qwidget *mainwindow = new qwidget; mainwindow->setwindowtitle("plex calculator"); qpushbutton *calculate = new qpushbutton("calculate"); qcombobox *kbormb = new qcombobox; qspinbox *spinner =new qspinbox; qslider *slider = new qslider(qt::horizontal); qlabel *re

ASP.Net MVC multi record save -

i'm writing mvc5 application have model called survey. public class survey { public int surveyid { get; set; } [required] public string description { get; set; } [required] public string classification { get; set; } [required] public int score1{ get; set; } [required] public int score2{ get; set; } public string notes { get; set; } } i'm passing collection of survey records view display them in list. want able allow user answer each survey record/question , have save button @ bottom of form conduct 1 post action controller. i've never tried pass collection of objects post controller i'm curious if approach? suggestions appreciated! thanks in advance! what suggest not passing collection view new viewmodel 'surveyset' perhaps field being ilist(survey). in controller when call db.savechanges() on surveyset , changes each of surveys should saved. [httppost] [validateantiforgerytoken] public a

jquery - Edge Animate Timeline Control -

i very new writing code hoping out there me out couple of functions have in head! i have made button in edge animate , i’d add kind of jquery or code actions. basically, on timeline getting animation play points on different mouse events. on ‘rollover’, plays , stops halfway. on ‘click’ i’ve got playing next ‘label’ because mouse still hovering on button, ‘rollover’ function kinda trips whole thing , doesn’t know on timeline. i’d ‘rollover’ function disable after first mouse click. or ‘not’ play until ‘mouseout’ (after click). ideally (as extra) i’d toggle between 2 states on alternating clicks. so, click 1: play point (a), click 2: play point (b), . . . . (a), (b), (a), (b), ad infinitum! , whole thing should reset on mouseout!! that’s lot of work, hey? appreciate tips or suggestions… somewhere start from! muchly. a way via timeline duplicate button , change code on @ every label. first button has sym.play("b"); code on @ b label have identical button

Prevent a triggering action using a cookie with JavaScript -

in wordpress site have pop window (for email capture) triggered "mouseleave" event. the pop works fine once info captured or pop window closed dont want bother visitor pop anymore. want set cookie detect event has taken place , not trigger again until week or month later visitor. here code: <script> jquery(document).ready(function() { jquery('html').one("mouseleave", function(e){ jquery('.backdrop, .box').animate({'opacity': '.50'}, 300, 'linear'); jquery('.box, .box').animate({'opacity': '1.00'}, 300, 'linear'); jquery('.backdrop, .box').css('display', 'block'); jquery( ).off( event ); }); jquery('.close').click(function(){ jquery('.backdrop, .box').animate({'opacity': '0'}, 300, 'linear', function(){

jquery - Gradient text cross browser -

i'm trying make menu bar horizontal gradient. i've had success using -webkit-background-clip won't work in firefox. i found jquery plugin pxgradient that's cross browser compatible can't span gradient on several li elements. see following jsfiddle: http://jsfiddle.net/vnv4nyhj/10/ function gradient1() { $(".test").pxgradient({ step: 10, colors: ["#ff0066", "#2850ff"], dir: "x" }); }; i want gradient more top one. ideally i'd border-bottom include same gradient on hover can possibly live in world without that. ps- font-awesome icon there because gave me problems earlier included make sure works. update: possible idea playing read number of elements, divide colours per element , use nth-child() selector assign each color. <script> //get number of list items var menuitems = $("li").children().length; //convert colors hex hexstring1 = '2850ff'; hexs

python - Using a for loop to interchange maximum and mininum variables in an equation -

so have unpacked multiple arrays containing numbers in text file. i've figured out put them in equation so: import numpy np import matplotlib.pyplot plt import urllib numpy import sin, cos scipy.special import jv tms, period, perioderr, bjdo, bjdoerr, ecc, eccerr, omega, omegaerr, ampltd, ampltderr, yo, yoerr = np.loadtxt(tm_filename, unpack = true) def compute_etv(bjd, bjdo, period, ecc, ampltd, omega, yo, numiter = 20): m = 2 * np.pi * (bjd - bjdo) / period u = m + sum([2./k * jv(k,k*ecc) * sin(k*m) k in range(1,numiter)]) return yo + ampltd/(24*60*60) * ((1-ecc**2)**0.5 * sin(u)*cos(omega)+(cos(u)-ecc)*sin(omega)) i,item in enumerate(tms[:10]): etv = compute_etv(bjd[ecl==0], bjdo[i], period[i], ecc[i], ampltd[i], omega[i], yo[i], 20) the question is, "how can interchange minimum , maximum numbers of these values? want use loop input maximums , minimums each of arrays corresponding error value adding maximum or subtracting minimum, how can mix , ma

android - Java - Typecast a object to a String Class Named Object -

this question has answer here: java: how can dynamic casting of variable 1 type another? 13 answers i have object of class. want typecast class. so, - heavyvehicle hv = new heavyvehicle(); truck tr = (truck) hv; if typecast hv object truck classes object. but if name of class stored in string this- string tocaststringname = "truck"; is there way typecast hv object class named tocaststringname ? i'm not sure use case can use: class.forname(classname).cast(someobject) to dynamically cast object knowing class name. in case, code: heavyvehicle hv = new heavyvehicle(); string tocaststringname = "truck"; class.forname(tocaststringname).cast(hv); would return object of type truck . there's long discussion uses , tradeoffs of either approach in post: java class.cast() vs. cast operator

css3 - Image scale transform jumps (chrome blink engine only) -

please move cursor center of image whitespace , back. image jumps max scale without animation. video .wrapper { margin : 120px; } .wrapper img { display : block; width : 400px; -webkit-transition: -webkit-transform 300ms linear; -moz-transition: -moz-transform 300ms linear; -ms-transition: -ms-transform 300ms linear; -o-transition: -o-transform 300ms linear; transition: transform 300ms linear; -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden; -ms-backface-visibility: hidden; -o-backface-visibility: hidden; backface-visibility: hidden; } .wrapper img:hover { -webkit-transform: scale(1.5); -moz-transform: scale(1.5); -ms-transform: scale(1.5); -o-transform: scale(1.5); transform: scale(1.5); } <div class="wrapper"> <img src="http://retriever

can't push huge git commit -

i have huge 11gb repo android sources. created repo "git init", 1 single commit "git commit --all ." can't push remote repo, when issue " git push -u origin --all " it's stuck executing "git pack-objects --all-progress-implied --revs --stdout --thin --delta-base-offset --progress" . speed of reading data 1mb/s iotop says. bitbucket refuses message "fatal: remote end hung unexpectedly" , nothing yet pushed git job locally. how disable packing , go further? your repository way big bitbucket : in order improve , maintain overall performance uses bitbucket, rolling out size limits on newly-created repositories. starting [may 30, 2014], repository size limits be: soft limit of 1 gb – in-product , email notifications give heads-up you’re approaching limit. hard limit of 2 gb – pushing repository disabled until you’re under limit.

python - What is the function of elif? -

if wanted check multiple conditions, can't use multiple if statements? example: a = 10 b = 20 if == b: print('equal') if < b: print('less') if > b: print('greater') using multiple if statements evaluate every if condition. conditions in example mutual exclusive, might have similar result. however, if a or b changes in-between, condition might become true: a = 5 b = 7 if < b: = b if == b: b += 1 both conditions evalute true , executed. might not intended, use: a = 5 b = 7 if < b: = b elif == b: b += 1 will execute first condition. even mutual exclusive conditions example, every expression has evaluated, slower second variant. note elif (aka else if ) identical to: if <cond1>: pass else: if <cond2>: pass else: if <cond3>: pass as can see, result in tests run out of text , less readable than: if <cond1>: pass elif <co

python - Pygame lines disappear after rotating points -

i new python , tried make game ship rotates. however, after rotating, ship disappears. printed coordinates of 3 points, , should appear on screen. know what's wrong code? this code rotating ship: radius = self.width / 2 self.angle += da center = [self.pos[0] + radius, self.pos[1] + radius] point in self.points: dx = int(math.cos(self.angle) * radius) dy = int(math.sin(self.angle) * radius) point[0] = center[0] + dx point[1] = center[1] + dy this code drawing screen: while true: event in pygame.event.get(): if event.type == pygame.quit: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.k_up]: self.ship.move(self) if keys[pygame.k_right]: self.ship.rotate(0.08) if keys[pygame.k_left]: self.ship.rotate(-0.08) self.display.fill(self.bgcolor) self.ship.draw(self.display) pygame.display.update() self.fpsclock.tick(self.fps) look @ code

c# - WaitHandleCannotBeOpenedException occured in System.dll -

Image
i getting warning when trying run project in debug mode. in previous projects, when have gotten warning, visual studio typically points me specific line of code. but in case, have no idea how respond warning. what steps should take debug/fix warning? there nothing need go debug menu exceptions option , uncheck "thrown" option. see on exception dialog listed first chance exception . first chance exception sent notify debugger. second change exception send application handle. all happening have option "thrown" option enabled , visual studio pointing code throw occurred, inside of system dll, not surprising @ all.

ifstream - C++ : Dynamic C-String Usage in ifstreamObject.getline(c string, char limit) -

i wondering if there way dynamically allocate space char aray equal amount of spaces in line file while use getline method. (c++) example int main(){ char *theline; ifstream thefile; //set theline = new char[sizeofthefileline] //is there way above thefile.getline(theline, 500); return 0; } if use std::getline , desired behavior. std::string theline; std::ifstream thefile; // .... std::getline(thefile, theline);

r - ggplot2 following layer removing previous layer -

when add layer ggplot graph, previous layer settings disappear. keep size of chart points, when add layer change background of plot, point sizes removed. code plot: p <- ggplot(a,aes(zip, perc)) + geom_point() p <- p + labs(x = "zip code", y = "percent penetration") + labs(title = "zip code tier a") p + geom_point(aes(size = zgrp)) p + theme(panel.background = element_rect(fill = "ivory")) data: zip cgrp zgrp perc 1: 12007 4 15 48.387097 2: 12008 4 25 41.666667 3: 12009 4 956 52.643172 4: 12010 4 1047 30.025810 5: 12018 4 859 49.113779 6: 12019 4 838 54.380273 7: 12020 4 1233 43.126967 8: 12022 4 37 34.579439 9: 12023 4 225 47.669492 10: 12027 4 139 50.180505 11: 12028 4 35 46.052632 12: 12033 4 1062 48.559671 13: 12041 4 47 42.342342 14: 12046 4 55 43.650794 15: 12047 4 1282 36.807350 16: 12052 4

javascript - if div does not contain this class then execute following -

at moment have few div resize functions work on different page width queries. these working fine, want wrap of these functions different window widths in conditional statement.basically want functions resize div "portfoliopod" if div not contain class pod expanded. please see code below , live example at http://mrliger.com/index2.php you can see on live example image being clipped due having height of how portfoliopod before expanding it if ($( '.portfoliopod' ).not( ".podexpanded" )) { $(window).resize(function() { if ($(window).width() >= 1025) { var cw = $(".portfoliocontainer").width()/4; $('.portfoliopod').height(cw); } }); $(window).resize(function() { if ($(window).width() <= 1024) { var cw = $(".portfoliocontainer").width()/3; $('.portfoliopod').height(cw); } }); $(window).resize(function() { if ($(window).width() <= 767) { var cw = $

android - Using onUpGrade with multiple versions of App to add columns -

i have versions 4,5 out in production application. between 4 , 5 added new columns app's database adapter using alter statement: public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { //add new columns string alter = "alter table " + database_table + " add column " + key_newcolumn_name+ " integer default 0"; db.execsql(alter); } so, in next version (version 6) if wanted add new column. if had upgraded version 5, of course delete current onupgrade definition , change add new column. but, if user upgrading version 4 version 6? if leave both alter table statements, fine them, would create duplicate columns version 5 people ? running twice matter newer versions? my question basically, how around missing columns non upgraded people? you need make if statement each number if(oldversion < 5) ... sql alter statement first new column ... if(oldversion < 6) ... next

c++ - boost asio exception: use_private_key_file: key values mismatch -

i'm using example server boost asio , , i'm failing run , getting error, exception: use_private_key_file: key values mismatch i'm changing absolutely nothing in program, except keys , port. i'm willing use own key authority, , seems there's problem in library, it's not excluded doing fundamentally wrong, please assist. in program, use following lines keys: context_.use_certificate_chain_file("../sslkeys/server.crt"); context_.use_private_key_file("../sslkeys/server.key", boost::asio::ssl::context::pem); context_.use_tmp_dh_file("../sslkeys/dh512.pem"); and create these keys, following: 1- create certificate authority (ca) openssl genrsa -aes256 -out ca.key 4096 openssl req -new -x509 -extensions v3_ca -key ca.key -out ca.crt -days 36500 2- create server key , sign authority key openssl genrsa -des3 -out server.key 2048 openssl x509 -req -days 3650 -in server.csr -signkey ../sslca/ca.key -out server.crt cp

Bootstrap tooltip on exceeding textbox maxlength -

i have textbox allows maximum of 40 characters entered.when user tries enter 41th character ,i need display bootstrap tooltip (not on focus or hover).i struggling , not able it.please help. have created jsfiddle that http://jsfiddle.net/vijay4225/gjlusomk/ $(document).ready(function(){ $('#textbox').keyup(function() { var text_length = $('#textbox').val().length; if(text_length ==40) { $('#textbox').attr('title','you cannot enter more 40 characters'); $('input[rel="txttooltip"]').tooltip(); } }); }); you need set tooltip trigger manual , i.e data-trigger="manual" , show tooltip manually tooltip('show') . besides that, think keydown better event task - tooltip should appear user hits keybord, not when user has stopped typing. suggest implement logic prevent tooltip blinking or reappear if shown. $('#textbox').keydown(function() { if ($(this).val().len

python - hashes memory usage is higher than instagram test result -

hi new redis , following instagram engineering blog optimization purpose.i tested memory usage 1 milion keys storage through hashes(1000 hashes having 1000 keys each).according instagram post here it took 16mb of storage space test took 38mb.can tell me going wrong? here test code: # -*- coding: utf-8 -*- import redis #pool=redis.connectionpool(host=127.0.0.1,port=6379,db=4) num_entries=1000000 max_val=12000000 def createdata(min,max,userid): r_server=redis.redis(host='localhost',port=6379,db=5) p=r_server.pipeline() in xrange(0,1000): j in xrange(0,1000): p.hset('follower:%s' % (i),j,j) p.execute() size = int(r_server.info()['used_memory']) print '%s bytes, %s mb' % (size, size / 1024 / 1024) redis info : # server redis_version:2.8.9 redis_git_sha1:00000000 redis_git_dirty:0 redis_build_id:a9b5dff7da49156c redis_mode:standalone os:linux 3.19.0-15-generic

android - Send HTML e-mail with Intent -

i want send html e-mail when user decides share app. i'm using html in order have customised , appellative message. first approach, tried create string html (inline style) using html.fromhtml when received e-mail pure txt, no customization. second approach, send html file attached. problem approach html not showed until user opens attach. what's best solution, possible? thanks! you can achieve task using method html.fromhtml(string); html.fromhtml("<font color='#ff123456'>text</font>")

Are static global pointers always initialized to NULL in C? -

this question has answer here: static pointer default value in c/c++ [duplicate] 2 answers i learnt global variables initialized '0'. per if declare below line globally, static char *pointer; pointer should equal null. true? because in current project, initialized pointer this. when compared pointer == null, becoming false , assigned value. junk address? all objects static storage duration (global or not) implicitly initialized 0 or null if no explicit initializer given. chapter , verse : 6.7.9 initialization ... 10 if object has automatic storage duration not initialized explicitly, value indeterminate. if object has static or thread storage duration not initialized explicitly, then: — if has pointer type, initialized null pointer; — if has arithmetic type, initialized (positive or unsigned) zero; — if aggregate, every member initia

php - why (int) ( 307.03 * 100) = 30702 -

this question has answer here: is floating point math broken? 20 answers today coworker stumbled on this: $s = floatval("307.03"); $s = $s * 100; echo intval($s); //30702 float value or round($s) return 30703 expected. i guess it's problem connected float int approximation why happen ? the float val stored 307.02999 or intval truncate number, no rounding, hence 30702.

ruby - Writing file with multiple Chef cookbooks all targeting the same file -

i have situation have 3 cookbooks, each template resource writes /etc/hosts file. rather overwriting, append: the first cookbook creates /etc/hosts file , writes lines 1,2,3. the second cookbook appends lines 4,5. etc. what's right way handle in chef land? you should better create cookbook managing file generate attributes. cookbooka/attributes/default.rb default['hosts']['lines'] = [] cookbooka/recipes/genfile.rb template "/etc/hosts" source "hosts.erb" end cookbooka/templates/default/hosts.erb #file generated chef <% node['hosts']['lines'].each |l| %> <% l -%> <% end.unless node['hosts']['lines'].empty? %> and in other cookbooks attributes files: default['hosts']['lines'] << ["first line","second line"] and have thoose cookbooks depends on cookbooka , in recipe call include_recipe "cookbooka::genfile.rb"

javascript - How to wireup an AngularStrap modal show event -

i have modal displaying fine. i'm trying figure out how run function when modal shown. var = loginmodal = $modal({ placement: 'left', title: '', content: webauth, show: false }); $scope.$on('modal.show', function () { console.log("shown"); debugger; }); $scope.showmodal = function () { loginmodal.$promise .then(loginmodal.show); }; i expecting $scope.$on('modal.show') fire when modal shown, no luck far. try this: $scope.showmodal = function() { mymodal.$promise.then(mymodal.show).then(function(){ console.info('shown'); }); };

javascript - Projecting a point onto a path -

Image
suppose have ordered array containing points (lat, lon) describing path, , have point (lat, lon) describing current location. how can project point onto path (and place point in appropriate place in array)? what tried searching nearest 2 points , assume it's in middle of them. it's guess, fails. what way of doing this? i see this: p0,p1 path line segment endpoints p position q' closest point on line in 3d cartessian q q' corrected spherical projection so: convert points 3d cartessian coordinates compute perpendicular distance point , line q'=p0+(dot(p-p0,p1-p0)*(p1-p0)/(|p-p0|*|p1-p0|)) perpendicular_distance = |p-q'| find segment smallest perpendicular_distance and use rest of bullets compute q if use sphere instead of ellipsoid know radius if not either compute radius algebraically or use average: r=0.5*(|p0-(0,0,0)|+|p1-(0,0,0)|) assuming (0,0,0) earth's center. can more precise if weight position

c# - How do I remove elements from a table? -

allow me explain situation. i have table in database represented in model by public table<linkdate> dates; [table(name = "dates")] public class linkdate { public linkdate() { } [column(isprimarykey = true)] public string linkguid { get; set; } [column] public datetime dtime { get; set; } } which records day/time ids generated. these ids associated 1 or more files in table represented [table( name = "links")] public class assetlink { public assetlink() { } [column(isprimarykey = true, isdbgenerated = true)] public int linkid { get; set; } [column] public string linkguid { get; set; } [column] public int fileid { get; set; } } i'm adding functionality in web application user can delete links on number of days old. means if such links exist, deleting rows both links , dates . the action i've started create is [httppost] pub

azure - Newly created VMs from gallery image stuck in "Running (Provisioning)" or "Running (Provisioning Timed Out)" -

Image
i'm trying evaluate azure possible platform move our servers to, hasn't gone well. alas, i'm in "free trial" mode can't technical support :( i'm trying create vms using "openlogic 6.6" standard image. created 2 through gui - 1 basic_a1 , 1 basic_a0. basic_a0 succeeded, other 1 never finished provisioning , never available. deleted , tried again, same result. i found out afterwards can't used reserved ips on vm post-creation, killed both , started over. got powershell script work create them...however, both spinning in "running (provisioning)", they've been time. expect them time out. neither reachable @ public ip either. are things not working now? check provisioning events see if went wrong. @ portal.azure.com open vm blade, , click events tile , check operations errors. then then click rows check events.

how to extract data from a file in java and format it properly -

i trying extract data file , calculate totals of persons income. file looks exactly: mark 20 mike 25 mary 50 mink 5 the has this: who total1 total2 total3 mark - - - mike - - - mary - - - mink - - - combined total total 3: average total 3: the "-" lines data show when program calculates it. if first total >10, total multiplied 10. 2nd , 3rd same multiplied 20 , 30 respectively. how can take data file , calculate format shown above? wrote out of code 1 calculation test out, doesn't seem working right. getting several error messages on line of code: error: illegal start of expression public static void calc(double totalone) code: import java.util.scanner; import java.io.*; public class income { public static void main(string[] args) throws ioexception { scanner keyboard = new scanner(system.in); int = 0; string name = keyboard.nextline(); fil

PDF Form cannot be saved in LiveCycle HTML Workspace ES4 when file exceeds certain file size -

i have pdf form in livecycle html workspace es4 allows users add file attachments , images (via image fields). if these attachments and/or images total more 1.8 mb , "save" button pressed in workspace "error - message: null" prompt shown , form not saved draft folder. the following exception thrown: 2015-06-16 12:17:06,055 error [org.jboss.ejb.plugins.loginterceptor] (http-0.0.0.0-8080-7) runtimeexception in method: public abstract java.lang.object com.adobe.idp.dsc.transaction.impl.ejb.adapter.ejbtransactioncmtadapterlocal.dosupports(com.adobe.idp.dsc.transaction.transactiondefinition,com.adobe.idp.dsc.transaction.transactioncallback) throws com.adobe.idp.dsc.dscexception: java.lang.numberformatexception: null @ java.lang.long.parselong(long.java:404) @ java.lang.long.parselong(long.java:483) @ com.adobe.livecycle.processmanagement.services.impl.processmanagementtaskserviceimpl.save(processmanagementtaskserviceimpl.java:1622) @ sun.reflect.n

jquery mobile - JQM/knockoutJS component popup doesn't bind data? -

i have simple popup want use in components. doesn't bind data on popup, in other parts of components does? viewmodel ko.components.register('customer-search', { viewmodel: function(){ var self = this; //data self.search= ko.observable(); self.list= ko.observablearray([{supcode:"cho024",supname:"supplier"}]); self.next= ko.observable(); self.prev= ko.observable(); self.testtext= ko.observable('test'); //general vars ko.bindinghandlers.applyjquerymobilestuff = { init: function(elem) { $(elem).trigger("create"); } } }, template: '<div class="customer-search" data-bind="applyjquerymobilestuff: true">\ <input type="text" data-bind="value: testtext"/><br>\ \ <a href="#popupsearch1" data-rel="popup" data-position-to="window" data-

operators - What is the difference between Python's __add__ and __concat__? -

the list of python's standard operators includes both __add__(a, b) , __concat__(a, b) . both of them invoked a + b . question is, difference between them? there scenario 1 used rather other? there reason define both on single object? here's documentation found methods mentioned in. edit: adding weirdness documentation : finally, sequence types should implement addition (meaning concatenation) , multiplication (meaning repetition) defining methods __add__() , __radd__() , __iadd__() , __mul__() , __rmul__() , __imul__() described below; should not define __coerce__() or other numerical operators. if check source operator module ( add , concat ), find these definitions functions: def add(a, b): "same + b." return + b def concat(a, b): "same + b, , b sequences." if not hasattr(a, '__getitem__'): msg = "'%s' object can't concatenated" % type(a).__name__ raise typeerror

asp.net mvc 4 - MVC 4 - pass parameter to controller on button click -

i have mvc 4 project has save button when clicked asks user confirm , submits whole form controller model input, not formcollection. need add button form called submit. how can pass parameter differentiate between save , submit? i'd continue using jquery function confirmation. here code snippets: javascript function saveplan() { if (validateamounts() != true) { var message = "do want save? "; createconfirmationmessage(message, '$("#form_fiscalyearplanning").submit();'); return; } } jquery function createconfirmationmessage(message, confirmactiontotake, cancelactiontotake) { $('#project_confirmationquestion').html(message); if (confirmactiontotake !== null) { $('#button_confirmationaccept').attr('onclick', confirmactiontotake); } else { $('#button_confirmationaccept').removeattr('onclick'); } if (cancelactiontotake !==

github - git branch - local or what? -

i ran following commands: (we have staging branch called "master_next") (1) git fetch origin (2) git checkout -b origin/master_next now, when run (3) git branch i see weird stuff. instead of seeing master master_next i see master origin/master_next why branch checked out preceded "origin" - somehow different? here exact results: cacsvml-13295:smartconnect amills001c$ git fetch origin http://github.csv.comcast.com/baymax/smartconnect * [new branch] master_next -> origin/master_next * [new tag] 0.0.2 -> 0.0.2 * [new tag] 0.0.3 -> 0.0.3 cacsvml-13295:smartconnect amills001c$ git checkout -b origin/master_next switched new branch 'origin/master_next' cacsvml-13295:smartconnect amills001c$ git branch master * origin/master_next //wth? can explain why happened , how origin/master_next might different plain-old master_next? the problem in command: git checkout -b origin/master_

php - server sent events while loop takes so much time for page load, when page is refreshed or F5 is pressed -

i using server sent events query database new records , display events user here code javascript window.onload = function setdatasource() { if (!!window.eventsource) { var source = new eventsource("polling.php"); source.addeventlistener("message", function(e) { console.log(e.data); }, false); source.addeventlistener("open", function(e) { console.log("opened"); }, false); source.addeventlistener("error", function(e) { console.log(e); if (e.readystate == eventsource.closed) { console.log("closed"); } }, false); } else {}} php <?php header("content-type: text/event-stream\n\n"); include_once dirname(__file__) . '/db.php'; session_start(); while (1) { $response = getnewmessages(); echo 'data: message '. json_encode1($response)."\n\n"; ob_flush(); flush(); sleep(5); } function getnewmessages () { // query database , new records.