Search Results

Search found 461 results on 19 pages for 'parseint'.

Page 5/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Jasper report exports empty data in PDF format when there is more data

    - by stanley
    I have a report to be exported in excel, pdf and word using jasper reports. I use xml file as the DataSource for the report, but when the data increases jasper report exports empty file in only for PDF format, when i reduce the data content it export the data available correctly. is there any limitation to pdf size? , how can we manage the size in jasper reports from java? My jrxml is really big, so i cannot add it here, i have added my java code which i use to export the content:- JRAbstractExporter exporter = null; if (format.equals("pdf")) { exporter = new JRPdfExporter(); jasperPrint.setPageWidth(Integer.parseInt( pWidth )); } else if (format.equals("xls")) { exporter = new JRXlsExporter(); } else if (format.equals("doc")) { jasperPrint.setPageWidth(Integer.parseInt( pWidth )); } exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream_); exporter.exportReport(); contents = outputStream_.toByteArray(); response.setContentType("application/"+format); response.addHeader("Content-disposition", "attachment;filename=" + name.toString() + "."+format);

    Read the article

  • Flash gets XML but the values are wrong, as3

    - by VideoDnd
    Flash receives the XML, but the values are wrong. How do I fix this? Problem I can see the XML loaded with no errors, but my output is way off. It's as though it's not receiving any values. Numbers in the output window and animation move rapidly. The Flash file runs as if it's variables where set to zero. I changed the order of my code, but that didn't help with this. Please explain how I can correct this. SWF //load xml var myXML:XML; var myLoader:URLLoader = new URLLoader(); myLoader.load(new URLRequest("xml.xml")); myLoader.addEventListener(Event.COMPLETE, processXML); //parse XML function processXML(e:Event):void { myXML = new XML(e.target.data); trace(myXML); //receive values from XML delay = parseInt(myXML.DELAY.text()); trace(delay); repeat = parseInt(myXML.REPEAT.text()); trace(repeat); } //variables var delay:uint = 0; var repeat:uint = 0; //timer and event var timer:Timer = new Timer(uint(delay),uint(repeat)); timer.addEventListener(TimerEvent.TIMER, countdown); //counter function countdown(event:TimerEvent) { myText.text = String(0 + timer.currentCount); trace(0 + timer.currentCount); } timer.start(); XML <?xml version="1.0" encoding="utf-8"?> <SESSION> <DELAY TITLE="starting position">1000</DELAY> <REPEAT TITLE="starting position">60</REPEAT> </SESSION>

    Read the article

  • PHP APC and Pecl upload progress returning false/null.

    - by Keyo
    This is a long shot. I believe this might be suhosin patch issue. Here is my php from codeigniter: public function uploadprogress($id) { if ($id) { header("Cache-Control: no-cache, must-revalidate"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); echo json_encode(apc_fetch('upload_'.$id)); exit(); } } public function uploader() { $this->load->view('myid/' . $this->router->class . '_uploader'); //phpinfo(); } script: <script type="text/javascript"> $(document).ready(function(){ var progress_key = $('#progress_key').val(); // this sets up the progress bar $('#uploadform').submit(function() { setTimeout(beginUpload,1500); return; }); function beginUpload() { $("#progressbar").progressbar({ value:0}).fadeIn(); var i = setInterval(function() { $.getJSON("/myid/videos/uploadprogress/" + progress_key, function(data) { alert('data'); if (data == null) { clearInterval(i); location.reload(true); return; } var response; eval ("response = " + data); if (!response) return; var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total'])); $("#progressbar").progressbar({value:percentage}); }, 1500); }); } }); </script> Has anyone had strange troubles with this before? The upload key is the same on the view and the uploadprogress method. I've Tried apc and pecl upload-progress both return false or null. I wondering if it's just suhosin patch messing up everything?

    Read the article

  • jQuery and MooTools Conflict

    - by flipflopmedia
    Okay, so I got jQuery to get along with MooTools with one script, by adding this at the top of the jQuery script: var $j = jQuery.noConflict(); and then replacing every: $( with $j( But how would you get MooTools to like the following script that using jQuery?? Thanks in advance for any input, Tracy //Fade In Content Viewer: By JavaScript Kit: http://www.javascriptkit.com var fadecontentviewer={ csszindex: 100, fade:function($allcontents, togglerid, selected, speed){ var selected=parseInt(selected) var $togglerdiv=$("#"+togglerid) var $target=$allcontents.eq(selected) if ($target.length==0){ //if no content exists at this index position (ie: stemming from redundant pagination link) alert("No content exists at page number "+selected+"!") return } if ($togglerdiv.attr('lastselected')==null || parseInt($togglerdiv.attr('lastselected'))!=selected){ var $toc=$("#"+togglerid+" .toc") var $selectedlink=$toc.eq(selected) $("#"+togglerid+" .next").attr('nextpage', (selected<$allcontents.length-1)? selected+1+'pg' : 0+'pg') $("#"+togglerid+" .prev").attr('previouspage', (selected==0)? $allcontents.length-1+'pg' : selected-1+'pg') $target.css({zIndex: this.csszindex++, visibility: 'visible'}) $target.hide() $target.fadeIn(speed) $toc.removeClass('selected') $selectedlink.addClass('selected') $togglerdiv.attr('lastselected', selected+'pg') } }, setuptoggler:function($allcontents, togglerid, speed){ var $toc=$("#"+togglerid+" .toc") $toc.each(function(index){ $(this).attr('pagenumber', index+'pg') }) var $next=$("#"+togglerid+" .next") var $prev=$("#"+togglerid+" .prev") $next.click(function(){ fadecontentviewer.fade($allcontents, togglerid, $(this).attr('nextpage'), speed) return false }) $prev.click(function(){ fadecontentviewer.fade($allcontents, togglerid, $(this).attr('previouspage'), speed) return false }) $toc.click(function(){ fadecontentviewer.fade($allcontents, togglerid, $(this).attr('pagenumber'), speed) return false }) }, init:function(fadeid, contentclass, togglerid, selected, speed){ $(document).ready(function(){ var faderheight=$("#"+fadeid).height() var $fadecontents=$("#"+fadeid+" ."+contentclass) $fadecontents.css({top: 0, left: 0, height: faderheight, visibility: 'hidden'}) fadecontentviewer.setuptoggler($fadecontents, togglerid, speed) setTimeout(function(){fadecontentviewer.fade($fadecontents, togglerid, selected, speed)}, 100) $(window).bind('unload', function(){ //clean up $("#"+togglerid+" .toc").unbind('click') $("#"+togglerid+" .next", "#"+togglerid+" .prev").unbind('click') }) }) } }

    Read the article

  • Why does Clojure hang after hacing performed my calculations?

    - by Thomas
    Hi all, I'm experimenting with filtering through elements in parallel. For each element, I need to perform a distance calculation to see if it is close enough to a target point. Never mind that data structures already exist for doing this, I'm just doing initial experiments for now. Anyway, I wanted to run some very basic experiments where I generate random vectors and filter them. Here's my implementation that does all of this (defn pfilter [pred coll] (map second (filter first (pmap (fn [item] [(pred item) item]) coll)))) (defn random-n-vector [n] (take n (repeatedly rand))) (defn distance [u v] (Math/sqrt (reduce + (map #(Math/pow (- %1 %2) 2) u v)))) (defn -main [& args] (let [[n-str vectors-str threshold-str] args n (Integer/parseInt n-str) vectors (Integer/parseInt vectors-str) threshold (Double/parseDouble threshold-str) random-vector (partial random-n-vector n) u (random-vector)] (time (println n vectors (count (pfilter (fn [v] (< (distance u v) threshold)) (take vectors (repeatedly random-vector)))))))) The code executes and returns what I expect, that is the parameter n (length of vectors), vectors (the number of vectors) and the number of vectors that are closer than a threshold to the target vector. What I don't understand is why the programs hangs for an additional minute before terminating. Here is the output of a run which demonstrates the error $ time lein run 10 100000 1.0 [null] 10 100000 12283 [null] "Elapsed time: 3300.856 msecs" real 1m6.336s user 0m7.204s sys 0m1.495s Any comments on how to filter in parallel in general are also more than welcome, as I haven't yet confirmed that pfilter actually works.

    Read the article

  • httpClient proxy support in apache commons 3.1

    - by user1173339
    I am using apache commons 3.1 to implement httpClient with proxy support. I am trying to connect to a remote host through proxy. The proxy server is configured without any authentication, however the the remote host is configured with authentication. When I am passing the proxy parameters through properties file, it gives warning while execution: WARN - Required proxy credentials not available for BASIC @xx.xx.xx.xx WARN - Preemptive authentication requested but no default proxy credentials availble But the execution goes ahead. On the other hand when I am passing the proxy parameters through the JVM arguments then the again the same warning is given and the execution is stopped. Is there any specific reason for this behavior? Is there any difference in passing the proxy parameters through properties file and through JVM arg? Here is the code: if(System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) { httpClient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort"))); } else if(AMXAdminTask.props.getProperty("http.proxyHost") != null && AMXAdminTask.props.getProperty("http.proxyPort") != null) { httpClient.getHostConfiguration().setProxy(Propfile.props.getProperty("http.proxyHost"), Integer.parseInt(Propfile.props.getProperty("http.proxyPort"))); }

    Read the article

  • How to get top and left style property values in Javascript

    - by Dude-Dastic
    Hi all, I have a little bit of Javascript that almost works correctly. Here's the code: function toggle(curlink) { curlink.style.backgroundColor = curlink.style.backgroundColor == "yellow" ? "transparent" : "yellow"; var maindiv = document.getElementById("grid"); var links = maindiv.getElementsByTagName("a"); var list = ""; for (var i = 0; i < links.length; ++i) { var link = links[i]; if (link.style.backgroundColor == "yellow") { list += ("," + parseInt(link.style.left, 10) + "-" + parseInt(link.style.top, 10)); } } document.theForm.theList.value = list.substring(1); return false; }; window.onload = function() { var links = document.getElementById("grid").getElementsByTagName("a"); for (var i = 0; i < links.length; ++i) { links[i].onclick = function() { return toggle(this); } } }; The issue is with line #9; it only works when I specify values for the top and left style property of every link in the array. How do I get the top and left style property values (or X and Y coordinates) of each link in the array with Javascript when those values aren't given? Also, what would the code above look like in jquery? Not that it's needed - I just want to reduce the code a little and dabble in the jquery framework (I'm a Javascript newbie). Thanks in advance, Dude-Dastic

    Read the article

  • Converting an int64 value to a Number object in JavaScript

    - by Matt
    I have a COM object which has a method that returns an unsigned int64 (VT_UI8) value. We have an HTML page which contains some JavaScript which can load the COM object and make the call to that method, to retrieve the value as such: var foo = MyCOMObject.GetInt64Value(); This value can easily be displayed to the user in a message dialog using: alert(foo); or displayed on the page by: document.getElementById('displayToUser').innerHTML = foo; However, we cannot use this value as a Number (e.g. if we try to multiply it by 2) without the page throwing "Number expected" errors. If we check "typeof(foo)" it returns "unknown". I've found a workaround for this by doing the following: document.getElementById('displayToUser').innerHTML = foo; var bar = parseInt(document.getElementById('displayToUser').innerHTML); alert(bar*2); What I need to know is how to make that process more efficient. Specifically, is there a way to cast foo to a String explicitly, rather than having to set some document element's innerHTML to foo and then retrieve it from that. I wouldn't mind calling something like: alert(parseInt((string)foo) * 2); Even better would be if there is a way to directly convert the int64 to a Number, without going through the String conversion, but I hold out less hope for that.

    Read the article

  • javascript setTimeout function out of scope.

    - by Keyo
    I am trying to call showUpload(); from within two setTimeouts. Neither works. It seems to be out of scope and I'm not sure why. I tried this.showUpload() which didn't work either. $(document).ready(function(){ var progress_key = $('#progress_key').val(); // this sets up the progress bar $('#uploadform').submit(function() { setTimeout("showUpload()",1500); $("#progressbar").progressbar({ value:0}).fadeIn(); }); // uses ajax to poll the uploadprogress.php page with the id // deserializes the json string, and computes the percentage (integer) // update the jQuery progress bar // sets a timer for the next poll in 750ms function showUpload() { $.get("/myid/videos/uploadprogress/" + progress_key, function(data) { if (!data) return; var response; eval ("response = " + data); if (!response) return; var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total'])); $("#progressbar").progressbar({ value:percentage}) }); setTimeout("showUpload()", 750); } }); Thank you for your time.

    Read the article

  • Angularjs: addition of integers even after I parse the variable as integer

    - by Shiv Kumar
    I really have a weird problem in adding two numbers. Here is my code, in the first controller everything is working fine, but in the second controller instead of 0 if I add 10, the output is completely weird Here is html code <div ng-app=""> <div ng-controller="Controller1"> <br/>**** Controller-1 <br/>Add 0 : {{update1(0)}} <br/>Add 10 : {{update1(10)}} <br/>Add 50 : {{update1(50)}} <br/>Add -60 : {{update1(-60)}}</div> <div ng-controller="Controller2"> <br/>**** Controller-2 <br/>Add 10 : {{update2(10)}} <br/>Add 10 : {{update2(10)}} <br/>Add 50 : {{update2(50)}} <br/>Add -60 : {{update2(-60)}}</div> </div> Here is my javascript function Controller1($scope) { var x = 0; $scope.update1 = function (smValue) { x += parseInt(smValue); return x; } } function Controller2($scope) { var y = 0; $scope.update2 = function (smValue) { y += parseInt(smValue); return y; } } and here is the output **** Controller-1 Add 0 : 0 Add 10 : 10 Add 50 : 60 Add -60 : 0 **** Controller-2 Add 0 : 110 Add 10 : 120 Add 50 : 170 Add -60 : 110 here is the link to try: http://jsfiddle.net/6VqqN/ can anyone please explain me why it is behaving like that. Even if I add a 3or4 digit number, output is completely different then what I expected.

    Read the article

  • javascript - How to pass an argument in a function call?

    - by Fernando SBS
    function rp_marcadesmarcaFarm(valor) { FM_log(3, "marcadesmarcaFarm called = "+valor); for (i = 0; i < farmList.length; i++) { var arr = farmList[i].split("|"); var xy = arr[0].split(","); var fvillageId = xy2id(parseInt(xy[0]), parseInt(xy[1])); GM_setValue("farmAtivada_"+suffixLocal+fvillageId, valor); GM_setValue("farmAtivada_"+suffixLocal+i, valor); }; reloadFarmTable(); }; function createLinkButton(text, title, jsFunction, value) { var button = dom.cn("a"); button.href = "javascript:void(0)"; button.innerHTML = text; button.title = title; if (jsFunction != null) { button.addEventListener('click', jsFunction, false); } return button; } createLinkButton("X", T('CHECKFARM_M'), rp_marcadesmarcaFarm(true)); apparently the last argument (rp_marcadesmarcaFarm(true)) when invoking the createLinkButton is not working. If I change to: createLinkButton("X", T('CHECKFARM_M'), rp_marcadesmarcaFarm); it works. So how can I pass the (true) variable to the third argument of createLinkButton?

    Read the article

  • jQuery UI Rang Slider show divs based on selected range

    - by andi_sf
    I have set up a range slider that should show/hide divs based on their range values - meaning if the range of the one specifies in the div falls into the selected range in the slider it should show - the others hide. Somehow it does not work correctly - if anybody could help that would be greatly appreciated. My code so far: $("#slider").slider({ range: true, min: 150, max: 280, step: 5, values: [150, 280], slide: function(event, ui) { $("#amount").val('Min. Value' + ui.values[0] + ' - Max. Value' + ui.values[1]); }, change: function(event, ui) { $('#col-2 div').each(function(){ var valueS = parseInt($(this).attr("class")); var valueX = parseInt($(this).attr("title")); if (valueS < ui.values[0] && valueX <= ui.values[1] || valueS ui.values[0] && valueX = ui.values[1] ) { $(this).stop().animate({opacity: 0.25}, 500) } else { $(this).stop().animate({opacity: 1.0}, 500) $("#amount").val('Min. Value' + ui.values[0] + ' - Max. Value' + ui.values[1]); } }); } }); $("#amount").val('Min. Value' + $("#slider").slider("values", 0) + ' - Max. Value' + $("#slider").slider("values", 1)); }); I have also posted a sample at: http://www.webdesigneroakland.com/slider/444range_slider.html

    Read the article

  • substitution cypher with different alphabet length

    - by seanizer
    I would like to implement a simple substitution cypher to mask private ids in URLs I know how my IDs will look like (combination of upperchase ascii, digits and underscore), and they will be rather long, as they are composed keys. I would like to use a longer alphabet to shorten the resulting codes (I'd like to use upper and lower case ascii letters, digits and nothing else). So my incoming alphabet would be [A-Z0-9_] (37 chars) and my outgoing alphabet would be [A-Za-z0-9] (62 chars) so a compression of almost 50% would be available. let's say my URLs look like this: /my/page/GFZHFFFZFZTFZTF_24_F34 and I want them to look like this instead: /my/page/Ft32zfegZFV5 Obviously both arrays would be shuffled to bring some random order in. This does not have to be secure. if someone figures it out: fine, but I don't want the scheme to be obvious. My desired solution would be to convert the string to an integer representation of radix 37, convert the radix to 62 and use the second alphabet to write out that number. is there any sample code available that does something similar? Integer.parseInt ( http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29 ) has some similar logic, but it is hard-coded to use standard digit behavior Any hints? I am using java to implement this but code or pseudo-code in any other language is of course also helpful

    Read the article

  • Tower of Hanoi, stop sliding

    - by ArtWorkAD
    Hi, I developed a solution for the Tower of Hanoi problem: public static void bewege(int h, char quelle, char ablage, char ziel) { if(h > 0){ bewege(h - 1, quelle, ziel, ablage); System.out.println("Move "+ h +" from " + quelle + " to " + ziel); bewege(h - 1, ablage, quelle, ziel); } } It works fine. Now i want to limit the number of slides and throw an exception if a certain limit is reached. I tried it with a counter but it does not work: class HanoiNK{ public static void main(String args[]){ Integer n = Integer.parseInt(args[0]); Integer k = Integer.parseInt(args[1]); try{ bewege(k, n, 'A', 'B', 'C'); }catch(Exception e){ System.out.println(e); } } public static void bewege(int c, int h, char quelle, char ablage, char ziel) throws Exception{ if(h > 0){ if(counter != 0){ bewege(c, h - 1, quelle, ziel, ablage); c--; System.out.println("Move "+ h +" from " + quelle + " to " + ziel); bewege(c, h - 1, ablage, quelle, ziel); c--; }else{ throw new Exception("stop sliding"); } } } } The exception is never thrown. Any ideas?

    Read the article

  • function binding and the clone() function - Jquery

    - by Sam Vloeberghs
    Hi I have problems with my keyup binding when cloning an element. Here's the scenario: I have an html markup like this: <tr class="rijbasis"> <td> <input type="text" class="count" /> </td> <td> <span class="cost">10</span> </td> <td> <span class="total">10</span> </td> </tr> I'm binding an keyup function to the input element of my table row like this: $('.rijbasis input').keyup(function(){ var parent = $(this).parent().parent(); $('.total',parent).text(parseInt($('.cost',parent).text()) * parseInt($('.count',parent).val())); } I designed the function like this so I could clone the table row on a onclick event and append it to the tbody: $('.lineadd').click(function(){ $('.contract tbody').append($('.contract tbody tr:last').clone()); $('.contract tbody tr:last input').val("0"); }); This al works , but the keyup function doesnt work on the input elements of the cloned row.. Can anybody help or advice? I hope I was clear enough and I'll be surely adding details if needed to solve this problem. Greetings

    Read the article

  • convert list of relative widths to pixel widths

    - by mkoryak
    This is a code review question more then anything. I have the following problem: Given a list of relative widths (no unit whatsoever, just all relative to each other), generate a list of pixel widths so that these pixel widths have the same proportions as the original list. input: list of proportions, total pixel width. output: list of pixel widths, where each width is an int, and the sum of these equals the total width. Code: var sizes = "1,2,3,5,7,10".split(","); //initial proportions var totalWidth = 1024; // total pixel width var sizesTotal = 0; for (var i = 0; i < sizes.length; i++) { sizesTotal += parseInt(sizes[i], 10); } if(sizesTotal != 100){ var totalLeft = 100;; for (var i = 0; i < sizes.length; i++) { sizes[i] = Math.floor(parseInt(sizes[i], 10) / sizesTotal * 100); totalLeft -= sizes[i]; } sizes[sizes.lengh - 1] = totalLeft; } totalLeft = totalWidth; for (var i = 0; i < sizes.length; i++) { widths[i] = Math.floor(totalWidth / 100 * sizes[i]) totalLeft -= widths[i]; } widths[sizes.lenght - 1] = totalLeft; //return widths which contains a list of INT pixel sizes

    Read the article

  • Java: Generics, Class.isaAssignableFrom, and type casting

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupporteded value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • Image re sizing not working after rotation in Html5 canvas

    - by Deepu the Don
    In my HTML 5 + Javascript application, we can drag, re size and rotate image in Html 5 canvas. But after doing rotation, re sizing is not working. (I think it i related to finding dx,dy,not sure). Please help me to fix the code given below. Thanks in advance. <!doctype html> <html> <head> <style> #canvas{ border:red dashed #ccc; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script> $(function(){ var canvas=document.getElementById("canvas"),ctx=canvas.getContext("2d"),canvasOffset=$("#canvas").offset(); var offsetX=canvasOffset.left,offsetY=canvasOffset.top,startX,startY,isDown=false,pi2=Math.PI*2; var resizerRadius=8,rr=resizerRadius*resizerRadius,draggingResizer={x:0,y:0},imageX=50,imageY=50; var imageWidth,imageHeight,imageRight,imageBottom,draggingImage=false,startX,startY,doRotation=false; var r=0,rotImg = new Image(); rotImg.src="rotation.jpg"; var img=new Image(); img.onload=function(){ imageWidth=img.width; imageHeight=img.height; imageRight=imageX+imageWidth; imageBottom=imageY+imageHeight; w=img.width/2; h=img.height/2; draw(true,false); } img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png"; function draw(withAnchors,withBorders){ ctx.fillStyle="black"; ctx.clearRect(0,0,canvas.width,canvas.height); ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.drawImage(img,0,0,img.width,img.height,imageX,imageY,imageWidth,imageHeight); ctx.restore(); if(withAnchors){ drawDragAnchor(imageX,imageY); drawDragAnchor(imageRight,imageY); drawDragAnchor(imageRight,imageBottom); drawDragAnchor(imageX,imageBottom); } if(withBorders){ ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.beginPath(); ctx.moveTo(imageX,imageY); ctx.lineTo(imageRight,imageY); ctx.lineTo(imageRight,imageBottom); ctx.lineTo(imageX,imageBottom); ctx.closePath(); ctx.stroke(); ctx.restore(); } ctx.fillStyle="blue"; ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.beginPath(); ctx.moveTo(imageRight+15,imageY-10); ctx.lineTo(imageRight+45,imageY-10); ctx.lineTo(imageRight+45,imageY+20); ctx.lineTo(imageRight+15,imageY+20); ctx.fill(); ctx.closePath(); ctx.restore(); } function drawDragAnchor(x,y){ ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.beginPath(); ctx.arc(x,y,resizerRadius,0,pi2,false); ctx.closePath(); ctx.fill(); ctx.restore(); } function anchorHitTest(x,y){ var dx,dy; dx=x-imageX; dy=y-imageY; if(dx*dx+dy*dy<=rr){ return(0); } // top-right dx=x-imageRight; dy=y-imageY; if(dx*dx+dy*dy<=rr){ return(1); } // bottom-right dx=x-imageRight; dy=y-imageBottom; if(dx*dx+dy*dy<=rr){ return(2); } // bottom-left dx=x-imageX; dy=y-imageBottom; if(dx*dx+dy*dy<=rr){ return(3); } return(-1); } function hitImage(x,y){ return(x>imageX && x<imageX+imageWidth && y>imageY && y<imageY+imageHeight); } function handleMouseDown(e){ startX=parseInt(e.clientX-offsetX); startY=parseInt(e.clientY-offsetY); draggingResizer= anchorHitTest(startX,startY); draggingImage= draggingResizer<0 && hitImage(startX,startY); doRotation = draggingResizer<0 && !draggingImage && ctx.isPointInPath(startX,startY); } function handleMouseUp(e){ draggingResizer=-1; draggingImage=false; doRotation=false; draw(true,false); } function handleMouseOut(e){ handleMouseUp(e); } function handleMouseMove(e){ mouseX=parseInt(e.clientX-offsetX); mouseY=parseInt(e.clientY-offsetY); if(draggingResizer>-1){ switch(draggingResizer){ case 0: //top-left imageX=mouseX; imageWidth=imageRight-mouseX; imageY=mouseY; imageHeight=imageBottom-mouseY; break; case 1: //top-right imageY=mouseY; imageWidth=mouseX-imageX; imageHeight=imageBottom-mouseY; break; case 2: //bottom-right imageWidth=mouseX-imageX; imageHeight=mouseY-imageY; break; case 3: //bottom-left imageX=mouseX; imageWidth=imageRight-mouseX; imageHeight=mouseY-imageY; break; } if(imageWidth<25) imageWidth=25; if(imageHeight<25) imageHeight=25; imageRight=imageX+imageWidth; imageBottom=imageY+imageHeight; draw(true,true); }else if(draggingImage){ imageClick=false; var dx=mouseX-startX; var dy=mouseY-startY; imageX+=dx; imageY+=dy; imageRight+=dx; imageBottom+=dy; startX=mouseX; startY=mouseY; draw(false,true); }else if(doRotation){ var dx=mouseX-imageX; var dy=mouseY-imageY; r=Math.atan2(dy,dx); draw(false,true); } } $("#canvas").mousedown(function(e){handleMouseDown(e);}); $("#canvas").mousemove(function(e){handleMouseMove(e);}); $("#canvas").mouseup(function(e){handleMouseUp(e);}); $("#canvas").mouseout(function(e){handleMouseOut(e);}); }); </script> </head> <body> <canvas id="canvas" width=800 height=500></canvas> </body> </html>

    Read the article

  • More efficient comparison of numbers

    - by Pez Cuckow
    I have an array which is part of a small JS game I am working on I need to check (as often as reasonable) that each of the elements in the array haven't left the "stage" or "playground", so I can remove them and save the script load I have coded the below and was wondering if anyone knew a faster/more efficient way to calculate this. This is run every 50ms (it deals with the movement). Where bots[i][1] is movement in X and bots[i][2] is movement in Y (mutually exclusive). for (var i in bots) { var left = parseInt($("#" + i).css("left")); var top = parseInt($("#" + i).css("top")); var nextleft = left + bots[i][1]; var nexttop = top + bots[i][2]; if(bots[i][1]>0&&nextleft>=PLAYGROUND_WIDTH) { remove_bot(i); } else if(bots[i][1]<0&&nextleft<=-GRID_SIZE) { remove_bot(i); } else if(bots[i][2]>0&&nexttop>=PLAYGROUND_HEIGHT) { remove_bot(i); } else if(bots[i][2]<0&&nexttop<=-GRID_SIZE) { remove_bot(i); } else { //alert(nextleft + ":" + nexttop); $("#" + i).css("left", ""+(nextleft)+"px"); $("#" + i).css("top", ""+(nexttop)+"px"); } } On a similar note the remove_bot(i); function is as below, is this correct (I can't splice as it changes all the ID's of the elements in the array. function remove_bot(i) { $("#" + i).remove(); bots[i] = false; } Many thanks for any advice given!

    Read the article

  • Uva's 3n+1 problem

    - by dmindreader
    I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far. import java.io.*; public class NewClass{ /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { int maxCounter= 0; int input; int lowerBound; int upperBound; int counter; int numberOfCycles; int maxCycles= 0; int lowerInt; BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in)); String line = consoleInput.readLine(); String [] splitted = line.split(" "); lowerBound = Integer.parseInt(splitted[0]); upperBound = Integer.parseInt(splitted[1]); int [] recentlyused = new int[1000001]; if (lowerBound > upperBound ) { int h = upperBound; upperBound = lowerBound; lowerBound = h; } lowerInt = lowerBound; while (lowerBound <= upperBound) { counter = lowerBound; numberOfCycles = 0; if (recentlyused[counter] == 0) { while ( counter != 1 ) { if (recentlyused[counter] != 0) { numberOfCycles = recentlyused[counter] + numberOfCycles; counter = 1; } else { if (counter % 2 == 0) { counter = counter /2; } else { counter = 3*counter + 1; } numberOfCycles++; } } } else { numberOfCycles = recentlyused[counter] + numberOfCycles; counter = 1; } recentlyused[lowerBound] = numberOfCycles; if (numberOfCycles > maxCycles) { maxCycles = numberOfCycles; } lowerBound++; } System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1)); } }

    Read the article

  • Google App-Engine Java Batch Update

    - by Manjoor
    I need to upload a .csv file and save the records in bigtable. My application successfully parse 200 the records in the csv files and save to table. Here is my code to save the data. for (int i=0;i<lines.length -1;i++) //lines hold total records in csv file { String line = lines[i]; //The record have 3 columns integer,integer,Text if(line.length() > 15) { int n = line.indexOf(","); if (n>0) { int ID = lInteger.parseInt(ine.substring(0,n)); int n1 = line.indexOf(",", n + 2); if(n1 > n) { int Col1 = Integer.parseInt(line.substring(n + 1, n1)); String Col2 = line.substring(n1 + 1); myTable uu = new myTable(); uu.setId(ID); uu.setCol1(MobNo); Text t = new Text(Col2); uu.setCol2(t); PersistenceManager pm = PMF.get().getPersistenceManager(); pm.makePersistent(uu); pm.close(); } } } } But when no of records grow it gives timeout error. The csv file may have upto 800 records. Is it possible to do that in App-Engine? (something like batch update)

    Read the article

  • How to change CSS color values in real-time off a javascript slider?

    - by bflora
    I'm making a page where the user gets a javascript slider that goes from 0 to 100 and can use it to set the opacity of a div on the page. I want the opacity of that div to change in real-time as they work the slider. I've not done this before. What's the best approach? There cursor in the slider displays the slider's current value as you move it. It seems to be that I just need to find a way to display that value in any arbitrary other place on the page so I can display it in the style settings for the div. The .js file that generates the slider has a line that (I think) is setting the current value in the cursor: $(this).children(".ui-slider-handle", context).html(parseInt(settings[index]['default'])); TO get this changing number to display somewhere else at the same time, do I just need to add a div somewhere and then add a line like this? $("#newDivId").children(".ui-slider-handle", context).html(parseInt(settings[index]['default'])); That seems like it would give me the number showing up in a div. How then would I get it into a form I could put into the style settings for a div? If this was a php variable, I would do something like this, style="opacity:<?php print $value ?>;" What would be the .js equivalent?

    Read the article

  • Java: Typecasting to Generics

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupported value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • Autocomplete and User define keyboard

    - by Geetha
    Hi All, I am using asp:button to create a keyboard with A-Z and 0-9 for touch screen using Java script. This keyboard is linked with one textbox. If we click one button corresponding text will be displayed on the textbox. Its working fine. I have included the autocomplete feature to this textbox using jquery JQuery Autocomplete. Problem: The autocomplete is not working if i my user define keyboard. How to modify my key buttons as keyboard keys? Is it possible? Is there any other way to achieve this? Code: <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> <asp:Button ID="zero" runat="server" Text="0" CssClass="myclass" OnClientClick="return typeLetter(this);" TabIndex="20"/> function typeLetter(currentbutton) { if (previousActiveElement != null) { if (previousActiveElement == 'antSearchText'){ var position = document.getElementById('position').value; if (position == '') { alert('chk position'); } else { var existingString = document.getElementById(previousActiveElement).value; var beforeString = existingString.substring(0, position); var afterString = existingString.substring(position, existingString.length); document.getElementById(previousActiveElement).value = beforeString + currentbutton.value + afterString; setCaretPosition(document.getElementById(previousActiveElement), parseInt(position) + 1); setCaretPosition(document.getElementById(previousActiveElement), parseInt(position) + 1); } } } return false; }

    Read the article

  • Loading data from file to Vector structure

    - by owca
    I'm trying to parse through fixed-width formatted file extracting x,y values of points from it, and then storing them in int[] array inside a Vector. Text file looks as follows : 0006 0015 0125 0047 0250 0131 That's the code : Vector<int[]> vc = new Vector<int[]>(); try { BufferedReader file = new BufferedReader(new FileReader("myfile.txt")); String s; int[] vec = new int[2]; while ((s = file.readLine()) != null) { vec[0] = Integer.parseInt(s.substring(0, 4).trim()); vec[1] = Integer.parseInt(s.substring(5, 8).trim()); vc.add(vec); } file.close(); } catch (IOException e) { } for(int i=0; i<vc.size(); i++){ for(int j=0; j<2; j++){ System.out.println(vc.elementAt(i)[j]); } } But the output shows only last line. 250 131 250 131 250 131 Should I somehow use Vector.nextElement() here to get all my data ?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >