Posts

Showing posts from March, 2011

sockets - Android using TCP between 2 simulators -

i have 2 apps tcp server , client app. have use redir add tcp:5000:6000 client talk server. if try load apps on 2 actual devices client fails because can't connect. how can 2 apps on 2 different devices talk each other simulator? i'm using tcp tcp example app in client.java file change following 2 lines... private static final int serverport = 5000; private static final string server_ip = "10.0.2.2"; serverport needs same number in server.java file, i.e., 6000. server_ip needs actual ip address of android device running server app.

Configuring wamp mysql to use innodb not working - error 123 -

i in error log (wamp): 140205 22:57:41 innodb: operating system error number 123 in file operation. innodb: operating system error numbers described @ innodb: http://dev.mysql.com/doc/refman/5.1/en/operating-system-error-codes.html innodb: file name c:\wampin\mysql\mysql5.5.8\data\ibdata1 innodb: file operation call: 'create'. innodb: cannot continue operation. i don't understand else have uncommented commands , changed paths appropriately: # uncomment following if using innodb tables innodb_data_home_dir = c:\wamp\bin\mysql\mysql5.5.8\data/ innodb_data_file_path = ibdata1:10m:autoextend innodb_log_group_home_dir = c:\wamp\bin\mysql\mysql5.5.8\data/ innodb_log_arch_dir = c:\wamp\bin\mysql\mysql5.5.8\data/ # can set .._buffer_pool_size 50 - 80 % # of ram beware of setting memory usage high innodb_buffer_pool_size = 50m innodb_additional_mem_pool_size = 10m # set .._log_file_size 25 % of buffer pool size innodb_log_file_size = 50m innodb_log_buffer_size = 80m innod

java - Methods of custom-implementation of TargetDataLine aren't invoked -

i tried work javax.sound.sampled-package. i tried implementing own version of targetdataline (for test purposes @ point). dismay, however, when done , tried "play" it, neither 1 of it's methods invoked (nor exceptions raised), instead, program froze. the code segment in question looks this: try { // create stream. assembleddataline line = new assembleddataline(); audioinputstream stream = new audioinputstream(line); // create content. int size = 65536; byte[] array = new byte[size]; byte inc = 1; byte pos = (byte) 0; (int = 0; < size; ++i) { array[i] = (pos += inc); if (pos == 127) { inc = -1; } else if (pos == -128) { inc = 1; } } line.writearray(array); // play. system.out.println("starting play."); clip clip = audiosystem.getclip(); clip.loop(clip.loop_continuously); system.out.println("got clip"); clip.open(stream); system.out.println("opened"); clip.start();

Bash script that creates a bash script with variables -

i'm writing bash called "newproject" creates second bash script called "compile". both scripts must able take arguments input. problem can not write "$1" compile script - copies contents of newproject's first argument compile script. part of newproject script creates compile script. echo "#!/bin/bash" > $1/compile echo " if [[ -z '$1' ]]; echo "you missing file names. type in: compile -o executable files." exit 1 fi" >> $1/compile chmod u+x $1/compile and here output test run of newproject script. #!/bin/bash if [[ -z 'testproject4' ]]; echo missing file names. type in: compile -o executable files. exit 1 fi how can change newproject script instead of 'testproject4' , compile script contains '$1' ? i use heredoc cat <<'end' > "$1"/compile #!/bin/bash if [[ -z $1 ]]; echo "you

javascript - Referring to non-widget objects in Dojo without "polluting" global namespace -

what's clean best practice keeping track of , referring general javascript objects - dojo-declared - may have been declared in 1 area (read module) of application need used in area? we're assuming amd here. as mentioned "non-widgets" section of dojo's "using declarative syntax" reference guide : ... regular objects don't have registry dijit based widgets do, therefore in order able reference them after instantiate them, have create reference them in global scope. global scope? rrraaughh?! 1 of biggest things "modern dojo" frowning upon willy-nilly usage of global namespace: one of core concepts of "modern" dojo things in global namespace bad. there numerous reasons this, in complex web application, global namespace can become polluted manner of code [...]. means in "modern" dojo, if access in global namespace stop because doing wrong. also, guide: again, repeat after me "the global names

java - Gson gives "unchecked conversion" warning -

i trying convert json strings objects this: string jsonstring = "[\"string1\", \"string2\"]"; gson gson = new gson(); list<string> list = gson.fromjson(jsonstring, list.class); there warning: warning: [unchecked] unchecked conversion list = gson.fromjson(jsonstring, list.class); ^ required: list<string> found: list i tried use list<string>.class instead of list.class compile time error saying can't that... how can rid of warning? you can use array string[] array = gson.fromjson(jsonstring, string[].class); or using typetoken type listtype = new typetoken<arraylist<string>>() {}.gettype(); list<string> list = gson.fromjson(jsonstring, listtype);

Java how to return two variables? -

this question has answer here: how return multiple objects java method? 25 answers after c++ trying learn java, , have question code have been working on. working on fraction class , got stuck in reduce section. since method did not let me return both "num" , "den", had return "n" method public double reduce() { int n = num; int d = den; while (d != 0) { int t = d; d = n % d; n = t; } int gcd = n; num /= gcd; //num = num / greatestcommondivisor den /= gcd; //den = den / greatestcommondivisor return n; } i trying "return num, den;" not let me. and to reduced test 100/2 2.0 reduced test 6/2 2.0 when run system.out.println("to reduced test " + f4.tostring() + " " + f4.reduce()); system.out.println("to reduced test " + f6.tostri

Python, memory error, csv file too large -

this question has answer here: reading huge .csv file 5 answers i have problem python module cannot handle importing big datafile (the file targets.csv weights 1 gb) the error appens when line loaded: targets = [(name, float(x), float(y), float(z), float(bg)) name, x, y, z, bg in csv.reader(open('targets.csv'))] traceback: traceback (most recent call last): file "c:\users\gary\documents\epson studies\colors_text_d65.py", line 41, in <module> name, x, y, z, bg in csv.reader(open('targets.csv'))] memoryerror i wondering if there's way open file targets.csv line line? , wondering slow down process? this module pretty slow... thanks! import geometry import csv import numpy np import random import cv2 s = 0 img = cv2.imread("map.tif", -1) height, width = img.shape pixx = height * width iter

javascript - Trouble passing custom headers in a CORS GET request using jquery -

i wrote web api need accessed outside of app domain. have cors enabled , i'm able make api call outside application domain. i'm trying pass in custom http headers part of request i'm not able working i searched in web working unable to. i'm trying pass in 2 parameters appid custom header on request web api call using jquery $.ajax. url: "http://localhost:38994/api/search/getsearchresults", type: 'get', datatype: 'json', headers: { 'appid': '234' }, data: { param1: 1, param2: { search_by_param: 'xyz', category: 'null'}}, success: function (result) { alert(result); } , error: function (err) { alert(err); } i tried use beforesend add headers well. regardless use 'headers' or beforese

android:path, Prefix, Pattern url parser -

i know there couple question can't find answer , it's annoying docs don't have couple of examples. better if link me guide. actual problem following: what should [<path>|<pathprefix>|<pathpattern>] in order start activity on: http://www.example.com/e=variable e.g. http://www.example.com/e=foo http://www.example.com/e=bar481 i have tried: <data android:host="www.example.com" android:pathpattern="./e=.*" android:scheme="http" /> and <data android:host="www.example.com" android:pathpattern="/e=.*" android:scheme="http" /> also, tried in position of android:pathpattern , path , pathprefix . i assume can use foo , bar481 based on second part here i'm still struggling starting intent. docs: http://developer.android.com/guide/topics/manifest/data-element.html solved with: <data android:scheme="http" /> <d

javascript - How do I make a <ul> or bullet in fabric.Text()? -

i looking example application takes user input , inserts inside canvas fabric.js. possible? haven't been able find lists in fabric.js example. canvas.filltext not accept html markup. canvas bitmap, has nothing html markup. can control font style described here . there libraries convert xml markup canvas.filltext calls, maybe adapt one.

php foreach loop only display the first letter of array -

$item= "stackoverflow"; $price = "30.00"; $cs1_array = array(); $cs1_array['item'] = $item; $cs1_array['price'] = $price; if($cs1_array > 0){ echo "<table>"; foreach ($cs1_array $item){ echo "<tr>"; echo "<td>{$item['item']}</td><td>{$item['price']}</td>"; echo "</tr>"; } echo "</table>"; } this output first alphabet of array only. example display letter s of stackoverflow. want display whole stackoverflow word, how so? you did create single level array, while need multidimensional array (i.e. array in array): $cs1_array = array(); $cs1_array[] = array( 'item' => $item, 'price' => $price ); compare this: // wrong array(2) { ["item"]=> string(13) "stackover

r - how to get and modify size legend in ggplot2 -

Image
i having trouble displaying size legend in plot , changing name of size legend. my data corp has size column either of values 5, 10, 20 i using ggplot2 have legend color i want add 1 size , manually change size labels.. how increase the font of legend ? it's super tiny (fin, ind util) 15 size shouldnt there want omit , display both legends side side. p <- ggplot(corp, aes(x=annrisk, y=annret, color = corp$subsector1, face = "bold")) p<- p + geom_point(aes(size = corp$colsize), alpha = 0.55) p<-p + scale_size(range = c(8, 20)) p<-p + scale_colour_manual("", values = c("util" = "#fdcc8b", "ind" = "#fc8d59", "fin" = "#d7301f", "abs" = "#74a9cf", "cmbs" = "#0570b0", "la" = "#8c96c6", "sov"= "#88419d", "supra" = "#b3cde3")) p<-p+labs(title = "some title") print(p

broadcastreceiver - Android receiver cannot always get broadcast correctly -

i have package added receiver in android application, , has been distributed couple months. recently found not package_added broadcasts can received receiver. looked while, said if app had been killed users or system, no longer broadcasts. my questions are: is true? confirmed, if terminate app settings->applications --> force stop application wont receive broadcast. how can prevent happening, or there work around? 1.yes true. 2.take @ wakefulbroadcastreceiver wake when receives intent. make sure spawn eg. intentservice process work in background. take @ commonsware's wakefulintentservice implementation example.

java - I cannot find the error -

i following tutorial here , have been trying working 2 days now. error message when compiling filedata. filedata.java:13: error: cannot find symbol readfile file = new readfile(file_name); ^ symbol: class readfile location: class filedata filedata.java:13: error: cannot find symbol readfile file = new readfile(file_name); ^ symbol: class readfile location: class filedata any assistance appreciated. the code follows: package textfiles; import java.io.ioexception; public class filedata { public static void main(string[] args) throws ioexception { string file_name = "c:/test.txt"; try { readfile file = new readfile(file_name); string[] arylines = file.openfile(); int i; (i=0; < arylines.length; i++) { system.out.println(arylines[i]); } } catch (ioex

c# - Why should I inherit? -

sorry if foolish question, m confuced namespace test { public class class1 { public string property1 { get; set; } public void method1() { } } public class class2 : class1 { public void method2() { property1 = "set class2"; method1(); } } public class class3 { class1 objclass1 = new class1(); public void method3() { objclass1.property1 = "set class3"; objclass1.method1(); } } } if can access public methods of class1 class3 using object of class1, s advantage of inheritance (as done in class2) ? in oops, concept of inheritance provides idea of reusability. means can add additional features existing class without modifying it. possible deriving new class existing one. new class have combined features of both classes. once behavior (method) or property defined in super clas

javascript - Passing callback function as parameter -

i calling function below. here passing callback function should called after particular form submit not before that. <div onclick="mynamespace.opendialog(par1,par2,mynamespace.callback(mynamespace.cb,'p1','p2'))">open dialog</div> var mynamespace = mynamespace || {}; mynamespace={ return{ cb:function(p1,p2){alert(p1+" cb "+p2);}, callback:function(f){f(arguments[1],arguments[2]);}, opendialog:function(p1,p2,f){ // aboutbizzns.cb should called here after form submit } } }(); the problem alert(p1+" cb "+p2); called after open dialog clicked. should not that. should called when want. problem the problem aboutbizzns.callback immediately invokes function supplied argument. compare following creates , returns closure (function) invoke function supplied when iself invoked: callback: function(f){ // f variable bound in closure below, returned immed

c# - Excel: Values from Ranges With Multiple Areas -

i values of non contiguous, multi area range in excel using c#. have seen another question says can this: obj[,] data = sheet.get_range("b4:k4,b5:k5").get_value(); however, when examine result see data first area: "b4:k4" . testing further, found if request data in following way: obj[,] data = sheet.get_range( "b4:k4","b5:k5").get_value(); i data both areas... so, question is, there way programmatically combine area addresses such "b4:k4,b5:k5" in order of data refer? thanks the solution came isn't elegant have liked trick nonetheless: public list<list<object>> getnoncontiguousrowvalue(excel.worksheet ws, string noncontiguous_address) { var addresses = noncontiguous_address.split(','); // e.g. "a1:d1,a4:d4" var row_data = new list<list<object>>(); // value of 1 row @ time: foreach (var addr in addresses) { object[,] arr = ws.get_r

accumulo, zookeeper hadoop Installation instructions, downloads and versions for CENTOS 6 -

i appreciate guidance on accumulo, zookeeper hadoop installation instructions, downloads , versions centos 6. thanks, chris you can installation via cloudera manager version 5. installed accumulo using same. here link cloudera manager 5. you can use this youtube video reference.

javascript - How to display uploaded image using ajax? -

i need upload image , display image without reloading page how can implement this. think can using ajax form submission. tried following code ajax form submit function not working. there mistake in code tell me how implement <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#myform').ajaxform(function() { alert("thank comment!"); }); }); </script> <body> <form id="myform" action="" method="post"> <input type="file" name="image_name" id="image_name" > </form> </body> thank :-) si

c# - Converting XSL-FO to HTML -

i have set of xsl-fo documents used pdf generation. have requirement same output data (which in pdf) exported html file. further, need html have similar styles in pdf. is there way convert xsl-fo xhtml using c#? note : know 1 option use "renderx:fo2html" . since it's commercial product, learn other options available , comparison before continuing further. i use renderx fo2html stylesheet lot, , recommend customers because 0 cost. have built number of client solutions. have go through renderx online store it, costs nothing.

c# - In Button Click Context Menu How do I bind to viewModel? -

i have button on click on button opening context menu, clicking on context menus binded viewmodel. not happening. <button content="copy" tag="{binding linkviewmodel, relativesource={relativesource mode=self}}" command="{binding linkcopycommand, updatesourcetrigger=propertychanged}" > <button.contextmenu> <contextmenu> <menuitem header="copy download link " command="{binding path=parent.placementtarget.tag.copyviewcommand, relativesource={relativesource mode=findancestor, ancestortype=contextmenu}}" /> <menuitem ... /> </contextmenu> </button.contextmenu> </button> i have tried tag property seems me not working. viewmodel working fine if bind button itself, contextmenu databinding not working. edit: now code working after discussion, think post here. what changes made put updatesourcetrigger="propertychanged" here code

PHP 5.5 php.ini - how configure to show all error messages -

i want made aware of php errors - below php.ini config this. advice on potential changes ensure i'm make aware of issues: display_errors = on ; default value: on ; development value: on ; production value: off display_startup_errors = on ; default value: off ; development value: on ; production value: off error_reporting = e_all ; default value: e_all & ~e_notice & ~e_strict & ~e_deprecated ; development value: e_all ; production value: e_all & ~e_deprecated & ~e_strict html_errors = on ; default value: on ; development value: on ; production value: on log_errors = on ; default value: off ; development value: on ; production value: on ; max_input_time ; default value: -1 (unlimited) ; development value: 60 (60 seconds) ; production value: 60 (60 seconds) ; output_buffering ; default value: off ; development value: 4096 ; production value: 4096 ; register_argc_argv ; default value: on ; development value

Maven compilation error while installation -

compilation error : error: error reading /root/.m2/repository/net/sf/ehcache/ehcache-core/2.4.3/ehcache-core-2.4.3.jar; error in opening zip file failed execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project edvie-ws-core: compilation failure error: error reading /root/.m2/repository/net/sf/ehcache/ehcache-core/2.4.3/ehcache-core-2.4.3.jar; error in opening zip file

ios - App crashing with exception: -[NSConcreteMutableData _fastCharacterContents] -

i trying share data facebook. able share data except image stored locally in iphone memory. when try share image stored locally parameter @"source" app gets terminated error "[nsconcretemutabledata _fastcharactercontents]". for sharing local image converting nsdata required @"source" parameter. nsdata *data = [nsdata datawithcontentsofurl:localurl]; __block acaccount *facebookaccount = nil; acaccounttype *facebookaccounttype = [self.accountstore accounttypewithaccounttypeidentifier:acaccounttypeidentifierfacebook]; // specify app id , permissions nsdictionary *options = @{ acfacebookappidkey: @"xxxxxxxxxxxxxx", acfacebookpermissionskey: @[@"email"], acfacebookaudiencekey: acfacebookaudienceeveryone }; // basic read permissions [self.accountstore requestaccesstoaccountswithtype:facebooka

groovy - Display 3 lists (java.util.List) -

i ask display 3 lists groovy. in fact have 3 lists (java.util.list) : first 4 checkboxes, second , third editable grids 1 column , 4 fields. saved in 3 differents variables java.util.list. i try display 3 lists in text field area loop : def out = [] (i=0; i<grids1.size();i++) { out.add([grids1.getat(i),checkboxes.getat(i),grids2.getat(i)]) } out but result pretty bad. [[[], checkboxes, []], [[2], checkboxes, [grids2]], [[], null, []], [[3], null, [grids2]], [[], null, []]] could me ? more info answer below: thanks. not in dark because it's that! have gap between each data. example : 3 lists 4 fields each. def = [ [], [2], [], [4] ] def b = [ '', 'two', '', 'four' ] def c = [ [], [6], [], [8] ] it display that, lag (maybe because lists a , c keep index counter b list. [[], two, []] [[2], four, [6]] [[], , [], []] [[4], , [], [8]] the list , b keep "positions" opposed list b. without knowing

python - pdfminer/poppler - how to set encoding -

i have file, i.e. http://www.agfl.cs.ru.nl/papers/manual28.pdf (it's english) pdfminer , poppler shows same result in parsed pages, like: ¾º¿  ÒÙ Öݸ ¾¼¼ Ⱥ ¾º ÂÙÒ ¸ ¾¼¼ ź Ë ÙØØ Ö¸ Ǻ Ë it seems can't read font custom encodings. how specify it? here's code samples: # poppler input_filename = '/tmp/manual28.pdf' document = poppler.document_new_from_file('file://%s' % urllib.pathname2url(os.path.abspath(input_filename)), none) n_pages = document.get_n_pages() in range(n_pages): page = document.get_page(i) print page.get_text() # chardet.detect(page.get_text()) # utf8 time # pdfminer def pdf_to_html(in_fp, out_fp, codec='utf-8', maxpages=0, pagenos=none, html=true): rsrcmgr = pdfresourcemanager() laparams = laparams() if isinstance(in_fp, basestring): in_fp = open(in_fp, 'rb') if isinstance(out_fp, basestring): out_fp = open(out_fp, 'wb') if html: device = htmlco

Convert Curl command line in Rails -

this curl command works nicely in command line : curl --data @order_new.json \ -h "x-augury-token:my_token_goes_here" \ -h "content-type:application/json" \ http://staging.hub.spreecommerce.com/api/stores/store_id_goes_here/messages i need implement same in rails using sort of gem, tried httparty /rest_client / spree-api-client, wrong here : require 'httparty' result = httparty.post( "http://staging.hub.spreecommerce.com/api/stores/52eb347f755b1c97e900001e/messages", :body => json.parse(file.read("order_new.json")), :header => { "x-augury-token" => "ujjksdxbrwjpapx9hiw4", "content-type" => "application/json" } ) but getting error, "the page looking doesn't exist (404)" i need rails equivalent of above curl command, use of spree-api-client gem helpful. if prefer use spree::api::cl

osx - Create dmg installer with $HOME/Application folder -

i have created script application installation root application folder (/application), i'm not able create same 1 user home folder $home/application (~/application). here script #!/bin/sh #http://stackoverflow.com/questions/96882/how-do-i-create-a-nice-looking-dmg-for-mac-os-x-using-command-line-tools set -o verbose #echo onset +o verbose #echo off # note: must run on mac app_name="xxx" out_mac=out/ dmg_path=${out_mac}${app_name}.dmg dmg_content_path=${out_mac}contents bundle_path=${dmg_content_path}/${app_name}.app #clean old dmg if exist rm -rf ${dmg_path} setfile -a b "${bundle_path}" hdiutil create -srcfolder ${dmg_content_path} -volname ${app_name} -fs hfs+ \ -fsargs "-c c=64,a=16,e=16" -format udrw -size 550m ${dmg_path}.temp.dmg device=$(hdiutil attach -readwrite -noverify -noautoopen "${dmg_path}".temp.dmg | \ egrep '^/dev/' | sed 1q | awk '{print $1}') osascript <<eot tell application "finder&

IOS RAM usage and Framework -

i working on ios , performances , have question! first, have implemented complete application native sdk. added source code in main bundle of application. then, have implemented same application 5 custom frameworks (.framework). have extracted source code independent application. example, have framework manages http requests (sending, getting response ...). finally, have examined ram used 2 applications. that, closed applications in background on iphone 5s. then, have launched each application version , have examined free ram. when compared 2 results, note when first application launched, free ram 272,39 mo (the second 1 closed). whereas, when second application launched, free ram 325,33 mo (the first 1 closed). to free memory. used method: vm_size_t freememory(void) { mach_port_t host_port = mach_host_self(); mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t); vm_size_t pagesize; vm_statistics_data_t vm_stat; host_page_siz

Mongodb projection returning a given position -

i trying simple return subarray of document. query is: db.mydocs.findone({_id:objectid("af7a85f758e338d762000012")},{'house.0.room.4.windows':1}); i want return value. empty structure. know $slice. far know, can't subarrays. mean: {'house':{'$slice':0}} work. don't know how house 0 , room 4. you'll have use chained $slice operators work: db.mydocs.findone( {_id:objectid("af7a85f758e338d762000012")}, {"house" : {$slice : [0,1]}, // house.0 "house.room" :{$slice : [3,1]}, // house.0.room.4 "house.room.windows" : 1}); // house.0.room.4.windows the resulting document this, i.e. arrays still arrays (which helpful when mapping typed languages): house : [ { room : [ { windows : foo } ] } ] from the documentation: tip : mongodb not support projections of portions of arrays except when using $elemmatch , $slice projection operators. p.s: find irritatin

php - Jquery language change - change include with jquery -

i have 1 question. not know if possible way maybe 1 can help. imagine have 2 definitions php files, languages defined. want change files click on flag. the aim of dont want refresh page want jquery. second thing whole structure load files div named contentwrapper. wondering creating copy of each file in language , click empty every wrapper , load files languages. i hope understand want do. i wanted load definition file 'flagclick' dont work. 100% server not reload definitions jquery via load. or maybe there still old definitions default file. can give me hints? thanks! see if help: bind js function 'flagclick', send ajax call corresponding php file, 'lang-en.php', 'lang-other.php'... load context json object. , use values json data replace text displayed.

c# - Retain dropdown values in gridview -

i have having grid use checkbox edit grid rows. on checkbox click how can retain dropdown values? <columns> <asp:templatefield> <headertemplate> <asp:checkbox id="chkall" runat="server" autopostback="true" oncheckedchanged="oncheckedchanged" /> </headertemplate> <itemtemplate> <asp:checkbox id="checkbox1" runat="server" autopostback="true" oncheckedchanged="oncheckedchanged" /> </itemtemplate> </asp:templatefield> <asp:templatefield headertext="scope"> <headerstyle horizontalalign="center" wrap="false" cssclass="header"> </headerstyle> <itemtemplate> <asp:label id="lblscope" runat="server" text='<%# bind("scope") %>'></asp:label> <asp:dropdownlist id="ddlcms" visib

ruby - Predicate method syntax -

i made class these methods: def promotion_available? promotion.present? end def promotion @promotion ||= promotionuser.user(@user.id).available.first end then, colleague removed promotion method, , changed predicate promotion_available? in way: def promotion_available? @promotion ||= promotionuser.user(@user.id).available.first end can set instance variable directly on predicate method? can predicate method return entire object instead of true / false (i think no, colleague says opposite)? can set instance variable directly on predicate method? yes, there's nothing wrong it. often. can predicate method return entire object instead of tre/false (i think no, colleague says opposite) yes, common. works if use idiomatic ruby truthiness checks. if obj.promotion_available? # if obj.promotion_available? == true # bad! remember, nil , false in ruby falsey values. else true. why returning object or nil works kinda returning true or false

JavaScript Error because of rendered velocity line-break -

i use javascript-code in velocity-template , it's not working! i read content template , want set js-variable, there line-breaks in content , following error: syntaxerror: unterminated string literal in rendered code there see error: var exampletext = 'this first line , second line.'; in original code written way: var exampletext = '$question.answer.data'; var regularpanels = new a.panel( { bodycontent: exampletext, collapsible: true, collapsed: true, headercontent: '$question.data' } ) .render('#regularpanels$counter$reserved-article-id.data$randomnamespace'); }); is there possibility ignore linebreak js-compilation, still show on complete rendered page? okay, solved of escapetool velocity. combined answer emiliocai it's following code works fine: <div id="example-text" style="display:none;"> <p>$escapetool.java($question.answer.data).replace("\n&qu

javascript - How can I call a function with user selected data? -

i'm having contacts array holding list of emails. generate div's using ng-repeat when user clicks on particular div call ng-click="foo($index)" var contacts=[somemail]; var userselectedcontact[]; $scope.foo=function(row) { userselectedcontact.push(contacts[row]); } the problem when add "|filter" in ng-repeat search , select particular contact. since filter creates array after filtering: when ever user selects contact foo($index) called, , adding other contact not selected user. i can understand since using $index different index in original contacts array before filter. so have stop using either filter (or) index find user selected contact. should do? there other way? how can call function user selected data ng-click="foo(someemail)" ? you can pass whole ng-repeat item ng-click function <div ng-repeat="item in items" ng-click="myfunction(item)"></div>

javascript - Getting all <input> inside the document -

how can display in console list of <input> tags inside html? i've tried use $('input') , $(':input') , or $('tbody input') of commands returns jquery.fn.jquery.init[<number>] . anyways, using google chrome. yet think wouldn't affect other browsers, of course ie exemption. $('input') correct approach. $(...) returns jquery object , jquery.fn.jquery.init[<number>] console's representation of such object. it means have array object , constructed function jquery.fn.jquery.init , <number> elements. that's normal , code works fine (at least in regard), $('input') correct approach. of course should make select elements after document loaded, explained jquery tutorial .

Magento : Display all products with their Categories on Home Page -

Image
i need display products assigned categories on home page of website below. category category b category c ---------- ----------- ---------- product product b product c in cms > home page > content section have included block {{block type="catalog/product_list" name="homeproduct_list" template="catalog/product/list.phtml"}} here catalog/product/list.phtml default magento list.phtml without modifications. my products displayed on home page if assign product category default category (root category) for ex: product assigned default category (root) , categopry if assign product category (which want) not show products on home page. the issue here not 1 how display products in homepage? why have assign product default category (root) in order display on home page. thanks. because when have database table catalog_category_entity store category id first must root cate

java - Getting time out exception while accessing through HttpsUrlConnection -

i trying access website(for e.g https://www.yahoo.com ) through java code using eclipse ide, getting connection timeout exception. i've checked eclipse able connect internet , same website coming fine in eclipse internal browser , in chrome. the code given below public static void main(string[] args) throws exception { sslcontext sslctx = sslcontext.getinstance("ssl"); sslctx.init(null, new x509trustmanager[] { new mytrustmanager() }, null); httpsurlconnection.setdefaultsslsocketfactory(sslctx.getsocketfactory()); httpsurlconnection.setdefaulthostnameverifier(new hostnameverifier() { @override public boolean verify(string hostname, sslsession session) { return true; } }); url url = new url("https://www.yahoo.com"); httpsurlconnection con = (httpsurlconnection) url.openconnection(); con.setrequestmethod("get"); con.connect(); //getting exception here if (con.g

c# - DateTime shift to next predefined date -

say have list of valid scheduling days. like: 23, 27, 29 i want modify given date it's next valid day-month based on above list. if given date "23/11/2013" next valid date "27/11/2013" if given date "30/11/2013" has return "23/12/2013" , if given date "30/12/2013" has return "23/01/2014" i've done in sql, i'm translating c# , it's bit tricky. i'm trying using linq on list sql similarity, gets confusing. the sql statement (yes, know doesn't swift year): select top 1 @date = isnull(dateadd(yy, year(@date)-1900, dateadd(m, (month(@date)+case when datepart(day,@date)>[day] 1 else 0 end) - 1, [day] - 1)),@date) @days dateadd(yy, year(@date)-1900, dateadd(m, (month(@date)+case when datepart(day,@date)>[day] 1 else 0 end) - 1, [day] - 1))>=@date order [day] @days working table. i think you're looking (using linq): public static datetime nextdate(datetime seed, int[

apache pig - Changing the name of Hadoop job? -

hi change name of running hadoop job meaningful name. there command change name of running job, - hadoop job -set-priority <job_id> 'high'; changes priority of job the job id assigned job tracker on submit, calling jobtracker.getnewjobid() . cannot pre-set. change the job priority, must retrieve id submission. read comments on pig-948 why not possible know mr job id pig: reason jobcontrolcompiler compiles set of inter-dependent mr jobs , generates job-control object submitted asynchronously hadoop execution. since dont block on thread, possible job-ids not yet assigned when ask them

c++ - Is usage of Default parameters healthy habit or a bad one? -

when should use default parameters ? proper syntax , should not used? using them regularly or bad habit? affect efficiency? only case can think of affects efficiency when include big default parameter it's not used of callers. example: #include <iostream> void foo(std::ostream& out=std::cout) { out << "foo"; } if none of callers use default parameter, , rest of program doesn't need <iostream> have been included in vain, increasing executable size (and compilation time may or may not matter much).

c# - Why is an additional if statement to check if an event is null before invoking it? -

i going through code below: public delegate void personarrivedeventhandler(string personname, byte[] personid); public class sclib { public event personarrivedeventhandler personrrived; public sclib() { // simulate person arrived after 2000 milli-seconds. task.run(() => { system.threading.thread.sleep(2000); onpersonarrived("personname", new byte[] { 0x20, 0x21, 0x22 }); }); } protected virtual void onpersonarrived(string smartcardreadername, byte[] smartcardid) { if (this.personarrived != null) { personarrived(personname, personid); } } } but, don't know significance of line, if (this.personarrived != null) . why check done here? there significance of if statement here? removed line , ran program , works before. thanks. if event not subscribed con

nullpointerexception - Null Point Exception in Java -

i having weird problem in code, when execute code first if condition, works fine , excpected. however, when comment if statement , use other if condition (the 1 commented ), gives npe. both getuserip() , getphonenumber() normal getters private strings. , both values being set before normal setters. idea why happening ? thanks. public void sendbroadcast(final string broadcast) { system.out.println("entered sendbroadcast"); string fullpeep=broadcast; system.out.println("fullpeep: "+fullpeep); string array[] = fullpeep.split("<!!>"); for(user tempuser: friends) { if(tempuser.getuserip().equals(this.getuserip())) { system.out.println("tempuser:" +tempuser.getphonenumber() + " user: "+array[1] ); //if(tempuser.getphonenumber().equals(array[1])) //{ system.out.println("tempuser:" +tempuser.getphon

javascript - addclass() working in console but not working in script -

i have created div dynamically. tried add class expanded through jquery not working. tried code in console, working fine there. code follows: appending element name var menuid= '#itemmenu' + indexofelement; and tried this $(menuid).addclass('expanded'); when tried folllowing in console e.g. $('#itemmenu5').addclass('expanded') its working fine.. var menuid= 'itemmenu' + indexofelement; var element = document.getelementbyid(menuid); element.classname += ' expanded'; //note space

xml - How to add <p> tags around text nodes using XSLT -

i have following xml document <body> <h2>title</h2> text , <a href="link">link</a> here. </body> i want transform using xslt into: <body> <h2>title</h2> <p>some text , <a href="link">link</a> here.</p> </body> therefore tried following xslt: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output omit-xml-declaration="yes" method="xml" cdata-section-elements="script"/> <xsl:template match="/ | node() | @*"> <xsl:copy> <xsl:apply-templates select="node() | @*"/> </xsl:copy> </xsl:template> <xsl:template match="body/text()" > <p><xsl:copy/></p> </xsl:template> </xsl:stylesheet> but doesn't seem give expected result (it works fine if text no

excel - Force format of data input by user as text -

Image
i have excel sheet user can enter data several cells. want data treated strings, regardless if user enters "hello" or "123" or "12.12.2012". i partially resolve issue formatting input cells "text". if user enters number such "123" or string looks date ("12.12.2012"), appears small green rectangle , excel says number stored text, that's want. same thing text "1.2.90" in cell a5 seen excel "date stored text". text "aa" in cell a4 ok. when click on exclamation mark icon, can choose ignore "error", removes green triangle, change content of cell putting number, green triangle appears again. green field formatted "text" is there way force excel leave data entered string ? non vba version you can switch off error tracking file tab. read it, check ms link . vba version to using vba, need switch off backgroundchecking using application.errorcheckingopti

r - How to find F and p-value in Linear Mixed models -

i still not familiar r , construct linear model of mixed effects using lmer function. have 3 independent variables 2 modalities each time: group (g3 , g5) frequency (lf , hf) conditions (nr , ph) and 1 dependent variable: reaction time (rt). here sample of data, extract of data manipfreq : subject group item rt frequency condition 502 g3 argent 677 hf nr 502 g3 action 814 hf nr 502 g3 affaire 1278 hf nr 502 g3 armoire 716 lf ph 502 g3 aigle 761 lf ph 503 g3 affaire 841 hf ph 503 g3 argent 919 hf ph 503 g3 action 1071 hf ph 503 g3 aigle 1253 lf nr 505 g3 argent 785 hf ph 505 g3 affaire 1028 hf ph 505 g3 action 1190 hf ph 505 g3 aigle 1248 lf nr 506 g3 action 898 hf nr 506 g3 affaire 1566 hf nr 506 g3 argent 2037 hf nr 506 g3 aigle 707 lf ph 506 g3 armoire 839 lf ph 1530 g5 action 705 hf nr 1530 g5 argent 755 hf nr 1530 g5 affaire 789 hf nr 1530 g5 aigle 481 l

c - Which is the better Searching algorithm ?? -

i have 3 groups of items(names). group 1 has around 2,1k items, group 2 - around 7,6k , group 3 around 21k. need search in these groups. need hint better. thought either put in bin tree: gtree* t = g_tree_new((gcomparefunc)g_ascii_strcasecmp); , search this: goup = g_tree_lookup(t, (gpointer *)itemname); or more efficient make 3 arrays of strings: char g1[2300][14]; char g2[8000][14]; char g3[78000][14]; and search (not checked, pseudocode): int isvalueinarray(char val, char *g[][14];, int size){ int i; (i=0; < size; i++) { if (memcmp(val, g[i], strlenth) == 0) return true; } return false; } int group=0; if (isvalueinarray(itemname, g2, 7800) ) group = 2; if (isvalueinarray(itemname, g1, 2300) ) group = 1; or there better solution that? if want asymptotically efficient way of finding whether string in set of strings can pre-processed, can consider using a trie . construction

backbone.js - Backbone not to add a route to history -

i have route want able navigate in series. unfortunately backbone doesn't make possible navigate same route twice. is possible not save route history? i have route: app_router.on('route:deletefile', function(filename){ var r=confirm("do want delete "+filename); if (r==true) { //delete instruction } }); if don't accept confirm mistake, can't choose same file delete again. because route reached. one solution consist of navigating previous route when don't accept confirm, without triggering : app_router.on('route:deletefile', function(filename){ var r=confirm("do want delete "+filename); if (r==true) { //delete instruction } else { backbone.history.navigate(/* previous rout */, {trigger: false}); } });

String Tokenizing from file in android -

i have file stored in phone "savett.txt" . every word in file seperated spaces. wish retrieve each word file , display every word in seperate textviews. how this. please help i able retrieve contents of file string following code try { bufferedreader inputreader = new bufferedreader(new inputstreamreader( openfileinput("savett.txt"))); stringbuffer stringbuffer = new stringbuffer(); while ((inputstring = inputreader.readline()) != null) { stringbuffer.append(inputstring + "\n"); //edittext txt = (edittext) findviewbyid(r.id.temp); //txt.settext(inputstring); } } catch (ioexception e) { e.printstacktrace(); } with code entire string inputstring after . tokenizing string following code stringtokenizer tokenizer = new stringtokenizer(inputstring); string[] arr = new string[toke

javascript - How to run click event handler in Internet Explorer 10 using jquery? -

i'm trying run click event handler using jquery 1.7 clicking on anchor tag. this code working fine in firefox, i'm not able display alert box using same code in ie 10. please tell me how achieve functionality in internet explorer 10? $(document).ready(function() { $('.call-link').on('click', function (ev, evdata) { alert("hello world"); }); }); it not calling in ie because element disabled. see: demo $(document).ready(function() { $('.call-link').click(function (ev, evdata) { alert("hello world"); }); });

c++ - Setting up a MVP Matrix in OpenGL -

i'm trying learn basics of opengl, have problem setting transformation matrices. made model, view , projection matrices, have problem sending them vertex shader. here code: //set mvp glm::mat4 model = glm::mat4(); glint unimodel = glgetuniformlocation(program, "model"); gluniformmatrix4fv(unimodel, 1, gl_false, glm::value_ptr(model)); glm::mat4 view = glm::lookat( glm::vec3(2.5f, 2.5f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)); glint uniview = glgetuniformlocation(program, "view"); gluniformmatrix4fv(uniview, 1, gl_false, glm::value_ptr(view)); glm::mat4 proj = glm::perspective(45.0f, 800.0f / 600.0f, 1.0f, 10.0f); glint uniproj = glgetuniformlocation(program, "proj"); gluniformmatrix4fv(uniproj, 1, gl_false, glm::value_ptr(proj)); and shader: layout (location = 0) in vec3 position; uniform mat4 model; uniform mat4 view; uniform mat4 proj; void main() { gl_position = proj * view * model * vec4(posi

arcmap - Putting raster file with big extention in shapefile -

hello, have raster file huge extention values: top 2862682.68853 left -8067545.46588 right 17050954.5341 bottom -2862317.31147 spatial reference wgs_1984_mollweide liniar unit meter 1.00000 angular unit degree (0.017453292519943299) datum d_wgs_1984 and want fit in same projection shapefile geometry type: polygon projected coordinate system: wgs_1984_world_mercator projection: mercator false_easting: 0.00000000 false_northing: 0.00000000 central_meridian: 0.00000000 standard_parallel_1: 0.00000000 linear unit: meter geographic coordinate system: gcs_wgs_1984 datum: d_wgs_1984 prime meridian: greenwich angular unit: degree i have been trying batch in same projection nothing worked. know how can that?

c++ - Garbage values and Buffers differences in TCP -

first question : confused between buffers in tcp. trying explain proble, read documentation tcp buffer , author said lot tcp buffer, thats fine , explanation beginner. need know tcp buffer same buffer 1 use in our basic client server program ( char *buffer[some_size] ) or different buffer hold tcp internally ? my second question sending string data prefix length ( this data me ) client on socket server, when print data @ console along string prints garbage value "this data me zzzzzz 1/2 1/2....." ?. fixed right shifting char *recvbuf = new char[nlength>>3]; nlength 3 bits why need in way ? my third question in relevance first question if there nothing tcp buffer , char *buffer[some_size] whats difference program notice using such static memory allocation buffer , using dynamic memory allocation buffer using char *recvbuf = new char[nlength]; . in short best , why ? client code int bytessent; int bytesrecv = socket_error; char sendbuf[200] = "this