Skip to content

Instantly share code, notes, and snippets.

@hsanchez
Last active July 12, 2016 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hsanchez/fde4103db09c865010b2 to your computer and use it in GitHub Desktop.
Save hsanchez/fde4103db09c865010b2 to your computer and use it in GitHub Desktop.
Ruby: A slight knowledge or suspicion about Curable Q & A on StackOverflow
# Ruby
.ruby-version
# History files
.Rhistory
# Example code in package build process
*-Ex.R
# R data files from past sessions
.Rdata
.RData
# RStudio files
.Rproj.user/
*.Rproj
*.gem
*.rbc
/.config
/coverage/
/InstalledFiles
/pkg/
/spec/reports/
/test/tmp/
/test/version_tmp/
/tmp/
## Specific to RubyMotion:
.dat*
.repl_history
build/
## Documentation cache and generated files:
/.yardoc/
/_yardoc/
/doc/
/rdoc/
## Environment normalisation:
/.bundle/
/lib/bundler/man/
# for a library or gem, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# Gemfile.lock
# .ruby-version
# .ruby-gemset
# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc
.DS_Store
.Rproj.user
.idea
We can't make this file beautiful and searchable because it's too large.
OwnerLink,QuestionLink,AcceptedAnswerLink,QuestionLastActivityDate,QuestionScore,QuestionViewCount,QuestionFavoriteCount,QuestionAnswerCount,QuestionTitle,QuestionBody,QuestionTitleLength,QuestionBodyLength,QuestionTags,QuestionCreationDate,QuestionContainsCodeBlock,IsAnswerWiki,AnswerId,AcceptedAnswerLastEditDate,AcceptedAnswerScore,AcceptedAnswerBody,AcceptedAnswerBodyLength,TextChunks,CodeChunks,AnswerCommentsCount,AcceptedAnswerCreationDate,PostedTimeDifferenceInMins,AcceptedAnswerContainsCodeBlock,AnswererReputation,SuggestionsCount
"http://stackoverflow.com/users/342235","http://stackoverflow.com/questions/6841333","http://stackoverflow.com/questions/6841333/#6841479","2014-08-06 23:21:08","2802","259340","803","8","Why is subtracting these two times (in 1927) giving a strange result?","<p>If I run the following program, which parses two date strings referencing times one second apart and compares them:</p>
<pre><code>public static void main(String[] args) throws ParseException {
SimpleDateFormat sf = new SimpleDateFormat(""yyyy-MM-dd HH:mm:ss"");
String str3 = ""1927-12-31 23:54:07"";
String str4 = ""1927-12-31 23:54:08"";
Date sDt3 = sf.parse(str3);
Date sDt4 = sf.parse(str4);
long ld3 = sDt3.getTime() /1000;
long ld4 = sDt4.getTime() /1000;
System.out.println(ld3);
System.out.println(ld4);
System.out.println(ld4-ld3);
}
</code></pre>
<p>The output is:</p>
<pre><code>-1325491905
-1325491552
353
</code></pre>
<p>Why is <code>ld4-ld3</code> not <code>1</code> (as I would expect from the one-second difference in the times), but <code>353</code>?</p>
<p>If I change the dates to times one second later:</p>
<pre><code>String str3 = ""1927-12-31 23:54:08"";
String str4 = ""1927-12-31 23:54:09"";
</code></pre>
<p>Then <code>ld4-ld3</code> will be <code>1</code></p>
<hr>
<p><strong>UPDATE</strong></p>
<p>Java version:</p>
<pre><code>java version ""1.6.0_22""
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode)
</code></pre>
<p>Timezone(<code>TimeZone.getDefault()</code>):</p>
<pre><code>sun.util.calendar.ZoneInfo[id=""Asia/Shanghai"",
offset=28800000,dstSavings=0,
useDaylight=false,
transitions=19,
lastRule=null]
Locale(Locale.getDefault()): zh_CN
</code></pre>
","69","1545","<java><date><timezone>","2011-07-27 08:15:58","TRUE","FALSE","6841479","2014-08-06 21:57:26","5483","<p>It's a time zone change on December 31st in Shanghai.</p>
<p>See <a href=""http://www.timeanddate.com/worldclock/clockchange.html?n=237&amp;year=1927"">this page</a> for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So ""1927-12-31 23:54:08"" actually happened twice, and it looks like Java is parsing it as the <em>later</em> possible instant for that local date/time - hence the difference.</p>
<p>Just another episode in the often weird and wonderful world of time zones.</p>
<p><strong>EDIT:</strong> Stop the press! History changes...</p>
<p>The original question would no longer demonstrate quite the same behaviour, if rebuilt with version 2013a of <a href=""https://code.google.com/p/noda-time/source/browse/src/NodaTime.Demo/StackOverflowExamples.cs"">TZDB</a>. In 2013a, the result would be 358 seconds, with a transition time of 23:54:03 instead of 23:54:08.</p>
<p>I only noticed this because I'm collecting questions like this in Noda Time, in the form of <a href=""https://code.google.com/p/noda-time/source/browse/src/NodaTime.Demo/StackOverflowExamples.cs"">unit tests</a>... The test has now been changed, but it just goes to show - not even historical data is safe.</p>
<p><strong>EDIT:</strong> History has changed again...</p>
<p>In TZDB 2014f, the time of the change has moved to 1900-12-31, and it's now a mere 343 second change (so the time between <code>t</code> and <code>t+1</code> is 344 seconds, if you see what I mean).</p>
<p><strong>EDIT:</strong> To answer <a href=""http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result/6841479#comment22684267_6841479"">Ken Kin's question</a> around a transition at 1900... it looks like the Java timezone implementation treats <em>all</em> time zones as simply being in their standard time for any instant before the start of 1900 UTC:</p>
<pre><code>import java.util.TimeZone;
public class Test {
public static void main(String[] args) throws Exception {
long startOf1900Utc = -2208988800000L;
for (String id : TimeZone.getAvailableIDs()) {
TimeZone zone = TimeZone.getTimeZone(id);
if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) {
System.out.println(id);
}
}
}
}
</code></pre>
<p>The code above produces no output on my Windows machine. So any time zone which has any offset other than its standard one at the start of 1900 will count that as a transition. TZDB itself has some data going back earlier than that, and doesn't rely on any idea of a ""fixed"" standard time (which is what <code>getRawOffset</code> assumes to be a valid concept) so other libraries needn't introduce this artificial transition.</p>
","2813","10","1","16","2011-07-27 08:31:10","16","TRUE","712839","48"
"http://stackoverflow.com/users/265683","http://stackoverflow.com/questions/2533236","http://stackoverflow.com/questions/2533236/#2533245","2013-03-09 01:21:29","10","14449","2","3","Setting user agent in Java httpclient and allow redirects to true","<p>I am trying to set my user agent string in the HttpClient apache object in Java but I cannot find out how to do it.</p>
<p>Please help!</p>
<p>Also I am trying to enable redirects to true but also cannot find this option within the HttpClient object.</p>
<p>Thanks</p>
<p>Andy</p>
","65","288","<java><android><apache><httpclient><user-agent>","2010-03-28 14:29:42","FALSE","FALSE","2533245","2013-03-09 01:21:29","17","<pre><code>HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter(
HttpMethodParams.USER_AGENT,
""Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2""
);
</code></pre>
","235","0","1","11","2010-03-28 14:33:12","4","TRUE","542294","0"
"http://stackoverflow.com/users/1000","http://stackoverflow.com/questions/408042","http://stackoverflow.com/questions/408042/#409041","2014-01-08 16:13:16","7","13969","9","4","Vector graphics in iText PDF","<p>We use iText to generate PDFs from Java (based partly on recommendations on this site). However, embedding a copy of our logo in an image format like GIF results in it looking a bit strange as people zoom in and out.</p>
<p>Ideally we'd like to embed the image in a vector format, such as EPS, SVG or just a PDF template. The website claims that EPS support has been dropped, that embedding a PDF or PS within a PDF can result in errors, and it doesn't even mention SVG.</p>
<p>Our code uses the Graphics2D API rather than iText directly, but we'd be willing to break out of AWT mode and use iText itself if it achieved the result. How can this be done?</p>
","28","663","<java><image><pdf><vector><itext>","2009-01-02 21:09:21","FALSE","FALSE","409041","2014-01-08 16:13:16","5","<p>According to the <a href=""http://itextdocs.lowagie.com/tutorial/objects/images/index.php"">documentation</a> iText supports the following image formats: JPEG, GIF, PNG, TIFF, BMP, WMF and EPS. I don't know if this might be of any help but I have successfully used <a href=""http://itextsharp.sourceforge.net/"">iTextSharp</a> to embed vector <a href=""http://en.wikipedia.org/wiki/Windows_Metafile"">WMF</a> image in a pdf file:</p>
<p>C#:</p>
<pre><code>using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class Program
{
public static void Main()
{
Document document = new Document();
using (Stream outputPdfStream = new FileStream(""output.pdf"", FileMode.Create, FileAccess.Write, FileShare.None))
using (Stream imageStream = new FileStream(""test.wmf"", FileMode.Open, FileAccess.Read, FileShare.Read))
{
PdfWriter.GetInstance(document, outputPdfStream);
Image wmf = Image.GetInstance(imageStream);
document.Open();
document.Add(wmf);
document.Close();
}
}
}
</code></pre>
","1126","2","1","1","2009-01-03 13:36:06","987","TRUE","542294","0"
"http://stackoverflow.com/users/242763","http://stackoverflow.com/questions/2349367","http://stackoverflow.com/questions/2349367/#2349377","2013-04-05 19:19:19","5","14084","0","6","Find sine in Java","<p>Can anyone give me a quick tip? </p>
<p>For example....how would I find the sine of 90 degrees?</p>
","17","104","<java><math>","2010-02-27 23:27:52","FALSE","FALSE","2349377","2012-11-02 11:12:40","8","<p>You could use the <a href=""http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#sin%28double%29"" rel=""nofollow"">Math.sin</a> function where the argument is given in radians. Example:</p>
<pre><code>double result = Math.sin(Math.PI / 2.0);
</code></pre>
","264","1","1","4","2010-02-27 23:30:27","3","TRUE","542294","0"
"http://stackoverflow.com/users/729995","http://stackoverflow.com/questions/7699284","http://stackoverflow.com/questions/7699284/#7699293","2011-10-08 19:45:35","3","3586","0","4","Using generics in Java","<p>I started using Java a while ago so this is probably a silly question for most of you,
I want to use Set in my code (assume I have a class T),</p>
<pre><code>Set&lt;T&gt; mySet;
</code></pre>
<p>Eclipse gives my an error : The local variable mySet may not have been initialized.
Than I tried to initialize it:</p>
<pre><code>Set&lt;T&gt; mySet = new Set&lt;T&gt;();
</code></pre>
<p>but than Eclipse gives the error : ""Cannot instantiate the type Set"".</p>
<p>What am I doing wrong here ?</p>
","22","501","<java><generics>","2011-10-08 19:35:33","TRUE","FALSE","7699293","2011-10-08 19:45:35","20","<p><code>Set&lt;T&gt;</code> is an interface and cannot be instantiated. You could use <code>HashSet&lt;T&gt;</code>:</p>
<pre><code>Set&lt;T&gt; set = new HashSet&lt;T&gt;();
</code></pre>
","191","1","1","5","2011-10-08 19:37:08","2","TRUE","542294","0"
"http://stackoverflow.com/users/321862","http://stackoverflow.com/questions/6806146","http://stackoverflow.com/questions/6806146/#6806158","2011-07-24 11:47:54","0","405","0","3","How to hit java.lang.OutOfMemoryError by spawning threads?","<p>I came across this <a href=""http://vanillajava.blogspot.com/2011/07/java-what-is-limit-to-number-of-threads.html"" rel=""nofollow"">blog site</a> where the author is testing against the maximum number of threads before the machine throws a java.lang.OutOfMemoryError. However, in my below test codes, i am unable to hit the error despite the arbitrary large threads spawned.</p>
<pre><code> for (int i = 0; i &lt; 1000000; i++) {
Thread thread = new Thread(new Car());
thread.setName(Integer.toString(i));
thread.start();
}
</code></pre>
","58","570","<java><multithreading><out-of-memory>","2011-07-24 10:01:00","TRUE","FALSE","6806158","2011-07-24 10:10:42","8","<p>Try sleeping inside the thread, otherwise it might end up too quickly and get garbage collected, as shown in the <a href=""http://code.google.com/p/core-java-performance-examples/source/browse/trunk/src/test/java/com/google/code/java/core/threads/MaxThreadsMain.java"" rel=""nofollow"">example code</a>:</p>
<pre><code>Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
while (!Thread.interrupted()) {
Thread.sleep(1000);
}
} catch (InterruptedException ignored) {
//
}
}
});
</code></pre>
","602","1","1","4","2011-07-24 10:03:36","2","TRUE","542294","0"
"http://stackoverflow.com/users/1918282","http://stackoverflow.com/questions/14454854","http://stackoverflow.com/questions/14454854/#14454870","2013-07-04 10:59:33","-9","772","0","4","Adding a number to the day or month or year in a date","<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href=""http://stackoverflow.com/questions/2507377/how-to-add-days-to-a-date-in-java"">How to add days to a date in Java</a> </p>
</blockquote>
<p>Consider the date to be <strong>19/05/2013</strong> and the number to be <strong>14</strong>. I would like to get the resulting date after adding the number to the month.</p>
<p>Expected result is: 19/07/2014.</p>
","53","427","<c#><java><algorithm><date>","2013-01-22 09:05:03","FALSE","FALSE","14454870","2013-07-04 10:59:33","9","<p>In .NET you could do use the <a href=""http://msdn.microsoft.com/en-us/library/system.datetime.addmonths.aspx""><code>AddMonths</code></a> method:</p>
<pre><code>DateTime date = new DateTime(2013, 5, 19);
DateTime newDate = date.AddMonths(14);
</code></pre>
<p>As far as parsing a date from a string using a specified format you could use the <a href=""http://msdn.microsoft.com/en-us/library/system.datetime.TryParseExact.aspx""><code>TryParseExact</code></a> method:</p>
<pre><code>string dateStr = ""19/05/2013"";
DateTime date;
if (DateTime.TryParseExact(dateStr, ""dd/MM/yyyy"", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// successfully parsed the string into a DateTime instance =&gt;
// here we could add the desired number of months to it and construct
// a new DateTime
DateTime newDate = date.AddMonths(14);
}
else
{
// parsing failed =&gt; the specified string was not in the correct format
// you could inform the user about that here
}
</code></pre>
","1007","2","2","2","2013-01-22 09:05:50","0","TRUE","542294","0"
"http://stackoverflow.com/users/374769","http://stackoverflow.com/questions/3106452","http://stackoverflow.com/questions/3106452/#3106909","2014-03-05 11:41:57","406","90354","467","6","How do servlets work? Instantiation, session variables and multithreading","<p>Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am getting the servlet context and setting session variables. Now, if 2 or more users send request to this server then what happens to the session variables? Will they all be common for all the users or they will be different for each user. If they are different, then how was the server able to differentiate between different users?</p>
<p>One more similar question, if there are <em>n</em> users accessing a particular servlet, then this servlet gets instantiated only the first time the first user accessed it or does it get instantiated for all the users separately?</p>
","73","686","<java><multithreading><session><servlets><session-variables>","2010-06-24 00:16:15","FALSE","FALSE","3106909","2013-04-04 17:28:53","784","<h3>ServletContext</h3>
<p>When the servletcontainer (like <a href=""http://tomcat.apache.org"">Apache Tomcat</a>) starts up, it will deploy and load all webapplications. When a webapplication get loaded, the servletcontainer will create the <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html""><code>ServletContext</code></a> once and keep in server's memory. The webapp's <code>web.xml</code> will be parsed and every <code>Servlet</code>, <code>Filter</code> and <code>Listener</code> found in <code>web.xml</code> will be created once and kept in server's memory as well. When the servletcontainer shuts down, it will unload all webapplications and the <code>ServletContext</code> and all <code>Servlet</code>, <code>Filter</code> and <code>Listener</code> instances will be trashed.</p>
<h3>HttpServletRequest and HttpServletResponse</h3>
<p>The servletcontainer is attached to a webserver which listens on HTTP requests on a certain port number, which is usually 80. When a client (user with a webbrowser) sends a HTTP request, the servletcontainer will create new <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html""><code>HttpServletRequest</code></a> and <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html""><code>HttpServletResponse</code></a> objects and pass it through the methods of the already-created <code>Filter</code> and <code>Servlet</code> instances whose <code>url-pattern</code> matches the request URL, all in the same thread. </p>
<p>The request object provides access to all information of the HTTP request, such as the request headers and the request body. The response object provides facility to control and send the HTTP response the way you want, such as setting headers and the body (usually with HTML content from a JSP file). When the HTTP response is committed and finished, then both the request and response objects will be trashed.</p>
<h3>HttpSession</h3>
<p>When a client visits the webapp for the first time and/or the <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpSession.html""><code>HttpSession</code></a> is to be obtained for the first time by <code>request.getSession()</code>, then the servletcontainer will create it, generate a long and unique ID (which you can get by <code>session.getId()</code>) and store it in server's memory. The servletcontainer will also set a <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/http/Cookie.html""><code>Cookie</code></a> in the HTTP response with <code>JSESSIONID</code> as cookie name and the unique session ID as cookie value. </p>
<p>As per the <a href=""http://www.faqs.org/rfcs/rfc2965.html"">HTTP cookie specification</a> (a contract a decent webbrowser and webserver has to adhere), the client (the webbrowser) is required to send this cookie back in the subsequent requests as long as the cookie is valid. Using a HTTP header checker tool like <a href=""http://getfirebug.com"">Firebug</a> you can <a href=""http://getfirebug.com/network"">check</a> them. The servletcontainer will determine every incoming HTTP request header for the presence of the cookie with the name <code>JSESSIONID</code> and use its value (the session ID) to get the associated <code>HttpSession</code> from server's memory.</p>
<p>The <code>HttpSession</code> lives until it has not been used for more than the <code>&lt;session-timeout&gt;</code> time, a setting you can specify in <code>web.xml</code>, which defaults to 30 minutes. So when the client doesn't visit the webapp anymore for over 30 minutes, then the servletcontainer will trash the session. Every subsequent request, even though with the cookie specified, will not have access to the same session anymore. The servletcontainer will create a new one. </p>
<p>On the other hand, the session cookie on the client side has a default lifetime which is as long as the browser instance is running. So when the client closes the browser instance (all tabs/windows), then the session will be trashed at the client side. In a new browser instance the cookie associated with the session won't be sent anymore. A new <code>request.getSession()</code> would return a brand new <code>HttpSession</code> and set a cookie with a brand new session ID.</p>
<h3>In a nutshell</h3>
<ul>
<li>The <code>ServletContext</code> lives as long as the webapp lives. It's been shared among <em>all</em> requests in <em>all</em> sessions.</li>
<li>The <code>HttpSession</code> lives as long as the client is interacting with the webapp with the same browser instance and the session hasn't timed out at the server side yet. It's been shared among <em>all</em> requests in the <em>same</em> session.</li>
<li>The <code>HttpServletRequest</code> and <code>HttpServletResponse</code> lives as long as the client has sent it until the complete response (the webpage) is arrived. It is <em>not</em> being shared elsewhere.</li>
<li>Any <code>Servlet</code>, <code>Filter</code> and <code>Listener</code> lives as long as the webapp lives. They are being shared among <em>all</em> requests in <em>all</em> sessions.</li>
<li>Any <code>attribute</code> which you set in <code>ServletContext</code>, <code>HttpServletRequest</code> and <code>HttpSession</code> will live as long as the object in question lives.</li>
</ul>
<hr>
<h3>Threadsafety</h3>
<p>That said, your major concern is possibly <em>threadsafety</em>. You should now have learnt that Servlets and filters are shared among all requests. That's the nice thing of Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise have been too expensive to recreate it on every request.</p>
<p>But you should also realize that you should <strong>never</strong> assign any request or session scoped data as an <em>instance</em> variable of a servlet or filter. It will be shared among all other requests in other sessions. That's <em>threadunsafe</em>! The below example illustrates that:</p>
<pre><code>public class MyServlet extends HttpServlet {
private Object thisIsNOTThreadSafe;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object thisIsThreadSafe;
thisIsNOTThreadSafe = request.getParameter(""foo""); // BAD!! Shared among all requests!
thisIsThreadSafe = request.getParameter(""foo""); // OK, this is thread safe.
}
}
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href=""http://stackoverflow.com/questions/2183974/difference-each-instance-of-servlet-and-each-thread-of-servlet-in-servlets/2184147#2184147"">Servlets and Multithreading</a></li>
<li><a href=""http://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp/2097732#2097732"">Difference between JSP and Servlet</a></li>
<li><a href=""http://stackoverflow.com/questions/1700390/best-option-for-session-management-in-java/1701107#1701107"">Session management in Java</a></li>
</ul>
","7047","9","1","8","2010-06-24 02:41:44","145","TRUE","511609","16"
"http://stackoverflow.com/users/240337","http://stackoverflow.com/questions/2422468","http://stackoverflow.com/questions/2422468/#2424824","2014-02-04 10:00:31","213","168808","156","7","How to upload files to server using JSP/Servlet?","<p>How can I upload files to server using JSP/Servlet? I tried this:</p>
<pre class=""lang-html prettyprint-override""><code>&lt;form action=""upload"" method=""post""&gt;
&lt;input type=""text"" name=""description"" /&gt;
&lt;input type=""file"" name=""file"" /&gt;
&lt;input type=""submit"" /&gt;
&lt;/form&gt;
</code></pre>
<p>However, I only get the file name, not the file content. When I add <code>enctype=""multipart/form-data""</code> to the <code>&lt;form&gt;</code>, then <code>request.getParameter()</code> returns <code>null</code>. </p>
<p>During research I stumbled upon <a href=""http://commons.apache.org/fileupload"">Apache Common FileUpload</a>. I tried this:</p>
<pre><code>FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.
</code></pre>
<p>Unfortunately, the servlet threw an exception without a clear message and cause. Here is the stacktrace:</p>
<pre><code>SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:637)
</code></pre>
","48","2202","<java><jsp><java-ee><servlets><file-upload>","2010-03-11 04:07:32","TRUE","TRUE","2424824","2013-11-20 00:34:06","444","<h2>Introduction</h2>
<p>To browse and select a file for upload you need a HTML <code>&lt;input type=""file""&gt;</code> field in the form. As stated in the <a href=""http://www.w3.org/TR/html4/interact/forms.html"">HTML specification</a> you have to use the <code>POST</code> method and the <code>enctype</code> attribute of the form has to be set to <code>""multipart/form-data""</code>.</p>
<pre class=""lang-html prettyprint-override""><code>&lt;form action=""upload"" method=""post"" enctype=""multipart/form-data""&gt;
&lt;input type=""text"" name=""description"" /&gt;
&lt;input type=""file"" name=""file"" /&gt;
&lt;input type=""submit"" /&gt;
&lt;/form&gt;
</code></pre>
<p>After submitting such a form, the binary multipart form data is available in the request body in <a href=""http://stackoverflow.com/questions/12156068/params-not-getting-passed-to-backing-bean-for-hcommandlink-under-richpopuppane/12159693#12159693"">a different format</a> than when the <code>enctype</code> isn't set.</p>
<p>Before Servlet 3.0, the Servlet API didn't natively support <code>multipart/form-data</code>. It supports only the default form enctype of <code>application/x-www-form-urlencoded</code>. The <code>request.getParameter()</code> and consorts would all return <code>null</code> when using multipart form data.</p>
<h2>Don't manually parse it!</h2>
<p>You can in theory parse the request body yourself based on <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getInputStream%28%29""><code>ServletRequest#getInputStream()</code></a>. However, this is a precise and tedious work which requires precise knowledge of <a href=""http://www.faqs.org/rfcs/rfc2388.html"">RFC2388</a>. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also <a href=""http://stackoverflow.com/questions/5038798/uploading-of-pdf-file"">uploading of pdf file</a>. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.</p>
<h2>When you're not on Servlet 3.0 yet, use Apache Commons FileUpload</h2>
<p>If you're not on Servlet 3.0 yet, the common practice is to make use of <a href=""http://commons.apache.org/fileupload"">Apache Commons FileUpload</a> to parse the multpart form data requests. It has an excellent <a href=""http://commons.apache.org/fileupload/using.html"">User Guide</a> and <a href=""http://commons.apache.org/fileupload/faq.html"">FAQ</a> (carefully go through both). There's also the O'Reilly (""<a href=""http://www.servlets.com/cos/"">cos</a>"") <code>MultipartRequest</code>, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.</p>
<p>In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's <code>/WEB-INF/lib</code>: </p>
<ul>
<li><a href=""http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi""><code>commons-fileupload.jar</code></a> </li>
<li><a href=""http://commons.apache.org/proper/commons-io/download_io.cgi""><code>commons-io.jar</code></a> </li>
</ul>
<p>Your initial attempt failed most likely because you forgot the commons IO. </p>
<p>Here's a kickoff example how the <code>doPost()</code> of your <code>UploadServlet</code> may look like when using Apache Commons FileUpload:</p>
<pre class=""lang-java prettyprint-override""><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List&lt;FileItem&gt; items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type=""text|radio|checkbox|etc"", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type=""file"").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException(""Cannot parse multipart request."", e);
}
// ...
}
</code></pre>
<p>Alternatively you can also wrap this all in a <code>Filter</code> which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using <code>request.getParameter()</code> the usual way and retrieve the uploaded file by <code>request.getAttribute()</code>. <a href=""http://balusc.blogspot.com/2007/11/multipartfilter.html"">You can find an example in this blog article</a>.</p>
<h2>When you're already on Servlet 3.0 or newer, use native API</h2>
<p>If you're already on the fresh new Servlet 3.0 API, then you can just use standard API provided <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getParts%28%29""><code>HttpServletRequest#getPart()</code></a> to collect the individual multipart form data items (most Servlet 3.0 implementations use Apache Commons FileUpload under the covers for this!). This is a bit less convenienced than when using pure Apache Commons FileUpload (a custom utility method is needed to get the filename), but it is workable and easier to use if you already know the input field names beforehand like as you would do with <code>getParameter()</code>. Also, normal form fields are since Servlet 3.0 available by <code>getParameter()</code> the usual way. </p>
<p>First annotate your servlet with <a href=""http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/MultipartConfig.html""><code>@MultipartConfig</code></a> in order to let it recognize and support <code>multipart/form-data</code> requests and thus get <code>getPart()</code> to work:</p>
<pre><code>@WebServlet(""/upload"")
@MultipartConfig
public class UploadServlet extends HttpServlet {
// ...
}
</code></pre>
<p>Then, implement its <code>doPost()</code> as follows:</p>
<pre class=""lang-java prettyprint-override""><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String description = request.getParameter(""description""); // Retrieves &lt;input type=""text"" name=""description""&gt;
Part filePart = request.getPart(""file""); // Retrieves &lt;input type=""file"" name=""file""&gt;
String filename = getFilename(filePart);
InputStream filecontent = filePart.getInputStream();
// ... (do your job here)
}
private static String getFilename(Part part) {
for (String cd : part.getHeader(""content-disposition"").split("";"")) {
if (cd.trim().startsWith(""filename"")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace(""\"""", """");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
</code></pre>
<p>This can all also be done in a <code>Filter</code> which does all the job transparently so that you can continue using the <code>request.getParameter()</code> the usual way. <a href=""http://balusc.blogspot.com/2009/12/uploading-files-in-servlet-30.html"">You can find an example in this article</a>.</p>
<h2>Workaround for GlassFish bug of <code>getParameter()</code> still returning <code>null</code></h2>
<p>Note that Glassfish versions older than 3.1.2 had <a href=""http://java.net/jira/browse/GLASSFISH-16740"">a bug</a> wherein the <code>getParameter()</code> still returns <code>null</code>. If you are targeting such a container and can't upgrade it, then you need to extract the value from <code>getPart()</code> as follows instead:</p>
<pre><code> String description = getValue(request.getPart(""description"")); // Retrieves &lt;input type=""text"" name=""description""&gt;
</code></pre>
<p>With this utility method:</p>
<pre><code>private static String getValue(Part part) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), ""UTF-8""));
StringBuilder value = new StringBuilder();
char[] buffer = new char[1024];
for (int length = 0; (length = reader.read(buffer)) &gt; 0;) {
value.append(buffer, 0, length);
}
return value.toString();
}
</code></pre>
<p>Hope this all helps :)</p>
","8772","16","3","30","2010-03-11 12:27:05","500","TRUE","511609","9"
"http://stackoverflow.com/users/303459","http://stackoverflow.com/questions/3481828","http://stackoverflow.com/questions/3481828/#3481842","2014-09-11 18:00:26","202","589948","55","15","How to split a String in Java","<p>I have a string ""004-034556"" that I want to split into two strings:</p>
<pre><code>string1=004
string2=034556
</code></pre>
<p>That means the first string will contain the characters before '-', and the second string will contain the characters after '-'. I also want to check if the string has '-' in it. If not, I will throw an exception. How can I do this?</p>
","29","369","<java><string>","2010-08-14 03:01:53","TRUE","FALSE","3481842","2014-08-30 07:37:53","445","<p>Just use the appropriate method: <a href=""http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-""><code>String#split()</code></a>.</p>
<pre><code>String string = ""004-034556"";
String[] parts = string.split(""-"");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
</code></pre>
<p>Note that this takes a <a href=""http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum"">regular expression</a>, so remember to escape special characters if necessary, e.g. if you want to split on period <code>.</code> which means ""any character"" in regex, use either <code>split(""\\."")</code> or <code>split(Pattern.quote("".""))</code>.</p>
<p>To test beforehand if the string contains a <code>-</code>, just use <a href=""http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contains-java.lang.CharSequence-""><code>String#contains()</code></a>.</p>
<pre><code>if (string.contains(""-"")) {
// Split it.
} else {
throw new IllegalArgumentException(""String "" + string + "" does not contain -"");
}
</code></pre>
<p>No, this does not take a regular expression.</p>
","1130","4","2","8","2010-08-14 03:05:34","4","TRUE","511609","0"
"http://stackoverflow.com/users/123891","http://stackoverflow.com/questions/4216745","http://stackoverflow.com/questions/4216745/#4216767","2014-06-21 04:48:53","194","444981","95","8","Java string to date conversion","<p>Can somebody recommend the best way to convert a string in the format 'January 2, 2010' to a date in java? Ultimately, I want to break out the month, the day, and the year as integers so that I can use:</p>
<pre><code>Date date = new Date();
date.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();
</code></pre>
<p>to convert the date into time.</p>
","30","394","<java><string><date><time>","2010-11-18 15:53:01","TRUE","FALSE","4216767","2013-05-09 16:47:08","465","<p>Don't do it, that's the hard way. Just use <a href=""http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html""><code>SimpleDateFormat</code></a> (click the link to see all format patterns).</p>
<pre><code>String string = ""January 2, 2010"";
Date date = new SimpleDateFormat(""MMMM d, yyyy"", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 BOT 2010
</code></pre>
<p>Here's an extract of relevance from <a href=""http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html"">the javadoc</a>, listing all available format patterns:</p>
<pre class=""lang-none prettyprint-override""><code>G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
u Day number of week Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
</code></pre>
","1724","2","1","4","2010-11-18 15:55:27","2","TRUE","511609","0"
"http://stackoverflow.com/users/24610","http://stackoverflow.com/questions/541194","http://stackoverflow.com/questions/541194/#541348","2013-07-24 13:56:03","109","58391","36","5","C# version of java's synchronized keyword?","<p>Does c# have its own version of the java ""synchronized"" keyword? </p>
<p>I.e. in java it can be specified either to a function, an object or a block of code, like so:</p>
<pre><code>public synchronized void doImportantStuff() {
// dangerous code goes here.
}
</code></pre>
<p>or</p>
<pre><code>public void doImportantStuff() {
// trivial stuff
synchronized {
// dangerous code goes here.
}
}
</code></pre>
","42","432","<c#><java><multithreading><synchronization>","2009-02-12 13:23:18","TRUE","FALSE","541348","2013-06-03 19:52:42","195","<p>First - most classes will never need to be thread-safe. Use <a href=""http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it"">YAGNI</a>: only apply thread-safety when you know you actually are going to use it (and test it).</p>
<p>For the method-level stuff, there is <code>[MethodImpl]</code>:</p>
<pre><code>[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}
</code></pre>
<p>This can also be used on accessors (properties and events):</p>
<pre><code>private int i;
public int SomeProperty
{
[MethodImpl(MethodImplOptions.Synchronized)]
get { return i; }
[MethodImpl(MethodImplOptions.Synchronized)]
set { i = value; }
}
</code></pre>
<p>Note that field-like events <em>are</em> synchronized by default, while auto-implemented properties <em>are not</em>:</p>
<pre><code>public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized
</code></pre>
<p>Personally, I don't like the implementation of <code>MethodImpl</code> as it locks <code>this</code> or <code>typeof(Foo)</code> - which is against best practice. The preferred option is to use your own locks:</p>
<pre><code>private readonly object syncLock = new object();
public void SomeMethod() {
lock(syncLock) { /* code */ }
}
</code></pre>
<p>Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a <code>lock(this)</code> / <code>lock(Type)</code> - however, <a href=""http://marcgravell.blogspot.co.uk/2010/03/revisited-fun-with-field-like-events.html"">in more recent compilers it uses <code>Interlocked</code></a> updates - so thread-safe without the nasty parts.</p>
<p>This allows more granular usage, and allows use of <code>Monitor.Wait</code>/<code>Monitor.Pulse</code> etc to communicate between threads.</p>
<p>A related <a href=""http://marcgravell.blogspot.com/2009/02/fun-with-field-like-events.html"">blog entry</a> (later <a href=""http://marcgravell.blogspot.co.uk/2010/03/revisited-fun-with-field-like-events.html"">revisited</a>).</p>
","2090","8","4","6","2009-02-12 14:00:48","37","TRUE","495227","12"
"http://stackoverflow.com/users/58737","http://stackoverflow.com/questions/1912475","http://stackoverflow.com/questions/1912475/#1912492","2011-11-09 19:06:06","10","2271","3","13","What is an abstract class?","<p>When I learned about abstract classes is said WT(H*)!!!</p>
<p>QUESTIONS:</p>
<ol>
<li>What is the point of creating a class that can't be instantiated?</li>
<li>Why would anybody want such a class?</li>
<li>What is the situation in which abstract classes become NECESSARY?</li>
</ol>
<p>*<em>if you know what i mean</em></p>
","26","332","<c#><java><oop>","2009-12-16 05:20:03","FALSE","FALSE","1912492","2011-11-09 19:06:06","16","<ol>
<li>most commonly to serve as a base-class or interface (some languages have a separate <code>interface</code> construct, some don't) - it doesn't <strong>know</strong> the implementation (that is to be provided by the subclasses / implementing classes)</li>
<li>abstraction and re-use</li>
<li>when the base-class can provide no meaningful default-implementation for a method (but allowing subclasses to re-use the non-abstract parts of the implementation; any fields, non-abstract methods, etc)</li>
</ol>
<p>For example:</p>
<pre><code>public abstract class Stream { /* lots of code, some abstract methods */ }
</code></pre>
<p>What the heck is a stream <strong>by itself</strong>? What <em>kind</em> of stream? a stream to a file? a network? a memory buffer? Each may have different and unrelated ways of reading / writing, but provide a common API. It makes <strong>no sense</strong> to create <em>just</em> a <code>Stream</code>, but via the <code>abstract</code> class, you can <em>code</em> to the <code>Stream</code> API without knowing the details:</p>
<pre><code>Stream s = CreateStream(...); // I don't *care* what kind of stream
s.Write(new byte[] {1,2,3,4,5});
s.Close();
</code></pre>
","1210","2","2","6","2009-12-16 05:25:28","5","TRUE","495227","0"
"http://stackoverflow.com/users/29544","http://stackoverflow.com/questions/374770","http://stackoverflow.com/questions/374770/#374776","2010-01-12 20:25:45","7","977","0","10","Chained IF structure","<p>Imagine this case where I have an object that I need to check a property.
However, the object can currently have a null value.</p>
<p>How can I check these two conditions in a single ""if"" condition?</p>
<p>Currently, I have to do something like this:</p>
<pre><code>if (myObject != null)
{
if (myObject.Id != pId)
{
myObject.Id = pId;
myObject.Order = pOrder;
}
}
</code></pre>
<p>I would like something like this:</p>
<pre><code>if (myObject != null &amp;&amp; myObject.Id != pId)
</code></pre>
<p>I want to evaluate the second condition only if the first was true.</p>
<p>Maybe I'm missing something, and that's why I need your help ;-)</p>
","20","681","<c#><java>","2008-12-17 14:51:41","TRUE","FALSE","374776","2010-01-12 20:25:45","43","<pre><code>if(myObject != null &amp;&amp; myObject.Id != pId)
{
myObject.Id = pId;
myObject.Order = pOrder;
}
</code></pre>
<p><code>&amp;&amp;</code> is a short-circuiting logic test - it only evaluates the right-hand-side if the left-hand-side is true. Contrast to ""a &amp; b"", which always evaluates both sides (and does a bitwise ""and"")</p>
","352","1","1","7","2008-12-17 14:53:34","2","TRUE","495227","0"
"http://stackoverflow.com/users/1581266","http://stackoverflow.com/questions/16540412","http://stackoverflow.com/questions/16540412/#16540535","2013-05-14 10:23:49","4","225","0","1","Why would we need void return type from methods in OOP languages?","<p>It's not that I've started learning Java yesterday, but suddenly I thought, why would we ever use <code>void</code> methods, if we can return <code>this</code> instead? That way we can chain method calls on object and make the code more readable (I know that this approach is gaining popularity already, but mostly with immutable objects, and lets forget about <em>Java Beans</em> convention). The only case I think of <code>void</code> being required is static methods.</p>
","65","478","<c#><java><oop>","2013-05-14 10:09:24","FALSE","FALSE","16540535","2013-05-14 10:23:49","14","<p>Presumably you will accept that some methods need to tell you something - some kind of return value. It seems artificial and obtuse that we would ""return the value we want to return, unless we don't actually want to return anything, in which case we return <code>this</code> instead, unless it is a static method, in which case we return <code>void</code>"".</p>
<p>How about:</p>
<ul>
<li>if it is appropriate to return something, then return it</li>
<li>if if isn't, then don't</li>
<li>(with some wriggle room for cases where a ""fluent"" API genuinely makes sense)</li>
</ul>
<p>Also: think inheritance; if I have a virtual method <code>Foo()</code>, then the return type would have to be <code>Foo</code>'s declaring type:</p>
<pre><code>public virtual SomeType Foo() {...}
</code></pre>
<p>Now imagine I subclass <code>SomeType</code>, with <code>Bar : SomeType</code> and have an instance of <code>Bar</code>:</p>
<pre><code>Bar obj = new Bar();
obj.Foo().SomeOtherMethodOnBar(); // ERROR hey, where did my Bar go!?!?!
</code></pre>
<p>polymorphism does not respect fluent APIs.</p>
<p>As a final thought: think of all the ""pop""s when you don't actually want to chain methods...</p>
","1198","6","2","4","2013-05-14 10:15:09","6","TRUE","495227","0"
"http://stackoverflow.com/users/158288","http://stackoverflow.com/questions/4303997","http://stackoverflow.com/questions/4303997/#4304015","2010-11-29 13:29:19","-2","1311","0","4","||(Or) Logical Operator in Java vs .Net","<p>I have been coding in Java(Mainly) and .Net for a while.</p>
<p>What I found is that the <code>||</code> logical operator in .Net is different in result to the <code>||</code> operator in Java.</p>
<p>Lets look at the following Java code:</p>
<pre><code>Object obj = null;
if(obj == null || obj.toString().isEmpty()){
System.out.println(""Object is null"");
}
</code></pre>
<p>The result of the code above will be:</p>
<p><strong>Object is null</strong></p>
<p>The reason for that is because <code>obj == null</code> is <code>true</code> and the second expression wasn't evaluated. If it was, I would have received a <code>java.lang.NullPointerException</code>.</p>
<p>And if I used the single or (<code>|</code>) I would also received a <code>NullPointerException</code> (Both are evaluated).</p>
<p>My question is the following:</p>
<p><em><strong>If the code was C#, I will always get a ObjectReferenceNotSet etc. exception because the obj value is null and the second expression is always evaluated (Regardless of the operator), meaning the result is different in C# than in Java.
If I would to change the C# code to work properly, I have to create two if statements.</em></strong></p>
<p><em><strong>Is there not an easier way to do this in C# to be similar to Java? (Keep it in one if with 2 expressions)</em></strong></p>
<p>Thank you.</p>
","39","1364","<c#><java><.net><logical-operators>","2010-11-29 13:04:19","TRUE","FALSE","4304015","2010-11-29 13:29:19","14","<p>The <code>||</code> operator in C# is short-circuiting, just like in Java. As is <code>&amp;&amp;</code>. The <code>|</code> and <code>&amp;</code> operators are <em>not</em> short-circuiting, just like in Java.</p>
<p>If your results are different, there is a bug in the code. Can you show us the offending C# please?</p>
<p>This works fine:</p>
<pre><code> object obj = null;
if(obj == null || string.IsNullOrEmpty(obj.ToString())) {
Console.WriteLine(""Object is null"");
}
</code></pre>
","515","3","1","2","2010-11-29 13:06:03","2","TRUE","495227","0"
"http://stackoverflow.com/users/31288","http://stackoverflow.com/questions/1135248","http://stackoverflow.com/questions/1135248/#1135317","2014-07-16 03:30:58","89","37450","12","2","Scala equivalent of Java java.lang.Class<T> Object","<p>The question is best explained by an example:</p>
<p>In Java for a JPA EntityManager, I can do the following(Account is my Entity class):</p>
<pre><code>Account result = manager.find(Account.class, primaryKey);
</code></pre>
<p>In Scala, my naive attempt is:</p>
<pre><code>val result = manager.find(Account.class, primaryKey)
</code></pre>
<p>But when I try to use <code>Account.class</code> in Scala, it seems to not like this. How can I specify the java.lang.Class object for the Account class in Scala?</p>
","50","520","<java><class><scala>","2009-07-16 03:24:50","TRUE","FALSE","1135317","2011-11-09 23:14:52","133","<p>According to ""<a href=""http://programming-scala.labs.oreilly.com/ch12.html"">The Scala Type System</a>"", </p>
<pre><code>val c = new C
val clazz = c.getClass // method from java.lang.Object
val clazz2 = classOf[C] // Scala method: classOf[C] ~ C.class
val methods = clazz.getMethods // method from java.lang.Class&lt;T&gt;
</code></pre>
<blockquote>
<p>The <code>classOf[T]</code> method returns the runtime representation for a Scala type. It is analogous to the Java expression <code>T.class</code>.<br>
Using <code>classOf[T]</code> is convenient when you have a type that you want information about, while <code>getClass</code> is convenient for retrieving the same information from an instance of the type.</p>
</blockquote>
<p>However, <code>classOf[T]</code> and <code>getClass</code> return slightly different values, reflecting the effect of type erasure on the JVM, in the case of getClass.</p>
<pre><code>scala&gt; classOf[C]
res0: java.lang.Class[C] = class C
scala&gt; c.getClass
res1: java.lang.Class[_] = class C
</code></pre>
<p>That is why the <a href=""http://www.nabble.com/-scala--getClass-returns-Class-_---td21534984.html"">following will not work</a>:</p>
<pre><code>val xClass: Class[X] = new X().getClass //it returns Class[_], nor Class[X]
val integerClass: Class[Integer] = new Integer(5).getClass //similar error
</code></pre>
<p>There is a <a href=""http://lampsvn.epfl.ch/trac/scala/ticket/490"">ticket regarding the return type of <code>getClass</code></a>.</p>
<p>(<a href=""http://stackoverflow.com/users/73046/james-moore"">James Moore</a> reports that the ticket is ""now"", ie Nov. 2011, two years later, fixed.<br>
In 2.9.1, <code>getClass</code> now does: </p>
<pre><code>scala&gt; ""foo"".getClass
res0: java.lang.Class[_ &lt;: java.lang.String] = class java.lang.String
</code></pre>
<p>)</p>
<p>Back in 2009:</p>
<blockquote>
<p>It would be useful if Scala were to treat the return from getClass() as a java.lang.Class[T] forSome { val T : C } where C is something like the erasure of the static type of the expression on which getClass is called</p>
<p>It would let me do something like the following where I want to introspect on a class but shouldn't need a class instance.<br>
I also want to limit the types of classes I want to introspect on, so I use Class[_ &lt;: Foo]. But this prevents me from passing in a Foo class by using Foo.getClass() without a cast. </p>
</blockquote>
<p>Note: regarding <code>getClass</code>, a possible workaround would be:</p>
<pre><code>class NiceObject[T &lt;: AnyRef](x : T) {
def niceClass : Class[_ &lt;: T] = x.getClass.asInstanceOf[Class[T]]
}
implicit def toNiceObject[T &lt;: AnyRef](x : T) = new NiceObject(x)
scala&gt; ""Hello world"".niceClass
res11: java.lang.Class[_ &lt;: java.lang.String] = class java.lang.String
</code></pre>
","2921","11","5","3","2009-07-16 03:59:53","35","TRUE","431338","0"
"http://stackoverflow.com/users/122547","http://stackoverflow.com/questions/1082437","http://stackoverflow.com/questions/1082437/#1082836","2014-06-03 13:37:13","63","56879","48","4","Android AlarmManager","<p>Can someone please show me some sample code on how to use an <code>AlarmManager</code> in ِAndroid.</p>
<p>I have been playing around with some code for a few days and it just won't work.</p>
<p>I need to trigger a block of code after 20 minutes from the <code>AlarmManager</code> being set.</p>
","20","301","<java><android><alarmmanager><android-alarms><android-1.5-cupcake>","2009-07-04 15:41:19","FALSE","FALSE","1082836","2013-11-29 13:58:45","85","<p>""Some sample code"" is not that easy when it comes to <code>AlarmManager</code>.</p>
<p>Here is a snippet showing the setup of <code>AlarmManager</code>:</p>
<pre><code>AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
</code></pre>
<p>In this example, I am using <code>setRepeating()</code>. If you want a one-shot alarm, you would just use <code>set()</code>. Be sure to give the time for the alarm to start in the same time base as you use in the initial parameter to <code>set()</code>. In my example above, I am using <code>AlarmManager.ELAPSED_REALTIME_WAKEUP</code>, so my time base is <code>SystemClock.elapsedRealtime()</code>.</p>
<p><a href=""https://github.com/commonsguy/cw-omnibus/tree/master/AlarmManager/Scheduled"">Here is a larger sample project</a> showing this technique.</p>
","1046","4","1","5","2009-07-04 19:30:03","229","TRUE","409813","0"
"http://stackoverflow.com/users/907921","http://stackoverflow.com/questions/11272839","http://stackoverflow.com/questions/11272839/#11273826","2014-04-15 10:48:03","19","14383","5","2","Non Deprecated findPreference() Method? - Android","<p>I want to detect when a <code>Preference</code> contained in a <code>ListView</code> gets clicked, so that I can launch an intent to manage that selection.</p>
<p>I would have done like this in my layout <code>XML</code> file:</p>
<pre><code>&lt;Preference android:title=""About"" android:key=""myKey""&gt;&lt;/Preference&gt;
</code></pre>
<p>And the following in my <code>java</code> code:</p>
<pre><code>Preference myPref = (Preference) findPreference(""myKey"");
myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//open browser or intent here
}
});
</code></pre>
<p>But the method <a href=""http://developer.android.com/reference/android/preference/PreferenceGroup.html#findPreference%28java.lang.CharSequence%29""><code>public Preference findPreference (CharSequence key)</code></a> is deprecated.</p>
<ol>
<li>Is there a non deprecated equivalent?</li>
<li>If not, what if I use it anyway?</li>
<li>How can <code>Fragments</code> help me do my task in a better way?Chek here: <a href=""http://stackoverflow.com/questions/6503496/preferences-without-deprecated-methods"">Preferences without deprecated methods</a>.</li>
</ol>
<hr>
<p>Here you can check the <code>XML</code> layout structure that my activity has, and a snapshot of the application:</p>
<p><strong>XML:</strong></p>
<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;PreferenceScreen xmlns:android=""http://schemas.android.com/apk/res/android"" &gt;
&lt;Preference
android:key=""about""
android:title=""@string/titleAbout""
android:summary=""@string/summaryAbout""
/&gt;
&lt;Preference
android:key=""labelTaxonomy""
android:title=""@string/titleLabelTaxonomy""
android:summary=""@string/summaryLabelTaxonomy""
/&gt;
&lt;/PreferenceScreen&gt;
</code></pre>
<p><strong>SNAPSHOT:</strong></p>
<p><img src=""http://i.stack.imgur.com/f2Y20.png"" alt=""snapshopt""></p>
<p>After clicking on the About (or Access Label Taxonomy) <code>Preference</code>, I'd like to open an <code>intent</code> of some kind (could also be a video or anything else...the names are misleading). </p>
","49","2245","<java><android><android-fragments><deprecated><android-preferences>","2012-06-30 08:54:48","TRUE","FALSE","11273826","2014-04-15 10:48:03","34","<blockquote>
<p>Is there a non deprecated equivalent?</p>
</blockquote>
<p>If you are using <code>PreferenceFragment</code> on API Level 11+ devices, you would call <code>findPreference()</code> on it. Otherwise, call <code>findPreference()</code> on your <code>PreferenceActivity</code>, as you have no choice.</p>
<blockquote>
<p>If not, what if I use it anyway?</p>
</blockquote>
<p>It will work.</p>
<blockquote>
<p>How can Fragments help me do my task in a better way?</p>
</blockquote>
<p>API Level 11+ introduced <code>PreferenceFragment</code> as another way of constructing the contents of a <code>PreferenceActivity</code>. You are welcome to use them, but if you are still supporting older devices, you cannot use <code>PreferenceFragment</code> for those devices.</p>
<p>That being said:</p>
<blockquote>
<p>I want to detect when a Preference contained in a ListView gets clicked, so that I can launch an intent to manage that selection.</p>
</blockquote>
<p>You do not need Java code for this. Use:</p>
<pre><code> &lt;PreferenceScreen
android:title=""@string/title_intent_preference""
android:summary=""@string/summary_intent_preference""&gt;
&lt;intent android:action=""android.intent.action.VIEW""
android:data=""http://www.android.com"" /&gt;
&lt;/PreferenceScreen&gt;
</code></pre>
<p>(as seen in the <a href=""http://developer.android.com/reference/android/preference/PreferenceActivity.html"">JavaDocs for <code>PreferenceActivity</code></a>)</p>
<p>This will create an entry in the preference UI that, when clicked, will start an activity with the specified <code>Intent</code>.</p>
","1670","11","1","9","2012-06-30 11:46:58","172","TRUE","409813","0"
"http://stackoverflow.com/users/130076","http://stackoverflow.com/questions/3064423","http://stackoverflow.com/questions/3064423/#3064447","2014-01-17 08:42:51","179","142870","28","8","Java - easily convert array to set","<p>I'd like to convert an array to a set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:</p>
<pre><code>java.util.Arrays.asList(Object[] a);
</code></pre>
<p>Any ideas?</p>
","34","254","<java><collections><arrays><set>","2010-06-17 18:23:56","TRUE","FALSE","3064447","2011-11-18 14:31:14","319","<p>Like this:</p>
<pre><code>Set&lt;T&gt; mySet = new HashSet&lt;T&gt;(Arrays.asList(someArray));
</code></pre>
","113","1","1","12","2010-06-17 18:27:37","4","TRUE","404779","0"
"http://stackoverflow.com/users/440093","http://stackoverflow.com/questions/3231684","http://stackoverflow.com/questions/3231684/#3231702","2011-01-25 16:10:15","22","7006","3","5","Are Java enums considered primitive or reference types?","<p>If I have an enum object, is it considered a primitive or a reference?</p>
","55","78","<java>","2010-07-12 19:41:15","FALSE","FALSE","3231702","2010-07-12 19:53:26","27","<p>It's a reference type.</p>
<p>Unlike many languages, in which an <code>enum</code> is a set of integral constansts, Java enums are immutable object instances. You can get the numeric value of an enum instance by calling <code>ordinal()</code>.</p>
<p>You can even add your own members to the enum class, like this:</p>
<pre><code>public enum Operation {
PLUS { double eval(double x, double y) { return x + y; } },
MINUS { double eval(double x, double y) { return x - y; } },
TIMES { double eval(double x, double y) { return x * y; } },
DIVIDE { double eval(double x, double y) { return x / y; } };
// Do arithmetic op represented by this constant
abstract double eval(double x, double y);
}
//Elsewhere:
Operation op = Operation.PLUS;
double two = op.eval(1, 1);
</code></pre>
","801","3","1","7","2010-07-12 19:43:02","2","TRUE","404779","0"
"http://stackoverflow.com/users/2443","http://stackoverflow.com/questions/273485","http://stackoverflow.com/questions/273485/#273488","2014-05-15 20:30:54","19","5492","0","5","Why doesn't java's assert statement allow you to specify a message?","<p>Seems likes it might be useful to have the assert display a message when an assertion fails.</p>
<p>Currently an AssertionError gets thrown, but I don't think you have the power to specify a custom message for it.</p>
<p>Am I wrong?</p>
<p>If I am please correct me, and if I'm correct can you provide a mechanism for doing this (other than creating your own exception type and throwing it).</p>
","67","402","<java><assert>","2008-11-07 20:11:33","FALSE","FALSE","273488","2014-05-15 20:30:54","46","<p>You certainly can:</p>
<pre><code>assert x &gt; 0 : ""x must be greater than zero, but x = "" + x;
</code></pre>
<p>See <a href=""http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html"">Programming with Assertions</a> for more information.</p>
","266","2","1","4","2008-11-07 20:12:42","1","TRUE","370108","8"
"http://stackoverflow.com/users/108869","http://stackoverflow.com/questions/1789164","http://stackoverflow.com/questions/1789164/#1789177","2009-11-27 17:33:35","4","4380","3","9","iterator for loops with break","<p>let say my code look like below</p>
<pre><code>for(..)
for(..)
for(..){
break; //this will break out from the most inner loop OR all 3 iterated loops?
}
</code></pre>
","29","194","<java>","2009-11-24 10:23:43","TRUE","FALSE","1789177","2009-11-27 17:33:35","26","<p>Your example will break out of the innermost loop only. However, using a <a href=""http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html"">labeled break</a> statement, you can do this:</p>
<pre><code>outer:
for(..)
for(..)
for(..){
break outer; //this will break out from all three loops
}
</code></pre>
","349","1","1","9","2009-11-24 10:26:12","3","TRUE","370108","0"
"http://stackoverflow.com/users/133458","http://stackoverflow.com/questions/1678520","http://stackoverflow.com/questions/1678520/#1678526","2014-09-15 11:50:09","24","96739","13","13","javac not working in windows command prompt","<p>I'm trying to use javac with the windows command prompt, but its not working.</p>
<p>After adding the directory ""C:\Program Files\Java\jdk1.6.0_16\bin\"" to the end of the environment path variable, the java command works fine, but using javac gives me the error:</p>
<pre><code>'javac' is not recognized as an internal or external command, operable program or batch file.
</code></pre>
<p>Any ideas? Thanks.</p>
","43","418","<java><windows><javac><command-prompt><path-variables>","2009-11-05 05:26:37","TRUE","FALSE","1678526","2009-11-05 05:46:31","32","<p>If you added it in the control panel while your command prompt was open, that won't affect your current command prompt. You'll need to exit and re-open or simply do:</p>
<pre><code>set path=""%path%;c:\program files\java\jdk1.6.0_16\bin""
</code></pre>
<p>By way of checking, execute:</p>
<pre><code>echo %path%
</code></pre>
<p>from your command prompt and let us know what it is.</p>
<p>Otherwise, make sure there <em>is</em> a javac in that directory by trying:</p>
<pre><code>""c:\program files\java\jdk1.6.0_16\bin\javac.exe""
</code></pre>
<p>from the command prompt. You can also tell <em>which</em> executable (if any) is being used with the command:</p>
<pre><code>for %i in (javac.exe) do @echo %~$PATH:i
</code></pre>
<p>This is a neat trick similar to the <code>which</code> and/or <code>whence</code> commands in some UNIX-type operating systems.</p>
","872","6","4","5","2009-11-05 05:29:41","3","TRUE","355306","0"
"http://stackoverflow.com/users/273212","http://stackoverflow.com/questions/2375649","http://stackoverflow.com/questions/2375649/#2375830","2014-07-17 10:41:39","21","83362","0","5","Converting to upper and lower case in Java","<p>I want to convert the first character of a string to Uppercase and the rest of the characters to lowercase. How can I do it? </p>
<p>Example:</p>
<pre><code>String inputval=""ABCb"" OR ""a123BC_DET"" or ""aBcd""
String outputval=""Abcb"" or ""A123bc_det"" or ""Abcd""
</code></pre>
","42","276","<java><string>","2010-03-03 22:56:29","TRUE","FALSE","2375830","2014-07-17 10:41:39","40","<p>Try this on for size:</p>
<pre><code>String properCase (String inputVal) {
// Empty strings should be returned as-is.
if (inputVal.length() == 0) return """";
// Strings with only one character uppercased.
if (inputVal.length() == 1) return inputVal.toUpperCase();
// Otherwise uppercase first letter, lowercase the rest.
return inputVal.substring(0,1).toUpperCase()
+ inputVal.substring(1).toLowerCase();
}
</code></pre>
","461","1","1","1","2010-03-03 23:27:32","31","TRUE","355306","1"
"http://stackoverflow.com/users/1151746","http://stackoverflow.com/questions/9580457","http://stackoverflow.com/questions/9580457/#9580485","2014-09-11 18:17:50","13","36046","4","5","FIFO class in Java","<p>I want to implement FIFO through a class in Java.</p>
<p>Does such a class already exist? If not, how can I implement my own?</p>
<p><strong>NOTE</strong></p>
<p>I found a class here <a href=""http://www.dcache.org/manuals/cells/docs/api/dmg/util/Fifo.html"">http://www.dcache.org/manuals/cells/docs/api/dmg/util/Fifo.html</a>, but it doesn't contain dmg.util.*. I don't know if such a package even exists.</p>
","18","415","<java><fifo>","2012-03-06 08:50:07","FALSE","FALSE","9580485","2014-09-11 18:17:50","41","<p>You're looking for any class that implements the <a href=""http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html"" rel=""nofollow"">Queue interface</a>, excluding <code>PriorityQueue</code> and <code>PriorityBlockingQueue</code>, which do not use a FIFO algorithm.</p>
<p>Probably a <a href=""http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html"" rel=""nofollow"">LinkedList</a> using <code>add</code> (adds one to the end) and <code>removeFirst</code> (removes one from the front and returns it) is the easiest one to use.</p>
<p>For example, here's a program that uses a LinkedList to queue and retrieve the digits of PI:</p>
<pre><code>import java.util.LinkedList;
class Test {
public static void main(String args[]) {
char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
LinkedList&lt;Integer&gt; fifo = new LinkedList&lt;Integer&gt;();
for (int i = 0; i &lt; arr.length; i++)
fifo.add (new Integer (arr[i]));
System.out.print (fifo.removeFirst() + ""."");
while (! fifo.isEmpty())
System.out.print (fifo.removeFirst());
System.out.println();
}
}
</code></pre>
<hr>
<p>Alternatively, if you <em>know</em> you only want to treat it as a queue (without the extra features of a linked list), you can just use the <code>Queue</code> interface itself:</p>
<pre><code>import java.util.LinkedList;
import java.util.Queue;
class Test {
public static void main(String args[]) {
char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
Queue&lt;Integer&gt; fifo = new LinkedList&lt;Integer&gt;();
for (int i = 0; i &lt; arr.length; i++)
fifo.add (new Integer (arr[i]));
System.out.print (fifo.remove() + ""."");
while (! fifo.isEmpty())
System.out.print (fifo.remove());
System.out.println();
}
}
</code></pre>
<p>This has the advantage of allowing you to replace the underlying concrete class with any class that provides the <code>Queue</code> interface, without having to change the code too much.</p>
<p>The basic changes are to change the type of <code>fifo</code> to a <code>Queue</code> and to use <code>remove()</code> instead of <code>removeFirst()</code>, the latter being unavailable for the <code>Queue</code> interface.</p>
<p>Calling <code>isEmpty()</code> is still okay since that belongs to the <code>Collection</code> interface of which <code>Queue</code> is a derivative.</p>
","2452","7","2","6","2012-03-06 08:52:49","2","TRUE","355306","6"
"http://stackoverflow.com/users/114798","http://stackoverflow.com/questions/929773","http://stackoverflow.com/questions/929773/#929781","2014-07-25 03:49:16","10","28289","1","9","Calculating the distance between two points","<p>I need to create a class which calculates the distance between two points. I am stuck and I am a total beginner. Here are my classes:</p>
<pre><code>package org.totalbeginner.tutorial;
public class Punkt {
public double x;
public double y;
Punkt(double xkoord, double ykoord){
this.x = xkoord;
this.y = ykoord;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
</code></pre>
<p>The second class.</p>
<pre><code>package org.totalbeginner.tutorial;
public class Strecke{
double x;
double y;
Punkt p1 = new Punkt(2.0,2.0);
Punkt p2 = new Punkt(4.0,4.0);
Punkt mp = new Punkt(x,y);
public void mittelpunkt(){
x = (p1.getX() + p2.getX()) / 2;
y = (p1.getY() + p2.getY()) / 2;
}
}
</code></pre>
<p>I am not sure how to get a point object (the middle point) between both defined points.</p>
<p>I can create point objects but I am not sure how to return a point object through my <code>mittelpunkt()</code> method that lies between those two point objects.</p>
","43","1105","<java>","2009-05-30 14:05:26","TRUE","FALSE","929781","2012-05-27 10:31:44","26","<p>The distance between two points (x1,y1) and (x2,y2) on a flat surface is:</p>
<pre><code> ____________________
/ 2 2
\/ (y2-y1) + (x2-x1)
</code></pre>
<p>But, if all you want is the midpoint (<code>mittelpunkt</code>) of your two points, you should change your midpoint function to:</p>
<pre><code>public Punkt mittelpunkt (Punkt p1, Punkt p2) {
return new Punkt ((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
}
</code></pre>
<p>This will return a brand new point object with the points set to the middle of the given two points (without having to concern yourself with any other math). And, since your second class is a line, you only need the two end points to describe it, so I'd make some minor changes.</p>
<p>First <code>Punkt.java</code> (Point):</p>
<pre><code>class Punkt {
double x, y;
Punkt (double xkoord, double ykoord) {
this.x = xkoord;
this.y = ykoord;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
</code></pre>
<p>Then <code>Strecke.java</code> (Line):</p>
<pre><code>public class Strecke {
Punkt p1, p2;
Strecke (Punkt punkt1, Punkt punkt2) {
this.p1 = punkt1;
this.p2 = punkt2;
}
public Punkt mittelPunkt() {
return new Punkt ((p1.getX()+p2.getX())/2, (p1.getY()+p2.getY())/2);
}
public double abstand() {
return Math.sqrt(
(p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) +
(p1.getY() - p2.getY()) * (p1.getY() - p2.getY())
);
}
static public void main (String args[]) {
Strecke s = new Strecke (new Punkt(2.0, 2.0), new Punkt(5.0, 6.0));
Punkt mp = s.mittelPunkt();
System.out.println (""Midpoint = ("" + mp.getX() + "","" + mp.getY() + "")"");
double as = s.abstand();
System.out.println (""Length = "" + as);
}
}
</code></pre>
<p>These two files, when compiled and run with the endpoints <code>2,2</code> and <code>5,6</code> (the hypotenuse of a classic 3/4/5 right-angled triangle), generate the correct:</p>
<pre><code>Midpoint = (3.5,4.0)
Length = 5.0
</code></pre>
","2176","6","5","6","2009-05-30 14:10:57","5","TRUE","355306","0"
"http://stackoverflow.com/users/182959","http://stackoverflow.com/questions/1656506","http://stackoverflow.com/questions/1656506/#1656540","2012-07-14 23:22:37","10","2920","8","15","Which of these pieces of code is faster in Java?","<p><strong>a)</strong> <code>for(int i = 100000; i &gt; 0; i--) {}</code></p>
<p><strong>b)</strong> <code>for(int i = 1; i &lt; 100001; i++) {}</code></p>
<p>The answer is there on <a href=""http://www.mydeveloperconnection.com/html/JavaTrap.htm"" rel=""nofollow"">this website</a> (question 3). I just can't figure out <strong><em>why?</em></strong></p>
","48","354","<java><performance><micro-optimization>","2009-11-01 05:53:32","FALSE","FALSE","1656540","2012-07-14 23:22:37","61","<p>When you get down to the lowest level (machine code but I'll use assembly since it maps one-to-one mostly), the difference between an empty loop decrementing to 0 and one incrementing to 50 (for example) is often along the lines of:</p>
<pre><code> ld a,50 ld a,0
loop: dec a loop: inc a
jnz loop cmp a,50
jnz loop
</code></pre>
<p>That's because the zero flag in most sane CPUs is set by the decrement instruction when you reach zero. The same can't usually be said for the increment instruction when it reaches 50 (since there's nothing special about that value, unlike zero). So you need to compare the register with 50 to set the zero flag.</p>
<hr>
<p>However, asking which of the two loops:</p>
<pre><code>for(int i = 100000; i &gt; 0; i--) {}
for(int i = 1; i &lt; 100001; i++) {}
</code></pre>
<p>is faster (in pretty much <em>any</em> environment, Java or otherwise) is useless since neither of them does anything useful. The <em>fastest</em> version of both those loops no loop at all. I challenge anyone to come up with a faster version than that :-)</p>
<p>They'll only become useful when you start doing some useful work inside the braces and, at that point, the <em>work</em> will dictate which order you should use.</p>
<p>For example if you <em>need</em> to count from 1 to 100,000, you should use the second loop. That's because the advantage of counting down (if any) is likely to be swamped by the fact that you have to evaluate <code>100000-i</code> inside the loop every time you need to use it. In assembly terms, that would be the difference between:</p>
<pre><code> ld b,100000 dsw a
sub b,a
dsw b
</code></pre>
<p>(<code>dsw</code> is, of course, the infamous <code>do something with</code> assembler mnemonic).</p>
<p>Since you'll only be taking the hit for an incrementing loop once per iteration, and you'll be taking the hit for the subtraction <em>at least</em> once per iteration (assuming you'll be using <code>i</code>, otherwise there's little need for the loop at all), you should just go with the more natural version.</p>
<p>If you need to count up, count up. If you need to count down, count down.</p>
","2267","9","3","6","2009-11-01 06:27:40","34","TRUE","355306","0"
"http://stackoverflow.com/users/38663","http://stackoverflow.com/questions/563544","http://stackoverflow.com/questions/563544/#563564","2009-11-24 20:02:24","9","12976","3","5","java bit manipulation","<pre><code>byte x = -1;
for(int i = 0; i &lt; 8; i++)
{
x = (byte) (x &gt;&gt;&gt; 1);
System.out.println(""X: "" + x);
}
</code></pre>
<p>As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia). </p>
<p>Also, from the java docs:
""The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator "">>>"" shifts a zero into the leftmost position, while the leftmost position after "">>"" depends on sign extension. ""</p>
<p>Which means that >>> would shift a 0 to the left most bit every time. So I expect this code to be</p>
<p>iteration: bit representation of x</p>
<p>0: 11111111</p>
<p>1: 01111111</p>
<p>2: 00111111</p>
<p>3: 00011111</p>
<p>...so on</p>
<p>However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position. So I then try >>, and same result.</p>
<p>What's going on? I would expect my output to be: X: -1, x: 127, x: 63, etc.</p>
<p>Please help.</p>
<p>jbu</p>
","21","1081","<java><bit-manipulation><byte>","2009-02-19 01:08:43","TRUE","FALSE","563564","2009-02-19 01:23:14","21","<p>Whoever thought that bytes should be signed when Java was invented should be taken out and beaten with a wet stick of celery until they cry :-)</p>
<p>You can do what you want by casting up to an int and ensuring you never shift a 1 into the top bit, something like this:</p>
<pre><code>byte x = -1;
int x2 = ((int)x) &amp; 0xff;
for(int i = 0; i &lt; 8; i++)
{
x2 = (x2 &gt;&gt;&gt; 1);
System.out.println(""X: "" + x2);
}
</code></pre>
<p>Your particular problem is because >>> is casting up to an int to do the shift, then you're casting it back to a byte, as shown here:</p>
<pre><code>byte x = -1;
int x2 = ((int)x) &amp; 0xff;
int x3;
int x4 = x2;
for(int i = 0; i &lt; 8; i++)
{
x2 = (x2 &gt;&gt;&gt; 1);
System.out.println(""X2: "" + x2);
x3 = (x &gt;&gt;&gt; 1);
x = (byte)x3;
x4 = (x4 &gt;&gt;&gt; 1);
System.out.println(""X: "" + x3 + "" "" + x + "" "" + x4);
}
</code></pre>
<p>Which outputs:</p>
<pre><code>X2: 127
X: 2147483647 -1 127
X2: 63
X: 2147483647 -1 63
X2: 31
X: 2147483647 -1 31
X2: 15
X: 2147483647 -1 15
X2: 7
X: 2147483647 -1 7
X2: 3
X: 2147483647 -1 3
X2: 1
X: 2147483647 -1 1
X2: 0
X: 2147483647 -1 0
</code></pre>
<p>You can clearly see that x and x3 don't work (even though x3 shifts correctly, casting it back to byte in x sets it to -1 again). x4 works perfectly.</p>
","1333","5","3","4","2009-02-19 01:16:34","8","TRUE","355306","4"
"http://stackoverflow.com/users/523874","http://stackoverflow.com/questions/4397757","http://stackoverflow.com/questions/4397757/#4397863","2014-02-12 21:07:34","8","16952","4","8","How can i check to see if my sqlite table has data in it?","<p><strong>EDIT,
Changed the code slightly based on answers below, but still haven't got it working. I also added a log message to tell me if getCount was returning > 0, and it was, so i supect somthing might be wrong with my query? or my use of the cursor..</strong></p>
<p>I've created a table, and i want to check if its empty or not, if it's empty i want to run some insert statements (that are stored in an array).</p>
<p>Below is my code, while i have no errors, when i pull the .db file out i can see that it doesn't work. How would you approach this problem? </p>
<pre><code>public void onCreate(SQLiteDatabase db) {
Log.i(""DB onCreate"", ""Creating the database..."");//log message
db.execSQL(createCATBUDTAB);
db.execSQL(createTWOWEETAB);
try{
Cursor cur = db.rawQuery(""SELECT COUNT(*) FROM CAT_BUD_TAB"", null);
if (cur.getCount() &gt; 0){
Log.i(""DB getCount"", "" getcount greater than 0"");//log message
//do nothing everything's as it should be
}
else{//put in these insert statements contained in the array
Log.i(""DB getCount"", "" getcount less than 0, should read array"");//log message
for(int i=0; i&lt;13; i++){
db.execSQL(catInsertArray[i]);
}
}
}catch(SQLiteException e){System.err.println(""Exception @ rawQuery: "" + e.getMessage());}
}
</code></pre>
<p>Sorry if this is a pretty stupid question or approach, i'm new to all this. Any answers much appreciated!</p>
","57","1544","<java><sql><android><database><sqlite>","2010-12-09 11:36:49","TRUE","FALSE","4397863","2013-02-13 22:03:47","21","<p>The query <code>SELECT COUNT(*)</code> on an existing table should <em>never</em> return null. If there are no rows in the table, it should return one row containing the value zero.</p>
<p>Conversely, a row with a non-zero value indicates that it's <em>not</em> empty.</p>
<p>In both cases, one row should be returned, meaning that it will always go through the</p>
<pre><code>//do nothing everything's as it should be
</code></pre>
<p>section.</p>
<p>To fix it, leave your query as-is (you don't want to do <code>select column_name</code> simply because that would be unnecessary and possibly a little inefficient). Leave it as <code>select count(*)</code>, which will always return one row, and use the following code (tested only in my head so be careful):</p>
<pre><code>Cursor cur = db.rawQuery(""SELECT COUNT(*) FROM CAT_BUD_TAB"", null);
if (cur != null) {
cur.moveToFirst(); // Always one row returned.
if (cur.getInt (0) == 0) { // Zero count means empty table.
for (int i = 0; i &lt; 13; i++) {
db.execSQL (catInsertArray[i]);
}
}
}
</code></pre>
","1140","5","2","6","2010-12-09 11:49:24","13","TRUE","355306","0"
"http://stackoverflow.com/users/1076742","http://stackoverflow.com/questions/9122277","http://stackoverflow.com/questions/9122277/#9122291","2013-06-13 22:41:41","6","10467","2","8","What is a non recursive solution for Fibonacci-like sequence in Java?","<p>Given this pseudo code of a function</p>
<pre><code>f(0) = 1;
f(1) = 3;
f(n) = 3 * f(n - 1) - f(n - 2); // for n &gt;= 2.
</code></pre>
<p>Is there a non recursive way of doing this?</p>
","69","194","<java><algorithm><math><recursion>","2012-02-03 00:51:14","TRUE","FALSE","9122291","2012-09-28 02:44:17","26","<p>Yes, all recursive algorithms can be converted into iterative ones. The recursive solution to your problem is something like (pseudo-code):</p>
<pre><code>def f(n):
if n == 0: return 1
if n == 1: return 3
return 3 * f(n-1) - f(n-2)
</code></pre>
<p>Since you only have to remember the previous two terms to calculate the current one, you can use something like the following pseudo-code:</p>
<pre><code>def f(n):
if n == 0: return 1
if n == 1: return 3
grandparent = 1
parent = 3;
for i = 2 to n:
me = 3 * parent - grandparent
grandparent = parent
parent = me
return me
</code></pre>
<p>This simply handles the ""recursive"" termination condition first then iterates where it would normally recurse. At each iteration, you calculate the current term, then rotate the terms through the grandparent and parent.</p>
<p>There is no need to keep the grandparent around once you've calculated the current iteration since it's no longer used.</p>
<p>In fact, it could be said that the iterative solution is better (from a performance viewpoint) since terms are not recalculated as they are in the recursive solution. The recursive solution <em>does</em> have a certain elegance about it though (recursive solutions generally do).</p>
<hr>
<p>Of course, like the Fibonacci sequence, that value you calculate rises very quickly so, if you want what's possibly the fastest solution (you should check all performance claims, including mine), a pre-calculated lookup table may be the way to go.</p>
<p>Using the following Java code to create a table of long values (that <code>while</code> condition is just a sneaky trick to catch overflow, which is the point at which you can stop building the array):</p>
<pre><code>class GenLookup {
public static void main(String args[]) {
long a = 1, b = 3, c;
System.out.print (""long lookup[] = { "" + a + ""L, "" + b + ""L"");
c = 3 * b - a;
while ((c + a) / 3 == b) {
System.out.print ("", "" + c + ""L"");
a = b; b = c; c = 3 * b - a;
}
System.out.println ("" };"");
}
}
</code></pre>
<p>gives you an array definition that you can just plug in to a lookup function, as per the following example:</p>
<pre><code>public static long fn (int n) {
long lookup[] = { 1L, 3L, 8L, 21L, 55L, 144L, 377L, 987L, 2584L, 6765L,
17711L, 46368L, 121393L, 317811L, 832040L, 2178309L, 5702887L,
14930352L, 39088169L, 102334155L, 267914296L, 701408733L,
1836311903L, 4807526976L, 12586269025L, 32951280099L, 86267571272L,
225851433717L, 591286729879L, 1548008755920L, 4052739537881L,
10610209857723L, 27777890035288L, 72723460248141L, 190392490709135L,
498454011879264L, 1304969544928657L, 3416454622906707L,
8944394323791464L, 23416728348467685L, 61305790721611591L,
160500643816367088L, 420196140727489673L, 1100087778366101931L,
2880067194370816120L, 7540113804746346429L };
if ((n &lt; 1) || (n &gt; lookup.length))
return -1L;
return lookup[n-1];
}
</code></pre>
<hr>
<p>Interestingly enough, WolframAlpha comes up with a formulaic approach that doesn't even use iteration. If you go to <a href=""http://www.wolframalpha.com/"">their site</a> and enter <code>f(0)=1, f(1)=3, f(n)=3f(n-1)-f(n-2)</code>, you'll get back the formula:</p>
<p><img src=""http://i.stack.imgur.com/0lUPU.png"" alt=""enter image description here""></p>
<p>Unfortunately, it may not be as fast as the iteration, given the limited number of input values that result in something that can fit in a Java <code>long</code>, since it uses floating point. It's almost certainly (but, again, you would need to check this) slower than a table lookup.</p>
<p>And, it's probably perfect in the world of maths where real-world limits like non-infinite storage don't come into play but, possibly due to the limits of IEEE precision, it breaks down at higher values of <code>n</code>.</p>
<p>The following functions are the equivalent of that expression and the lookup solution:</p>
<pre><code>class CheckWolf {
public static long fn2 (int n) {
return (long)(
(5.0 - 3.0 * Math.sqrt(5.0)) *
Math.pow(((3.0 - Math.sqrt(5.0)) / 2.0), n-1) +
(5.0 + 3.0 * Math.sqrt(5.0)) *
Math.pow(((3.0 + Math.sqrt(5.0)) / 2.0), n-1)
) / 10;
}
public static long fn (int n) {
long lookup[] = { 1L, 3L, 8L, 21L, 55L, 144L, 377L, 987L, 2584L, 6765L,
17711L, 46368L, 121393L, 317811L, 832040L, 2178309L, 5702887L,
14930352L, 39088169L, 102334155L, 267914296L, 701408733L,
1836311903L, 4807526976L, 12586269025L, 32951280099L, 86267571272L,
225851433717L, 591286729879L, 1548008755920L, 4052739537881L,
10610209857723L, 27777890035288L, 72723460248141L, 190392490709135L,
498454011879264L, 1304969544928657L, 3416454622906707L,
8944394323791464L, 23416728348467685L, 61305790721611591L,
160500643816367088L, 420196140727489673L, 1100087778366101931L,
2880067194370816120L, 7540113804746346429L };
if ((n &lt; 1) || (n &gt; lookup.length)) return -1L;
return lookup[n-1];
}
</code></pre>
<p>Now we need a mainline to compare them:</p>
<pre><code> public static void main(String args[]) {
for (int i = 1; i &lt; 50; i++)
if (fn(i) != fn2(i))
System.out.println (""BAD: "" + i + "": "" + fn(i) + "", "" + fn2(i)
+ "" ("" + Math.abs(fn(i) - fn2(i)) + "")"");
else
System.out.println (""GOOD: "" + i + "": "" + fn(i) + "", "" + fn2(i));
}
}
</code></pre>
<p>This will output:</p>
<pre><code>GOOD: 1: 1, 1
GOOD: 2: 3, 3
GOOD: 3: 8, 8
GOOD: 4: 21, 21
GOOD: 5: 55, 55
GOOD: 6: 144, 144
GOOD: 7: 377, 377
GOOD: 8: 987, 987
GOOD: 9: 2584, 2584
GOOD: 10: 6765, 6765
GOOD: 11: 17711, 17711
GOOD: 12: 46368, 46368
GOOD: 13: 121393, 121393
GOOD: 14: 317811, 317811
GOOD: 15: 832040, 832040
GOOD: 16: 2178309, 2178309
GOOD: 17: 5702887, 5702887
GOOD: 18: 14930352, 14930352
GOOD: 19: 39088169, 39088169
GOOD: 20: 102334155, 102334155
GOOD: 21: 267914296, 267914296
GOOD: 22: 701408733, 701408733
GOOD: 23: 1836311903, 1836311903
GOOD: 24: 4807526976, 4807526976
GOOD: 25: 12586269025, 12586269025
</code></pre>
<p>Looking good up to here, some more:</p>
<pre><code>GOOD: 26: 32951280099, 32951280099
GOOD: 27: 86267571272, 86267571272
GOOD: 28: 225851433717, 225851433717
GOOD: 29: 591286729879, 591286729879
GOOD: 30: 1548008755920, 1548008755920
GOOD: 31: 4052739537881, 4052739537881
GOOD: 32: 10610209857723, 10610209857723
GOOD: 33: 27777890035288, 27777890035288
GOOD: 34: 72723460248141, 72723460248141
GOOD: 35: 190392490709135, 190392490709135
GOOD: 36: 498454011879264, 498454011879264
</code></pre>
<p>But then something starts going awry:</p>
<pre><code>BAD: 37: 1304969544928657, 1304969544928658 (1)
BAD: 38: 3416454622906707, 3416454622906709 (2)
BAD: 39: 8944394323791464, 8944394323791472 (8)
BAD: 40: 23416728348467685, 23416728348467705 (20)
BAD: 41: 61305790721611591, 61305790721611648 (57)
BAD: 42: 160500643816367088, 160500643816367232 (144)
BAD: 43: 420196140727489673, 420196140727490048 (375)
</code></pre>
<p>The fact that the above are tantalisingly close, and that the number of digits in the error is proportional to the number of digits in the result, indicates it's probably a loss-of-precision problem.</p>
<p>After this point, the formulaic function just starts returning the maximum long value:</p>
<pre><code>BAD: 44: 1100087778366101931, 922337203685477580 (177750574680624351)
BAD: 45: 2880067194370816120, 922337203685477580 (1957729990685338540)
BAD: 46: 7540113804746346429, 922337203685477580 (6617776601060868849)
</code></pre>
<p>And then our lookup function breaks down as well since the numbers are too big for a long:</p>
<pre><code>BAD: 47: -1, 922337203685477580 (922337203685477581)
BAD: 48: -1, 922337203685477580 (922337203685477581)
BAD: 49: -1, 922337203685477580 (922337203685477581)
</code></pre>
","8170","20","11","17","2012-02-03 00:52:37","1","TRUE","355306","0"
"http://stackoverflow.com/users/133374","http://stackoverflow.com/questions/3584945","http://stackoverflow.com/questions/3584945/#3585432","2010-08-30 09:13:45","16","1850","8","8","non-technical benefits of having string-type immutable","<p>I am wondering about the benefits of having the string-type immutable from the programmers point-of-view.</p>
<p>Technical benefits (on the compiler/language side) can be summarized mostly that it is easier to do optimisations if the type is immutable. Read <a href=""http://stackoverflow.com/questions/2916358/immutable-strings-vs-stdstring"">here</a> for a related question.</p>
<p>Also, in a mutable string type, either you have thread-safety already built-in (then again, optimisations are harder to do) or you have to do it yourself. You will have in any case the choice to use a mutable string type with built-in thread safety, so that is not really an advantage of immutable string-types. (Again, it will be easier to do the handling and optimisations to ensure thread-safety on the immutable type but that is not the point here.)</p>
<p>But what are the benefits of immutable string-types in the usage? What is the point of having some types immutable and others not? That seems very inconsistent to me.</p>
<p>In C++, if I want to have some string to be immutable, I am passing it as const reference to a function (<code>const std::string&amp;</code>). If I want to have a changeable copy of the original string, I am passing it as <code>std::string</code>. Only if I want to have it mutable, I am passing it as reference (<code>std::string&amp;</code>). So I just have the choice about what I want to do. I can just do this with every possible type.</p>
<p>In Python or in Java, some types are immutable (mostly all primitive types and strings), others are not.</p>
<p>In pure functional languages like Haskell, everything is immutable.</p>
<p>Is there a good reason why it make sense to have this inconsistency? Or is it just purely for technical lower level reasons?</p>
","54","1791","<java><c++><python><string><immutability>","2010-08-27 14:06:32","FALSE","FALSE","3585432","2010-08-30 09:13:45","15","<blockquote>
<p>What is the point of having some
types immutable and others not?</p>
</blockquote>
<p>Without <em>some</em> mutable types, you'd have to go the whole hog to pure functional programming -- a completely different paradigm than the OOP and procedural approaches which are currently most popular, and, while extremely powerful, apparently very challenging to a lot of programmers (what happens when you <em>do</em> need side effects in a language where nothing is mutable, and in real-world programming of course you inevitably do, is part of the challenge -- Haskell's <a href=""http://en.wikipedia.org/wiki/Monad_%28functional_programming%29"" rel=""nofollow"">Monads</a> are a very elegant approach, for example, but how many programmers do you know that fully and confidently understand them and can use them as well as typical OOP constructs?-).</p>
<p>If you don't understand the enormous value of having multiple paradigms available (both FP one <em>and</em> ones crucially relying on mutable data), I recommend studying Haridi's and Van Roy's masterpiece, <a href=""http://www.info.ucl.ac.be/~pvr/book.html"" rel=""nofollow"">Concepts, Techniques, and Models of Computer Programming</a> -- ""a <a href=""http://mitpress.mit.edu/sicp/"" rel=""nofollow"">SICP</a> for the 21st Century"", as I once described it;-).</p>
<p>Most programmers, whether familiar with Haridi and Van Roy or not, will readily admit that having at least <strong>some</strong> mutable data types is important to them. Despite the sentence I've quoted above from your Q, which takes a completely different viewpoint, I believe that may also be the root of your perplexity: <strong>not</strong> ""why some of each"", but rather ""why some <em>immutables</em> at all"".</p>
<p>The ""thoroughly mutable"" approach was once (accidentally) obtained in a Fortran implementation. If you had, say,</p>
<pre><code> SUBROUTINE ZAP(I)
I = 0
RETURN
</code></pre>
<p>then a program snippet doing, e.g.,</p>
<pre><code> PRINT 23
ZAP(23)
PRINT 23
</code></pre>
<p>would print 23, then 0 -- the <strong>number 23</strong> had been mutated, so all references to 23 in the rest of the program would in fact refer to 0. Not a bug in the compiler, technically: Fortran had subtle rules about what your program is and is not allowed to do in passing constants vs variables to procedures that assign to their arguments, and this snippet violates those little-known, non-compiler-enforceable rules, so it's a but in the program, not in the compiler. In practice, of course, the number of bugs caused this way was unacceptably high, so typical compilers soon switched to less destructive behavior in such situations (putting constants in read-only segments to get a runtime error, if the OS supported that; or, passing a fresh <em>copy</em> of the constant rather than the constant itself, despite the overhead; and so forth) even though technically they were program bugs allowing the compiler to display undefined behavior quite ""correctly"";-).</p>
<p>The alternative enforced in some other languages is to add the complication of multiple ways of parameter passing -- most notably perhaps in C++, what with by-value, by-reference, by constant reference, by pointer, by constant pointer, ... and then of course you see programmers baffled by declarations such as <code>const foo* const bar</code> (where the rightmost <code>const</code> is basically irrelevant if <code>bar</code> is an argument to some function... but crucial instead if <code>bar</code> is a <em>local variable</em>...!-).</p>
<p>Actually Algol-68 probably went farther along this direction (if you can have a value and a reference, why not a reference to a reference? or reference to reference to reference? &amp;c -- Algol 68 put no limitations on this, and the rules to define what was going on are perhaps the subtlest, hardest mix ever found in an ""intended for real use"" programming language). Early C (which only had by-value and by-explicit-pointer -- no <code>const</code>, no references, no complications) was no doubt in part a reaction to it, as was the original Pascal. But <code>const</code> soon crept in, and complications started mounting again.</p>
<p>Java and Python (among other languages) cut through this thicket with a powerful machete of simplicity: all argument passing, <em>and</em> all assignment, is ""by object reference"" (never reference to a variable or other reference, never semantically implicit copies, &amp;c). Defining (at least) numbers as semantically immutable preserves programmers' sanity (as well as this precious aspect of language simplicity) by avoiding ""oopses"" such as that exhibited by the Fortran code above.</p>
<p>Treating strings as primitives just like numbers is quite consistent with the languages' intended high semantic level, because in real life we <em>do</em> need strings that are just as simple to use as numbers; alternatives such as defining strings as lists of characters (Haskell) or as arrays of characters (C) poses challenges to both the compiler (keeping efficient performance under such semantics) and the programmer (effectively ignoring this arbitrary structuring to enable use of strings as simple primitives, as real life programming often requires).</p>
<p>Python went a bit further by adding a simple immutable container (<code>tuple</code>) and tying <em>hashing</em> to ""effective immutability"" (which avoids certain surprises to the programmer that are found, e.g., in Perl, with its hashes allowing mutable strings as keys) -- and why not? Once you have immutability (a precious concept that saves the programmer from having to learn about N different semantics for assignment and argument passing, with N tending to increase with time;-), you might as well get full mileage out of it;-).</p>
","5825","12","2","1","2010-08-27 14:57:49","51","TRUE","342489","0"
"http://stackoverflow.com/users/69514","http://stackoverflow.com/questions/2799755","http://stackoverflow.com/questions/2799755/#2799781","2014-05-18 07:25:11","3","15469","1","4","Rotate array clockwise","<p>I have a two dimensional array that I need to rotate 90 degrees clockwise, however I keep getting arrayindexoutofbounds...</p>
<pre><code>public int[][] rorateArray(int[][] arr){
//first change the dimensions vertical length for horizontal length
//and viceversa
int[][] newArray = new int[arr[0].length][arr.length];
//invert values 90 degrees clockwise by starting from button of
//array to top and from left to right
int ii = 0;
int jj = 0;
for(int i=0; i&lt;arr[0].length; i++){
for(int j=arr.length-1; j&gt;=0; j--){
newArray[ii][jj] = arr[i][j];
jj++;
}
ii++;
}
return newArray;
}
</code></pre>
","22","761","<java><algorithm><arrays>","2010-05-10 00:36:52","TRUE","FALSE","2799781","2010-05-10 00:52:57","7","<p>I don't understand your loops' logic -- shouldn't it be</p>
<pre><code> for(int i=0; i&lt;arr[0].length; i++){
for(int j=arr.length-1; j&gt;=0; j--){
newArray[i][j] = arr[j][i];
}
}
</code></pre>
<p>Net of whether each index goes up, like <code>i</code> here, or down, like <code>j</code> here (and of whether either or both need to be ""flipped"" in the assignment, e.g using <code>arr.length-1-j</code> in lieu of plain <code>j</code> on one side of the <code>=</code> in the assignment;-), since <code>arr</code> dimensions are <code>arr.length</code> by <code>arr[0].length</code>, and vice versa for <code>newArray</code>, it seems to me that the first index on <code>arr</code> (second on <code>newArray</code>) must be the one spanning the range from 0 to <code>arr.length-1</code> included, and the other range for the other index.</p>
<p>This is a kind of ""basic dimensional analysis"" (except that ""dimension"" is used in a different sense than normally goes with ""dimensional analysis"" which refers to physical dimensions, i.e., time, mass, length, &c;-). The issue of ""flipping"" and having each loop go up or down depend on visualizing exactly what you mean and I'm not the greatest ""mental visualizer"" so I think, in real life, I'd try the various variants of this ""axis transposition"" until I hit the one that's meant;-).</p>
","1377","3","1","4","2010-05-10 00:47:49","11","TRUE","342489","0"
"http://stackoverflow.com/users/337504","http://stackoverflow.com/questions/2805224","http://stackoverflow.com/questions/2805224/#2805296","2010-05-10 18:55:27","17","1225","2","7","Why aren't arrays expandable?","<p>When we create an array, we cannot change its size; it's fixed. OK, seems nice, we can create a new bigger array and copy the values one by one and that's little slow. What's the technical background of it?</p>
","29","214","<java><arrays><size>","2010-05-10 18:14:06","FALSE","FALSE","2805296","2010-05-10 18:28:45","21","<p>This question didn't mention a language so I'm going to choose 'C' based arrays for my answer. </p>
<p>Arrays are allocated as a single chunk of memory. Growing an array is problematic because the only way to do it properly is to grow it at the end. For a growth of size N there must be at least N free bytes at the end of the array before the next allocated address. </p>
<p>Supporting this type of allocation necessitates that allocations be spread across the virtual address space. This both removes the benefits of having memory allocations closer to each other and serves to increase fragmentation. This flies in the face of most memory managers which try to pack memory together and reduce fragmentation. </p>
<p>Allocating a new array at a place in memory with sufficient space and copying the array there is simply not an option as a general solution. The reason why is that the previous location of the array is visible to consumers through pointers.</p>
<pre><code>int* array = malloc(int*someSize);
int* pointer1 = &amp;(arr[2]);
growArray(&amp;array, 12); // Can't move because pointer1 knows the address of the array
</code></pre>
","1159","4","1","3","2010-05-10 18:22:09","8","TRUE","341544","0"
"http://stackoverflow.com/users/297115","http://stackoverflow.com/questions/3142817","http://stackoverflow.com/questions/3142817/#3142824","2010-06-30 15:47:16","4","1496","0","4","Java immutable-class rules","<p>Is the below class immutable:</p>
<pre><code>final class MyClass {
private final int[] array;
public MyClass(int[] array){
this.array = array;
}
}
</code></pre>
","26","185","<java><immutability>","2010-06-29 16:44:54","TRUE","FALSE","3142824","2010-06-30 15:47:16","20","<p>No it is not because the elements of the array can still be changed. </p>
<pre><code>int[] v1 = new int[10];
MyClass v2 = new MyClass(v1);
v1[0] = 42; // mutation visible to MyClass1
</code></pre>
","203","1","1","7","2010-06-29 16:45:48","1","TRUE","341544","0"
"http://stackoverflow.com/users/599184","http://stackoverflow.com/questions/9643563","http://stackoverflow.com/questions/9643563/#9643569","2012-03-10 03:37:50","1","602","0","4","Omit first parameter in for loop","<p>In PHP, Java, C++ (and many other languages), for loops are used like this:</p>
<pre><code>for(int i=0;i&lt;10;i++)
</code></pre>
<p>If I already initialized <code>i</code>, how can I omit the initialization statement?</p>
","32","228","<java><php><c++><for-loop>","2012-03-10 02:55:59","TRUE","FALSE","9643569","2012-03-10 03:37:50","10","<p>In Java, C++ and PHP it is completely valid to omit the initialization portion of the <code>for</code> loop</p>
<pre><code>int i = 0;
...
for(; i &lt; 10; i++);
</code></pre>
<p>This is true of most languages which have a <code>for</code> loop structure</p>
","263","2","1","2","2012-03-10 02:57:55","2","TRUE","341544","0"
"http://stackoverflow.com/users/2254173","http://stackoverflow.com/questions/15946674","http://stackoverflow.com/questions/15946674/#15946711","2013-04-11 11:18:45","0","505","0","2","looking for help call a perl script with arguments from java class","<p>I have to call a Perl script from a Java class. I am able to do that using </p>
<pre><code>final ProcessBuilder builder = new ProcessBuilder(""perl"", ""/home/abc.pl"");
</code></pre>
<p>I am wondering if I can pass parameters something like </p>
<pre><code>new ProcessBuilder(""perl"", ""/home/abc.pl x y"");
</code></pre>
<p>But it's throwing an error. </p>
<p>Could someone please suggest how this could be done?</p>
","66","421","<java><perl><perl-module>","2013-04-11 10:40:04","TRUE","FALSE","15946711","2013-04-11 10:53:22","2","<p>From <a href=""http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html"" rel=""nofollow"">the documentation</a>:</p>
<blockquote>
<p><code>ProcessBuilder pb = new ProcessBuilder(""myCommand"", ""myArg1"", ""myArg2"");</code></p>
</blockquote>
<p>Each argument to the program you are calling needs to be a separate argument to the ProcessBuilder constructor.</p>
<pre><code>new ProcessBuilder(""perl"", ""/home/abc.pl"", ""x"", ""y"");
</code></pre>
<p>Otherwise you are calling the equivalent of <code>perl ""/home/abc.pl x y""</code> and it will be unable to find a file called ""/home/abc.pl x y"" (since x and y are different arguments, not part of the file name).</p>
","678","4","1","1","2013-04-11 10:42:32","2","TRUE","337500","0"
"http://stackoverflow.com/users/421730","http://stackoverflow.com/questions/11897817","http://stackoverflow.com/questions/11897817/#11897834","2012-08-10 08:21:06","0","279","0","1","Android JSON Parse Error Undetermined Object","<p>I have a json with the following contents:</p>
<pre><code>{
""Dictionary"":[
{
""word"": ""abc""
""meaning"": ""meaning of abc""
},
{
""word"": ""def""
""meaning"": ""meaning of def""
}
]
}
</code></pre>
<p>The code which I have written for parsing the json file is as follows:</p>
<pre><code> public class JSONParser extends Activity
{
static JSONObject jObj = null;
static String json = """";
// constructor
public JSONParser()
{
}
public JSONObject getJSONFromInput(InputStream location)
{
InputStream isr = location;
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try
{
Reader reader = new BufferedReader(new InputStreamReader(isr,""UTF-8""));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
isr.close();
json = writer.toString();
}
catch (Exception e)
{
Log.e(""Buffer Error"", ""Error converting result "" + e.toString());
}
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e(""JSON Parser"", ""Error parsing data "" + e.toString());
}
// return JSON String
return jObj;
}
}
</code></pre>
<p>I'm getting the below Error:</p>
<pre><code>E/JSON Parser(555): Error parsing data org.json.JSONException: Unterminated object at character 47 of {
E/JSON Parser(555): ""Dictionary"":[
E/JSON Parser(555): {
E/JSON Parser(555): ""word"": ""abc""
E/JSON Parser(555): ""meaning"": ""meaning of abc""
E/JSON Parser(555): },
E/JSON Parser(555): {
E/JSON Parser(555): ""word"": ""def""
E/JSON Parser(555): ""meaning"": ""meaning of def""
E/JSON Parser(555): }
E/JSON Parser(555): ]
E/JSON Parser(555): }
</code></pre>
<p>Can anyone help me out.</p>
","44","2094","<java><javascript><android>","2012-08-10 08:15:46","TRUE","FALSE","11897834","2012-08-10 08:21:06","5","<p>Key/Value pairs in objects are separated by commas. Your input is missing them.</p>
<p>Original and corrected (in that order):</p>
<pre><code> { ""word"": ""abc"" ""meaning"": ""meaning of abc"" },
{ ""word"": ""abc"", ""meaning"": ""meaning of abc"" },
</code></pre>
<p>See also, the output of <a href=""http://jsonlint.com/"">JSON Lint</a>:</p>
<pre><code>Parse error on line 4:
... ""word"": ""abc""""meaning"": ""meaning
-----------------------^
Expecting '}', ':', ',', ']'
</code></pre>
","489","3","2","1","2012-08-10 08:17:19","2","TRUE","337500","0"
"http://stackoverflow.com/users/556328","http://stackoverflow.com/questions/4662215","http://stackoverflow.com/questions/4662215/#4662265","2014-06-20 18:42:26","63","71927","18","7","How to extract a substring using regex","<p>I have a string that has two single quotes in it, the <code>'</code> character. In between the single quotes is the data I want.</p>
<p>How can I write a regex to extract ""the data i want"" from the following text?</p>
<pre><code>mydata = ""some string with 'the data i want' inside"";
</code></pre>
","38","302","<java><regex><string><text-extraction>","2011-01-11 20:22:49","TRUE","FALSE","4662265","2011-01-11 20:46:22","99","<p>Assuming you want the part between single quotes, use this regular expression with a <a href=""http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html""><code>Matcher</code></a>:</p>
<pre><code>""'(.*?)'""
</code></pre>
<p>Example:</p>
<pre><code>String mydata = ""some string with 'the data i want' inside"";
Pattern pattern = Pattern.compile(""'(.*?)'"");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
</code></pre>
<p>Result:</p>
<pre>
the data i want
</pre>
<p><a href=""http://ideone.com/KmWqn"">(ideone)</a></p>
","598","4","2","3","2011-01-11 20:27:45","5","TRUE","326921","0"
"http://stackoverflow.com/users/1146504","http://stackoverflow.com/questions/4403542","http://stackoverflow.com/questions/4403542/#4403570","2014-06-23 15:38:42","40","32024","7","11","How does java do modulus calculations with negative numbers?","<p>Am I doing modulus wrong? Because in Java <code>-13 % 64</code> is supposed to evaluate to <code>-13</code> but I get <code>51</code>.</p>
","60","142","<java><math><modulo><negative-number>","2010-12-09 21:57:28","FALSE","FALSE","4403570","2010-12-09 23:18:17","58","<p>Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.</p>
<p>If you want to get a negative number for negative inputs then you can use this:</p>
<pre><code>int r = x % n;
if (r &gt; 0 &amp;&amp; x &lt; 0)
{
r -= n;
}
</code></pre>
<p>Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:</p>
<pre><code>int r = x % n;
if (r &lt; 0)
{
r += n;
}
</code></pre>
","500","3","2","2","2010-12-09 22:00:02","3","TRUE","326921","0"
"http://stackoverflow.com/users/1006201","http://stackoverflow.com/questions/7853502","http://stackoverflow.com/questions/7853502/#7853536","2014-08-03 14:55:08","36","163646","7","7","How to convert/parse from String to char in java?","<p>So the question is very basic: How to parse a String value to char type?<br>
I know how to do it to int and double (for example Integer.parseInt(""123"")), but then chars... there isn't any class like that for them, is there?</p>
","49","231","<java><string><parsing><char>","2011-10-21 18:09:20","FALSE","FALSE","7853536","2014-08-03 14:55:08","59","<p>If your string contains exactly one character the simplest way to convert it to a character is probably to call the <a href=""http://download.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29""><code>charAt</code></a> method:</p>
<pre><code>char c = s.charAt(0);
</code></pre>
","296","1","1","1","2011-10-21 18:12:06","3","TRUE","326921","1"
"http://stackoverflow.com/users/428390","http://stackoverflow.com/questions/4067809","http://stackoverflow.com/questions/4067809/#4067825","2014-07-21 20:52:48","21","58960","2","10","How to check space in string?","<p>How can i check if a string contains a white space or empty space or "" "". </p>
<p>looking for Java example. </p>
<p>example <code>String = ""test word"";</code> </p>
<p>Thanking you. </p>
","29","192","<java><string><space>","2010-11-01 09:38:32","FALSE","FALSE","4067825","2010-11-01 09:59:02","31","<p>For checking if a string <em>contains whitespace</em> use a <code>Matcher</code> and call it's find method.</p>
<pre><code>Pattern pattern = Pattern.compile(""\\s"");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
</code></pre>
<p>If you want to check if it <em>only consists of whitespace</em> then you can use <code>String.matches</code>:</p>
<pre><code>boolean isWhitespace = s.matches(""^\\s*$"");
</code></pre>
","441","2","2","2","2010-11-01 09:41:21","3","TRUE","326921","0"
"http://stackoverflow.com/users/507512","http://stackoverflow.com/questions/5317320","http://stackoverflow.com/questions/5317320/#5317339","2013-03-04 19:53:20","14","21602","0","1","ReGex to check string contains only Hex characters","<p>I have never done regex before, and I have seen they are very useful for working with strings. I saw a few <a href=""http://www.vogella.de/articles/JavaRegularExpressions/article.html"">tutorials</a> (for example) but I still cannot understand how to make a simple java regex check for hexadecimal characters in a string.</p>
<p>The user will input in the text box something like: <code>0123456789ABCDEF</code> and I would like to know that the input was correct otherwise if something like <code>XTYSPG456789ABCDEF</code> when return false.</p>
<p>Is it possible to do that with a regex or did I missunderstood how they work?</p>
","50","634","<java><regex><string><input-validation><hex>","2011-03-15 20:02:02","FALSE","FALSE","5317339","2011-03-15 20:15:14","52","<p>Yes, you can do that with a regular expression:</p>
<pre>
^[0-9A-F]+$
</pre>
<p>Explanation:</p>
<pre>
^ Start of line.
[0-9A-F] Character class: Any character in 0 to 9, or in A to F.
+ Quantifier: One or more of the above.
$ End of line.
</pre>
<hr>
<p>To use this regular expression in Java you can for example call the <code>matches</code> method on a String:</p>
<pre><code>boolean isHex = s.matches(""[0-9A-F]+"");
</code></pre>
<p>Note that <code>matches</code> finds only an exact match so you don't need the start and end of line anchors in this case. See it working online: <a href=""http://ideone.com/o8Sop"">ideone</a></p>
<p>You may also want to allow both upper and lowercase A-F, in which case you can use this regular expression:</p>
<pre>
^[0-9A-Fa-f]+$
</pre>
","823","5","1","7","2011-03-15 20:03:38","1","TRUE","326921","0"
"http://stackoverflow.com/users/282315","http://stackoverflow.com/questions/2444019","http://stackoverflow.com/questions/2444019/#2444025","2014-06-30 11:45:41","11","38257","5","5","How do I generate a random integer between min and max in java?","<p>What method returns a random int between a min and max? Or does no such method exist?</p>
<p>What I'm looking for is something like this: </p>
<pre><code>NAMEOFMETHOD (min, max)
</code></pre>
<p>(where min and max are <code>int</code>s) </p>
<p>that returns soemthing like this: </p>
<pre><code>8
</code></pre>
<p>(randomly) </p>
<p>If such a method does exist could you please link to the relevant documentation with your answer. thanks. </p>
<p>Update: atempting to implement the full solution in the nextInt answer I have this: </p>
<pre><code>class TestR
{
public static void main (String[]arg)
{
Random random = new Random() ;
int randomNumber = random.nextInt(5) + 2;
System.out.println (randomNumber) ;
}
}
</code></pre>
<p>I'm still getting the same errors from the complier: </p>
<pre><code>TestR.java:5: cannot find symbol
symbol : class Random
location: class TestR
Random random = new Random() ;
^
TestR.java:5: cannot find symbol
symbol : class Random
location: class TestR
Random random = new Random() ;
^
TestR.java:6: operator + cannot be applied to Random.nextInt,int
int randomNumber = random.nextInt(5) + 2;
^
TestR.java:6: incompatible types
found : &lt;nulltype&gt;
required: int
int randomNumber = random.nextInt(5) + 2;
^
4 errors
</code></pre>
<p>What's going wrong here? </p>
","63","1518","<java><random>","2010-03-14 22:20:46","TRUE","FALSE","2444025","2010-03-14 23:09:47","31","<p>Construct a Random object at application startup:</p>
<pre><code>Random random = new Random();
</code></pre>
<p>Then use <a href=""http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html#nextInt%28int%29"">Random.nextInt(int)</a>:</p>
<pre><code>int randomNumber = random.nextInt(max - min) + min;
</code></pre>
<p>Note that the lower limit is inclusive, but the upper limit is exclusive.</p>
","404","3","2","11","2010-03-14 22:22:31","2","TRUE","326921","0"
"http://stackoverflow.com/users/368616","http://stackoverflow.com/questions/3056703","http://stackoverflow.com/questions/3056703/#3056725","2010-06-16 19:56:57","11","26093","1","1","SimpleDateFormat","<p><br>
The following code is giving me the parsed date as ""Wed Jan 13 00:00:00 EST 2010""
instead of ""Wed Jun 13 00:00:00 EST 2010"". Any ideas much appreciated.</p>
<pre><code> SimpleDateFormat sf = new SimpleDateFormat(""yyyy-mm-dd'T'HH:mm:ss"");
String str = ""2010-06-13T00:00:00"";
Date date = sf.parse(str);
System.out.println("" Date "" + date.toString());
</code></pre>
","16","401","<java><simpledateformat>","2010-06-16 19:54:13","TRUE","FALSE","3056725","2010-06-16 19:56:57","33","<p>Try:</p>
<pre><code>""yyyy-MM-dd'T'HH:mm:ss""
</code></pre>
<p><code>MM</code> means month. <code>mm</code> means minutes. See the documentation for <a href=""http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html""><code>SimpleDateFormat</code></a> for more details of the supported date and time patterns.</p>
","328","2","1","4","2010-06-16 19:56:57","2","TRUE","326921","0"
"http://stackoverflow.com/users/457708","http://stackoverflow.com/questions/3844934","http://stackoverflow.com/questions/3844934/#3844959","2014-02-28 08:25:41","11","1709","4","3","Why is this statement not working in java x ^= y ^= x ^= y;","<pre><code>int x=1;
int y=2;
x ^= y ^= x ^= y;
</code></pre>
<p>I am expecting the values to be swapped.But it gives x=0 and y=1.
when i tried in C language it gives the correct result.</p>
","59","191","<java><swap><undefined-behavior><xor>","2010-10-02 08:23:30","TRUE","FALSE","3844959","2010-10-02 09:23:40","50","<p>Your statement is roughly equivalent to this expanded form:</p>
<pre><code>x = x ^ (y = y ^ (x = x ^ y));
</code></pre>
<p>Unlike in C, in Java the left operand of a binary operator is guaranteed to be evaluated before the right operand. Evaluation occurs as follows:</p>
<pre><code>x = x ^ (y = y ^ (x = x ^ y))
x = 1 ^ (y = 2 ^ (x = 1 ^ 2))
x = 1 ^ (y = 2 ^ (x = 3))
x = 1 ^ (y = 2 ^ 3) // x is set to 3
x = 1 ^ (y = 1)
x = 1 ^ 1 // y is set to 1
x = 0 // x is set to 0
</code></pre>
<p>You could reverse the order of the arguments to each xor expression so that the assignment is done before the variable is evaluated again:</p>
<pre><code>x = (y = (x = x ^ y) ^ y) ^ x
x = (y = (x = 1 ^ 2) ^ y) ^ x
x = (y = (x = 3) ^ y) ^ x
x = (y = 3 ^ y) ^ x // x is set to 3
x = (y = 3 ^ 2) ^ x
x = (y = 1) ^ x
x = 1 ^ x // y is set to 1
x = 1 ^ 3
x = 2 // x is set to 2
</code></pre>
<p>This is a more compact version that also works:</p>
<pre><code>x = (y ^= x ^= y) ^ x;
</code></pre>
<p>But this is a truly horrible way to swap two variables. It's a much better idea to use a temporary variable.</p>
","1228","5","4","4","2010-10-02 08:29:53","6","TRUE","326921","0"
"http://stackoverflow.com/users/51649","http://stackoverflow.com/questions/1902317","http://stackoverflow.com/questions/1902317/#1902342","2011-07-27 12:44:14","0","1800","0","2","Convert APPLET tags to OBJECT tags for IE6","<p>I have converted the following applet tags to object tags so that it can work. But for some reason the below isn't working. Firstly, <strong>Is the below a correct conversion that should work?</strong></p>
<p>Applet:</p>
<pre><code>document.writeln('&lt;applet');
document.writeln(' code=""LittleShootApplet""');
document.writeln(' id=""LittleShootApplet"" name=""LittleShootApplet""');
document.writeln(' scriptable=""true""');
document.writeln(' mayscript=""true""');
document.writeln(' height=""0"" width=""0""');
document.writeln(' style=""xdisplay: none; width:0; height:0; padding:0; margin:0;"" &gt;');
document.writeln('&lt;/applet&gt;');
</code></pre>
<p>Object:</p>
<pre><code>document.writeln('&lt;OBJECT ');
document.writeln('classid=""clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"" width=""0"" height=""0""&gt;');
document.writeln('&lt;PARAM name=""code"" value=""LittleShootApplet""&gt;');
document.writeln('&lt;PARAM name=""id"" value=""LittleShootApplet""&gt;');
document.writeln('&lt;PARAM name=""scriptable"" value=""true""&gt;');
document.writeln('&lt;PARAM name=""mayscript"" value=""true""&gt;');
document.writeln('&lt;PARAM name=""style"" value=""xdisplay: none; width:0; height:0; padding:0; margin:0;""&gt;');
document.writeln('&lt;/OBJECT&gt;');
</code></pre>
<p>Btw, I am using JavaScript to write the above to the page.</p>
<p>I have a button on the page which tries to call a Java Applet function using JavaScript but I get this error.</p>
<pre><code>Message: 'document.LittleShootApplet' is null or not an object
Line: 77
Char: 1
Code: 0
URI: http://localhost/webs/front-end/activity.php
</code></pre>
<p>The above Javascript is having trouble calling functions from the Java applet because the applet hasn't been loaded properly.</p>
<p>Thanks all for any help.</p>
","42","1778","<java><javascript><applet>","2009-12-14 17:33:33","TRUE","FALSE","1902342","2011-07-27 12:44:14","1","<p>Add the <em>ID</em> and <em>Name</em> attributes directly to the <code>object</code> tag, not as <code>param</code>'s:</p>
<pre><code>&lt;OBJECT classid=""clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"" width=""0""
id=""LittleShootApplet"" name=""LittleShootApplet""&gt;
...
&lt;/OBJECT&gt;
</code></pre>
<p><em>Removed document.write for readability.</em></p>
<p>And I would recommend you to get the elements by ID, not by <code>document.elementName</code>:</p>
<pre><code> var applet = document.getElementById('LittleShootApplet');
// instead of document.LittleShootApplet
</code></pre>
","588","3","2","1","2009-12-14 17:39:46","6","TRUE","324566","0"
"http://stackoverflow.com/users/2443","http://stackoverflow.com/questions/88434","http://stackoverflow.com/questions/88434/#88456","2014-04-10 15:33:24","13","3409","3","3","How can I detect if caps lock is toggled in Swing?","<p>I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on.</p>
<p>Is this possible? And if so I'd like to have it detected before the client types their first letter.</p>
<p>Is there a non-platform specific way to do this?</p>
","50","317","<java><swing>","2008-09-17 22:42:25","FALSE","FALSE","88456","2014-04-10 15:33:24","18","<p>Try this, from java.awt.Toolkit, returns a boolean:</p>
<pre><code>Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)
</code></pre>
","155","1","1","4","2008-09-17 22:45:48","3","TRUE","322200","0"
"http://stackoverflow.com/users/282315","http://stackoverflow.com/questions/2367185","http://stackoverflow.com/questions/2367185/#2367197","2010-03-03 00:14:16","5","2756","1","7","'Exception in thread ""main"" java.lang.NoClassDefFoundError' when running java program from command line","<p>What am I doing wrong here: </p>
<pre><code>class Helo {
// main: generate some simple output
public static void main (String[] args) {
System.out.println (""Hello, world.""); // print one line
System.out.println (""How are you?""); // print another
}
}
</code></pre>
<p>When I go into terminal I do: </p>
<pre><code>cd ~
javac Atempt2.java (//that's the file name)
java Atempt2
</code></pre>
<p>and then it gives me this error message: </p>
<pre><code>Exception in thread ""main"" java.lang.NoClassDefFoundError: Atempt2
</code></pre>
<p>So all in all this is what I do and what happens: </p>
<pre><code>david-allenders-macbook-pro:~ davidallender$ cd ~
david-allenders-macbook-pro:~ davidallender$ javac Atempt2.java
david-allenders-macbook-pro:~ davidallender$ java Atempt2
Exception in thread ""main"" java.lang.NoClassDefFoundError: Atempt2
david-allenders-macbook-pro:~ davidallender$
</code></pre>
<p>I am very new at this so please explain things in a very simple manner. </p>
<p>Thanks. </p>
","103","1036","<java>","2010-03-02 22:06:15","TRUE","FALSE","2367197","2010-03-03 00:14:16","6","<p>Rename your <code>Atempt2.java</code> to <code>Hello.java</code> to get going, then:</p>
<pre><code>javac Helo.java
java Helo
</code></pre>
<p>See <a href=""http://stackoverflow.com/questions/1841847/can-i-compile-a-java-file-with-a-different-name-than-the-class"">here for more discussion and the reasoning</a>.</p>
","320","2","1","2","2010-03-02 22:08:20","2","TRUE","322200","0"
"http://stackoverflow.com/users/547365","http://stackoverflow.com/questions/18026164","http://stackoverflow.com/questions/18026164/#18026235","2013-08-02 21:23:15","1","75","0","3","Java.lang.Character.isUnicodeIdentifierStart() equivalent in .NET","<p>Is there an equivalent method to <a href=""http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isUnicodeIdentifierStart%28char%29"" rel=""nofollow""><code>Java.lang.Character.isUnicodeIdentifierStart()</code></a> in .NET?</p>
","65","239","<c#><java><.net>","2013-08-02 21:08:23","FALSE","FALSE","18026235","2013-08-02 21:23:14","4","<p>There is no method directly for this. In most .NET languages, <a href=""http://msdn.microsoft.com/en-us/library/aa711644%28v=vs.71%29.aspx"" rel=""nofollow"">identifiers</a> can be any Unicode ""letter"" or an underscore, so you could easily write this as:</p>
<pre><code>bool IsValidIdentifierStart(char ch)
{
return ch == '_' || char.IsLetter(ch);
}
</code></pre>
<p>Note that the CLR is more flexible. The CLS specification, chapter 8.5.1, states:</p>
<blockquote>
<p>Assemblies shall follow Annex 7 of Technical Report 15 of the Unicode Standard 3.0 governing the set of characters permitted to start and be included in identifiers, available on-line at <a href=""http://www.unicode.org/unicode/reports/tr15/tr15-18.html"" rel=""nofollow"">http://www.unicode.org/unicode/reports/tr15/tr15-18.html</a>. Identifiers shall be in the canonical format defined by Unicode Normalization Form C.</p>
</blockquote>
<p>This allows the runtime to use identifiers that aren't permiitted by many of the standard languages.</p>
","1023","4","1","7","2013-08-02 21:13:43","5","TRUE","322038","0"
"http://stackoverflow.com/users/509490","http://stackoverflow.com/questions/10941778","http://stackoverflow.com/questions/10941778/#10941793","2012-06-08 00:45:55","1","155","0","2","Why can't I print to console after try block in Java?","<p>I have the following code in an Android application:</p>
<pre><code>public static HttpResponse dbPost(String handlerUrl, List&lt;NameValuePair&gt; postData) {
HttpClient httpclient = new DefaultHttpClient();
String postUrl = constants.postUrl();
HttpPost httppost = new HttpPost(postUrl);
HttpResponse response = null;
System.out.print(""Catch 0"");
try {
httppost.setEntity(new UrlEncodedFormEntity(postData));
response = httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(""Catch 1"");
return response;
}
</code></pre>
<p>I have a button that calls this block. If I press the button, the console will print ""Catch 0"" (but NOT ""Catch 1""). If I press the button again (same instance), the console will print ""Catch1Catch0"". What's the problem? </p>
<p>I'm a bit new to Java so bear with me.</p>
","53","1063","<java><android><try-catch>","2012-06-08 00:43:56","TRUE","FALSE","10941793","2012-06-08 00:45:55","8","<p>You need to call <a href=""http://docs.oracle.com/javase/1.4.2/docs/api/java/io/PrintStream.html#flush%28%29"">flush</a> since you're using <code>print</code>.</p>
<pre><code>System.out.print(""Catch 1"");
System.out.flush();
</code></pre>
<p>The default behavior of <code>PrintStream</code> is to only flush when a newline is written. (This behavior is documented in <a href=""http://docs.oracle.com/javase/1.4.2/docs/api/java/io/PrintStream.html#write%28int%29"">write(int)</a>.) </p>
<p>If you used <code>printLn</code> instead of <code>print</code>, the stream would flush automatically. Without that, you need to explicitly flush the output stream.</p>
","661","3","1","1","2012-06-08 00:45:55","2","TRUE","322038","0"
"http://stackoverflow.com/users/1075341","http://stackoverflow.com/questions/10577181","http://stackoverflow.com/questions/10577181/#10577188","2012-05-14 03:42:03","2","3111","0","2","Shell script and java parameter","<p>I have written the script <strong>run.sh</strong> below for calling a java class :</p>
<pre><code>java -cp . Main $1 $2 $3 $4
</code></pre>
<p>Here is my java class (it just displays the args) :</p>
<pre><code>public class Main {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
</code></pre>
<p>This is working unless I try to pass a parameter containing a space. For example :</p>
<pre><code>./run.sh This is ""a test""
</code></pre>
<p>will display :</p>
<pre><code>This
is
a
test
</code></pre>
<p>How could I modify my shell script and/or change my parameter syntax to pass the parameter ""a test"" unmodified ?</p>
","31","712","<java><shell><unix><command-line-arguments>","2012-05-14 03:23:35","TRUE","FALSE","10577188","2012-05-14 03:42:03","5","<p>Like this:</p>
<pre><code>java -cp . Main ""$@""
</code></pre>
","65","1","1","4","2012-05-14 03:25:08","2","TRUE","321065","0"
"http://stackoverflow.com/users/1277669","http://stackoverflow.com/questions/12041666","http://stackoverflow.com/questions/12041666/#12041846","2012-08-20 17:07:25","1","959","1","2","Why do I sometimes get different SHA256 hashes in Java and PHP?","<p>So I have an odd little problem with the hashing function in PHP. It only happens some of the time, which is what is confusing me. Essentially, I have a Java app and a PHP page, both of which calculate the SHA256 of the same string. There hasn't been any issues across the two, as they calculate the same hash (generally). The one exception is that every once in a while, PHP's output is one character longer than Java's.</p>
<p>I have this code in PHP:</p>
<pre><code>$token = $_GET[""token""];
$token = hash(""sha256"", $token.""&lt;salt&gt;"");
echo ""Your token is "" . $token;
</code></pre>
<p>99% of the time, I get the right hash. But every once in a while, I get something like this (space added to show the difference):</p>
<pre><code>26be60ec9a36f217df83834939cbefa33ac798776977c1970f6c38ba1cf92e92 # PHP
26be60ec9a36f217df83834939cbefa33ac798776977c197 f6c38ba1cf92e92 # Java
</code></pre>
<p>As you can see, they're nearly identical. But the top one (computed by PHP) has one more 0 for some reason. I haven't really noticed a rhyme or reason to it, but it's certainly stumped me. I've tried thinking of things like the wrong encoding, or wrong return value, but none of them really explain why they're almost identical except for that one character.</p>
<p>Any help on this issue would be much appreciated.</p>
<p>EDIT: The space is only in the bottom one to highlight where the extra 0 is. The actual hash has no space, and is indeed a valid hash, as it's the same one that Java produces.</p>
<p>EDIT2: Sorry about that. I checked the lengths with Notepad++, and since it's different than my normal text editor, I misread the length by 1. So yes, the top one is indeed right. Which means that it's a bug in my Java code. I'm going to explore Ignacio's answer and get back to you.</p>
","63","1801","<java><php><sha256>","2012-08-20 16:42:57","TRUE","FALSE","12041846","2012-08-20 17:04:05","4","<p>The top hash is the correct length; the bottom hash is output because the hexadecimal values were not zero-filled on output (note that it's the MSn of a byte). So, a bug in the Java program unrelated to the hash algorithm.</p>
<pre><code>&gt;&gt;&gt; '%04x %02x%02x %x%x' % (0x1201, 0x12, 0x01, 0x12, 0x01)
'1201 1201 121'
</code></pre>
","341","1","1","5","2012-08-20 16:57:33","15","TRUE","321065","0"
"http://stackoverflow.com/users/764272","http://stackoverflow.com/questions/809647","http://stackoverflow.com/questions/809647/#809657","2009-05-01 11:46:35","1","2511","0","2","Java vs Javascript Regex problem","<p><br />
I am having a problem with my regular expression: <code>&lt;a.*href=[\""'](.*?)[\""'].*&gt;(.*?)&lt;/a&gt;</code>. It is, as you can probably tell, supposed to take all the links from a string of HTML and return the link text in group 2, and the link target in group 1. But I am having a problem. If I try it in Javascript (using <a href=""http://www.regextester.com/"" rel=""nofollow"">http://www.regextester.com/</a>, with all the flags on), it works fine, but in Java, like this: </p>
<pre><code>Pattern myPattern = Pattern.compile(""&lt;a.*href=[\""'](.*?)[\""'].*&gt;(.*?)&lt;/a&gt;"", Pattern.CASE_INSENSITIVE);
Matcher match = myPattern.matcher(htmlData);
while(match.find()) {
String linkText = match.group(2);
String linkTarget = match.group(1);
}
</code></pre>
<p>I don't get all the matches I expect. With regex tester, I get many more and it works exactly like it is supposed to, but with the Java version, it just get 1 or 2 links per page.<br />
Sorry if this is obvious, but I am new to regular expressions.<br />
Thanks,<br />
Isaac Waller </p>
<p>Edit: I think it might be something wrong with my regex. See, from this Apache indexof page:</p>
<pre><code>&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Bryan%20Adams%20-%20Here%20I%20Am.mp3""&gt;Bryan Adams - Here I Am.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;27-Aug-2008 11:48 &lt;/td&gt;&lt;td align=""right""&gt;170K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Cars%20-%20Drive.mp3""&gt;Cars - Drive.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:04 &lt;/td&gt;&lt;td align=""right""&gt;149K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Cock%20Robin%20-%20When%20Your%20Heart%20Is%20Weak.mp3""&gt;Cock Robin - When Your Heart Is Weak.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:04 &lt;/td&gt;&lt;td align=""right""&gt;124K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Colbie%20Caillat%20-%20Bubbly.mp3""&gt;Colbie Caillat - Bubbly.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;27-Aug-2008 11:49 &lt;/td&gt;&lt;td align=""right""&gt;215K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Colbie%20Caillat%20-%20The%20Little%20Things.mp3""&gt;Colbie Caillat - The Little Things.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;27-Aug-2008 11:49 &lt;/td&gt;&lt;td align=""right""&gt;176K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Coldplay%20-%20Violet%20Hill.mp3""&gt;Coldplay - Violet Hill.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;27-Aug-2008 11:49 &lt;/td&gt;&lt;td align=""right""&gt;136K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Corrs%20-%20Radio.mp3""&gt;Corrs - Radio.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:04 &lt;/td&gt;&lt;td align=""right""&gt;112K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Corrs%20-%20What%20Can%20I%20Do.mp3""&gt;Corrs - What Can I Do.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:04 &lt;/td&gt;&lt;td align=""right""&gt;146K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Counting%20Crows%20-%20Big%20Yellow%20Taxi.mp3""&gt;Counting Crows - Big Yellow Taxi.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:04 &lt;/td&gt;&lt;td align=""right""&gt;135K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Curtis%20Stigers%20-%20I%20Wonder%20Why.mp3""&gt;Curtis Stigers - I Wonder Why.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:03 &lt;/td&gt;&lt;td align=""right""&gt;213K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Cyndi%20Lauper%20-%20Time%20After%20Time.mp3""&gt;Cyndi Lauper - Time After Time.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:03 &lt;/td&gt;&lt;td align=""right""&gt;193K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""David%20Bowie%20-%20Absolute%20Beginners.mp3""&gt;David Bowie - Absolute Beginners.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:04 &lt;/td&gt;&lt;td align=""right""&gt;155K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Depeche%20Mode%20-%20Enjoy%20The%20Silence.mp3""&gt;Depeche Mode - Enjoy The Silence.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;26-Aug-2008 19:03 &lt;/td&gt;&lt;td align=""right""&gt;230K&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td valign=""top""&gt;&lt;img src=""/icons/sound2.gif"" alt=""[SND]""&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=""Dido%20-%20White%20Flag.mp3""&gt;Dido - White Flag.mp3&lt;/a&gt;&lt;/td&gt;&lt;td align=""right""&gt;27-Aug-2008 11:48 &lt;/td&gt;&lt;td align=""right""&gt;158K&lt;/td&gt;&lt;/tr&gt;
</code></pre>
<p>I should get:<br />
1: Bryan%20Adams%20-%20Here%20I%20Am.mp3<br />
2: Bryan Adams - Here I Am.mp3<br />
and many more like that. With Regex tester, I get all the results I want. With Java, I get none.</p>
","32","5763","<java><regex>","2009-04-30 23:55:51","TRUE","FALSE","809657","2009-05-01 11:46:35","3","<p>You have to escape the backslash characters and the quotation marks:</p>
<pre><code>Pattern myPattern = Pattern.compile(""&lt;a.*href=[\\\""'](.*?)[\\\""'].*&gt;(.*?)&lt;/a&gt;"", Pattern.CASE_INSENSITIVE);
</code></pre>
<p>However, that might not be your real problem. The backslashes are not really needed in the pattern. There are some other possible issues with the pattern.</p>
<p>You are using a greedy match before the href property, which means that it will match from the start of the first link on the line to the href property of the last link on the line. Make the match non-greedy by changing it from ""<code>.*</code>"" to ""<code>.*?</code>"". The same goes for the match after the href property, it has to be non-greedy or it will match up to the end of the last link on the line.</p>
<p>The <code>.</code> character does not match line breaks, so if there are line breaks in the link code or in the text in the link, the link will not be matched. You can use <code>[\W\w]</code> instead of <code>.</code> to match any character.</p>
<p>So, removing the backslashes, making the matches non-greedy and allowing line breaks would make the pattern:</p>
<pre><code>Pattern myPattern = Pattern.compile(""&lt;a[\\W\\w]*?href=[\""'](.*?)[\""'][\\W\\w]*?&gt;([\\W\\w]*?)&lt;/a&gt;"", Pattern.CASE_INSENSITIVE);
</code></pre>
<p>Edit:<br />
I forgot to escape the backslashes in the <code>[\W\w]</code> codes in the string.</p>
","1433","6","2","2","2009-04-30 23:58:59","3","TRUE","317545","0"
"http://stackoverflow.com/users/231010","http://stackoverflow.com/questions/3004793","http://stackoverflow.com/questions/3004793/#3004860","2013-07-23 11:19:24","1","1274","1","4","Move all zero values in a big array to its front portion in a Time Efficiency way","<p>You're given a big array with Integral type value, How do you move all zero values within it to the front portion of the array in a Time Efficiency way?</p>
<p>e.g. 0,1,72,3,0,5,9,0,6,51,0,3 ---> 0,0,0,0,1,72,3,5,9,6,51,3</p>
<p>Regards!</p>
","81","248","<java><algorithm><arrays>","2010-06-09 10:04:17","FALSE","FALSE","3004860","2010-06-09 10:23:43","6","<p>If you want to keep the order between the other items, loop backwards copying all non-zero items, then fill up with zero items at the beginning:</p>
<pre><code>int source = arr.Length - 1;
int dest = arr.Length - 1;
while (source &gt;= 0) {
if (arr[source] != 0) {
arr[dest--] = arr[source];
}
source--;
}
while (dest &gt;= 0) arr[dest--] = 0;
</code></pre>
<p>If the order of the items is not important, you can simply swap zero items with items at the beginning of the array:</p>
<pre><code>int dest = 0;
for (int source = 0; source &lt; arr.Length; source++) {
if (arr[source] = 0) {
arr[source] = arr[dest];
add[dest++] = 0;
}
}
</code></pre>
<p>Both algorithms are O(n).</p>
<p>(Examples in C#, but it should be close enough as it's mostly a question about algorithms...)</p>
","811","4","2","1","2010-06-09 10:14:42","10","TRUE","317545","0"
"http://stackoverflow.com/users/315650","http://stackoverflow.com/questions/1079693","http://stackoverflow.com/questions/1079693/#1079803","2009-07-13 20:39:49","22","83119","5","4","How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?","<p>I am creating a Python script within which I am executing UNIX system commands. I have a
war archive named Binaries.war which is within an ear archive named Portal.ear</p>
<p>The Portal ear file resides in, say /home/foo/bar/</p>
<pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war
</code></pre>
<p>Will extract the Binaries.war file out of the /home/foo/bar/Portal.ear archive into the current directory I am running the script from.</p>
<p>How do you specify a target directory to be extracted to using just one command?
I would like to do something like this to extract Binaries.war into the directory /home/foo/bar/baz </p>
<pre><code>jar xf /home/foo/bar/Portal.ear Binaries.war [into target directory /home/foo/bar/baz]
</code></pre>
<p>I searched the the JAR man page for options and can't seem to find a simple way to do this. Of course I can extract the archive into my current directory and then move it using mv but I'd like to do this in one shot and not shuffle directories and files around.</p>
","123","1023","<java><python><linux><unix><jar>","2009-07-03 14:50:06","TRUE","FALSE","1079803","2009-07-13 20:39:49","27","<p>If your jar file already has an absolute pathname as shown, it is particularly easy:</p>
<pre><code>cd /where/you/want/it; jar xf /path/to/jarfile.jar
</code></pre>
<p>That is, you have the shell executed by Python change directory for you and then run the extraction.</p>
<p>If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that <code>jar</code> can find it after the change of directory.</p>
<p>The only issues left to worry about are things like blanks in the path names.</p>
","613","4","1","2","2009-07-03 15:12:40","22","TRUE","312090","0"
"http://stackoverflow.com/users/1094640","http://stackoverflow.com/questions/10711374","http://stackoverflow.com/questions/10711374/#10711452","2012-05-23 06:32:54","2","1468","0","6","Building a string with comma separated values","<p>For the purpose of building a database system I am using a simple builder to generate selection query based on user choices. It has a couple of booleans and then it progresses as follows</p>
<pre><code> StringBuilder builder = new StringBuilder();
builder.append(""SELECT "");
if(addOpen)
builder.append(""Open "");
if(addHigh)
builder.append(""High "");
if(addLow)
builder.append(""Low "");
if(addSettle)
builder.append(""Settle "");
builder.append(""FROM "" + tableName);
</code></pre>
<p>Now, my problem is trivial - I need to include commas but if I include a comma there must be a value coming after it, so I cannot do Open, or Open, Close, etc. Is there a neat solution to this trivial, yet surprisingly hard for me problem?</p>
","45","788","<java><sql><string><stringbuilder>","2012-05-22 23:10:34","TRUE","FALSE","10711452","2012-05-23 06:32:54","0","<p>The trick I use (in a generic semi-untyped pseudo-code) is:</p>
<pre><code> pad = """" # Empty string
builder = ""SELECT "";
if (addOpen)
builder += pad + ""Open""; pad = "", "";
if (addHigh)
builder += pad + ""High""; pad = "", "";
if (addLow)
builder += pad + ""Low""; pad = "", "";
if (addSettle)
builder += pad + ""Settle""; pad = "", "";
builder += ""FROM "" + TableName;
</code></pre>
<p>An alternative I've seen is to always include the comma (or comma space) after the terms, but trim the last two characters off the value before adding the FROM clause. Your choice...the 'pad' technique works even if you're doing output and can't undo an append.</p>
","681","2","1","2","2012-05-22 23:20:11","10","TRUE","312090","0"
"http://stackoverflow.com/users/259562","http://stackoverflow.com/questions/4485584","http://stackoverflow.com/questions/4485584/#4485599","2010-12-19 22:54:48","1","3290","1","1","Writing files into a directory which still does not exists","<p>I'm using this script on <strong>WINDOWS</strong></p>
<pre><code>public void copyFile(File sourceDirectory, File targetFile, File targetDirectory) throws IOException{
String temp = targetFile.getAbsolutePath();
String relativeD = temp.substring(sourceDirectory.getAbsolutePath().length(), targetFile.getAbsolutePath().length());
String rootD = sourceDirectory.getName();
String fullPath = targetDirectory.getAbsolutePath() + rootD + relativeD;
File fP = new File( fullPath );
System.out.println(""PATH: "" + fullPath);
FileChannel inChannel = new FileInputStream(targetFile).getChannel();
FileChannel outChannel = new FileOutputStream( fP ).getChannel();
int maxCount = (64 * 1024 * 1024) - (32 * 1024);
long size = inChannel.size();
long position = 0;
while (position &lt; size) {
position += inChannel.transferTo(position, maxCount, outChannel);
}
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
</code></pre>
<p>What I'm doing is simple. I need to copy a file from a location to another but I have to keep the directories they're in.</p>
<p>So with <code>relativeD</code> I'm taking something like this: <em>dir/files.sql</em> or simply <em>files.sql</em>.</p>
<p>This is happening because for specific directories I need to copy them recursively respecting the tree structure.</p>
<p>The problem is this method is not working. I don't know why because if I use a simple</p>
<pre><code> FileChannel outChannel = new FileOutputStream( new File( targetDirectory, targetFile ) ).getChannel();
</code></pre>
<p>it works. I suppose this is happening because in this case it's copying the file under an existing directory.</p>
","58","1748","<java><windows><file-io>","2010-12-19 22:51:22","TRUE","FALSE","4485599","2010-12-19 22:54:48","4","<p>According to this <a href=""http://webxadmin.free.fr/article/create-recursive-folders-with-java-1070.php"" rel=""nofollow"">article</a> (top Google search hit for 'java mkdir recursive'):</p>
<blockquote>
<p>Have a look at the java.io.File : it does the job perfectly, with the mkdirs function :</p>
<pre><code> new File(""c:/aaa/bbb/ccc/ddd"").mkdirs();
</code></pre>
</blockquote>
","387","2","1","3","2010-12-19 22:54:48","3","TRUE","312090","0"
"http://stackoverflow.com/users/2871925","http://stackoverflow.com/questions/19527440","http://stackoverflow.com/questions/19527440/#19527913","2013-10-22 21:52:03","1","86","0","1","What am I encrypting wrong here?","<p>So I have a wordplay project to do and I have to encrypt some characters. I am at the point where I am stuck, and when I run it and type 1 for encrypt it doesn't shift that many letters. It just prints the work over again. I am wondering what I could do to fix it where if I say ""hello"" it will print 1 character over and say ""ifmmp"" Thank you!</p>
<pre><code>import java.util.Scanner;
public class WordPlayTester{
public static void main(String [] args){
String word, reverse="""";
String original;
int key= 0;
String Menu= ""1-Encrypt \n2-Decrypt \n3-Is Palindrome \n0-Quit \n-Select an option-"";
Scanner in = new Scanner(System.in);
System.out.println(""-Type any word-"");
word = in.nextLine();
System.out.println(Menu);
int choice=in.nextInt();
if(choice==1)
{
System.out.println(""Insert a Key number"");
int select= in.nextInt();
for (int i=0; i &lt; word.length(); i++) {
char c = word.charAt(i);
if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') {
c = (char)(c - 64);
int n = c+1;
n = n % 26;
if (n &lt; 0) {
n = n + 26;
}
c = (char)(n + 65);
}
System.out.println(c);
}
}
else if(choice==3)
{
int length = word.length();
for ( int i = length - 1 ; i &gt;= 0 ; i-- )
reverse = reverse + word.charAt(i);
if (word.equals(reverse))
System.out.println(""Your word is a palindrome."");
else
System.out.println(""Your word is not a palindrome."");
}
else if(choice==0)
{
System.exit(0);
}
else
{
System.out.println(Menu);
}
}
}
</code></pre>
","32","1901","<java><encryption><character>","2013-10-22 20:14:17","TRUE","FALSE","19527913","2013-10-22 21:52:03","0","<p>Here's some revised, simplified code:</p>
<pre><code>import java.util.Scanner;
public class WordPlayTester {
public static void main(String [] args) {
String word;
int key= 0;
Scanner in = new Scanner(System.in);
System.out.println(""-Type any word-"");
word = in.nextLine();
System.out.println(""Insert a Key number"");
int select = in.nextInt();
for (int i=0; i &lt; word.length(); i++) {
char c = word.charAt(i);
if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') {
c = (char)(c - (int)'A');
int n = c+select;
n = n % 26;
if (n &lt; 0) {
n = n + 26;
}
c = (char)(n + (int)'A');
}
System.out.print(c);
}
System.out.print('\n');
}
}
</code></pre>
<p>Given an input BYZANTIUM and key 1, it outputs CZABOUJVN; given key 2, it outputs DABCPVKWO; given key 25, it outputs AXYZMSHTL; given key 26, it outputs BYZANTIUM.</p>
","942","2","1","2","2013-10-22 20:41:28","27","TRUE","312090","0"
"http://stackoverflow.com/users/1626699","http://stackoverflow.com/questions/12148186","http://stackoverflow.com/questions/12148186/#12148206","2012-08-27 19:26:07","0","1928","0","1","How do I pass a bash parameter that includes a directory with a space as a Java argument?","<p>I am currently attempting to make a bash script that executes a Java main class with a path to an archive file as an argument. I want to make sure that it can handle spaces in that path, which is giving me a bit of a headache.</p>
<p>I want to set that path as an environment variable and call it when I execute the main class, so the script looks something like this:</p>
<pre><code>export ArgPath='/Foo Path/foo.zip'
$JAVA_HOME/bin/java -cp ./foo.jar foopackage.main -a $ArgPath
</code></pre>
<p>Unfortunately, when I execute this in Bash, the command comes out like this:</p>
<pre><code>/foo_Java_Home/bin/java -cp ./foo.jar foopackage.main -a /Foo Path/foo.zip
</code></pre>
<p>Java arguments can't have spaces. Java treats ""/Foo"" and ""Path/foo.zip"" as two separate arguments. Okay, that's not a problem. Java can handle arguments with spaces. I need to find some way to get double or single quotes around it. I'll try to escape double quotes around the path. The script now looks like this:</p>
<pre><code>export ArgPath='\""/Foo Path/foo.zip\""'
$JAVA_HOME/bin/java -cp ./foo.jar foopackage.main -a $ArgPath
</code></pre>
<p>Bash gives me this...</p>
<pre><code>/foo_Java_Home/bin/java -cp ./foo.jar foopackage.main -a '\""/Foo' 'Path/foo.zip\""'
</code></pre>
<p>...which still causes Java to treat them as two separate arguments (not to mention that it wouldn't work as a single argument anyway). I've tried about every combination and permutation of using single quotes, double quotes, and escaping single quotes/double quotes/spaces I can think of. Is there any way to provide the desired output of</p>
<pre><code>'/Foo Path/foo.zip'
</code></pre>
<p>or
""/Foo Path/foo.zip""</p>
<p>In Bash? For that matter, is it possible to get Bash to accept an arbitrary string literal without trying to add anything to it in circumstances like these? Escaping characters doesn't seem to work, so that may be the only option if it's possible.</p>
<p>Thanks in advance. </p>
","89","1988","<java><linux><bash><shell>","2012-08-27 19:17:53","TRUE","FALSE","12148206","2012-08-27 19:26:07","3","<p>Enclose the variable in double quotes in the command invocation:</p>
<pre><code>export ArgPath='/Foo Path/foo.zip'
$JAVA_HOME/bin/java -cp ./foo.jar foopackage.main -a ""$ArgPath""
</code></pre>
<p>Note that this applies generally to invoking any command (not just Java). If an argument contains spaces (etc.), enclose it in quotes (single or double). When the argument is in a variable, use double quotes.</p>
","417","2","1","3","2012-08-27 19:19:15","2","TRUE","312090","0"
"http://stackoverflow.com/users/858366","http://stackoverflow.com/questions/16789832","http://stackoverflow.com/questions/16789832/#16795317","2014-05-08 09:44:14","163","5184","17","13","Missing return statement in a non-void method compiles","<p>I encountered a situation where a <strong>non-void method</strong> is missing a <strong>return</strong> statement and the code still compiles.
I know that the statements after the while loop are <strong>unreachable</strong>(dead code) and would never be executed. But why doesn't the compiler even warn about returning something? Or why would a language allow us to have a non-void method having an infinite loop and not returning anything?</p>
<pre><code>public int doNotReturnAnything() {
while(true) {
//do something
}
//no return statement
}
</code></pre>
<p>If I add a break statement(even a conditional one) in the while loop, the compiler complains of the infamous errors: 'Method does not return a value'(Eclipse) and 'Not all code paths return a value'(Visual Studio)</p>
<pre><code>public int doNotReturnAnything() {
while(true) {
if(mustReturn) break;
//do something
}
//no return statement
}
</code></pre>
<p>This is true of both Java and C#</p>
","54","1013","<c#><java><oop><design>","2013-05-28 10:32:48","TRUE","FALSE","16795317","2014-05-08 09:44:14","215","<blockquote>
<p>Why would a language allow us to have a non-void method having an infinite loop and not returning anything?</p>
</blockquote>
<p>The rule for non-void methods is <em>every code path that returns must return a value</em>, and that rule is satisfied in your program: zero out of zero code paths that return do return a value. The rule is not ""every non-void method must have a code path that returns"". </p>
<p>This enables you to write stub-methods like:</p>
<pre><code>IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
</code></pre>
<p>That's a non-void method. It <em>has</em> to be a non-void method in order to satisfy the interface. But it seems silly to make this implementation illegal because it does not return anything. </p>
<p>That your method has an unreachable end point because of a <code>goto</code> (remember, a <code>while(true)</code> is just a more pleasant way to write <code>goto</code>) instead of a <code>throw</code> (which is another form of <code>goto</code>) is not relevant.</p>
<blockquote>
<p>Why doesn't the compiler even warn about returning something? </p>
</blockquote>
<p>Because the compiler has no good evidence that the code is wrong. Someone wrote <code>while(true)</code> and it seems likely that the person who did that knew what they were doing. </p>
<blockquote>
<p>Where can I read more about reachability analysis in C#?</p>
</blockquote>
<p>See my articles on the subject, here:</p>
<p><a href=""http://ericlippert.com/category/reachability/"">ATBG: de facto and de jure reachability</a></p>
<p>And you might also consider reading the C# specification.</p>
","1671","11","1","8","2013-05-28 14:59:59","267","TRUE","308301","8"
"http://stackoverflow.com/users/2948805","http://stackoverflow.com/questions/19774018","http://stackoverflow.com/questions/19774018/#19775215","2013-11-05 11:50:01","2","292","0","1","Problems with converting Java code to delphi","<p>I have a method that must return a generic interface. Have tried to make the method in delphi. But are unsure on how it should be written? Is there anyone who can help me?
Here's an example I've made in Java that works:</p>
<pre><code>public &lt; T extends StandardDataProvider&lt;?&gt;&gt; T GetDataProvider(String dataProviderName) {
if (dataproviders == null)
buildDataProviderMap();
if (dataproviders.containsKey(dataProviderName)) {
return (T) dataproviders.get(dataProviderName);
} else
return null;
}
</code></pre>
<p>Then tried to do the same in delphi .. But can not get it to work?</p>
<pre><code>function TLocalDataProviderFactory. GetDataProvider(DataProviderName: string): IStandardDataProvider; // Shows errors here?
begin
if not Assigned(DataProvider) then
BuildDataProviderMap;
if DataProvider.ContainsKey(DataProviderName) then
begin
Result := DataProvider.Items[DataProviderName];
end
else
begin
Result:= nil;
end;
end;
</code></pre>
","44","1023","<java><delphi><delphi-xe4>","2013-11-04 17:56:50","TRUE","FALSE","19775215","2013-11-04 19:25:32","6","<p>Delphi generic constraints do not support wildcards. So the closest you can manage involves two generic parameters. The function would look like this:</p>
<pre><code>function GetDataProvider&lt;S; T: IStandardDataProvider&lt;S&gt;&gt;(...): T;
</code></pre>
","262","1","1","6","2013-11-04 19:10:57","74","TRUE","303200","0"
"http://stackoverflow.com/users/1227714","http://stackoverflow.com/questions/10574534","http://stackoverflow.com/questions/10574534/#10574542","2012-05-13 23:28:14","1","130","0","4","if () not working","<p>This is my code: </p>
<pre><code>Log.d(""inf"", loader);
if (loader == ""Klasse""){
Log.d(""inf"", ""Klasse yes"");
OPTS = new String[] { //Something };
} else {
Log.d(""inf"", ""Klasse no"");
OPTS = new String[] { //Something };
}
</code></pre>
<p>In the first Line, the Output is exactly ""Klasse"" but the next output is everytime ""Klasse no"". The loader String is set as follows:</p>
<pre><code>String loader = """";
Bundle exta = getIntent().getExtras();
if(exta !=null) {
try {
json = new JSONObject(exta.getString(""json""));
loader = exta.getString(""order"");
} catch (JSONException e) {
e.printStackTrace();
}
}
</code></pre>
<p>Do you guys have any Idea whats wrong?</p>
","17","753","<java><android>","2012-05-13 19:24:48","TRUE","FALSE","10574542","2012-05-13 23:28:14","11","<p>The <code>==</code> comparison operator compares references rather than values. You need to compare the values and so need to use the <code>equals()</code> method.</p>
<pre><code>if (loader.equals(""Klasse""))
</code></pre>
","226","1","1","10","2012-05-13 19:26:18","2","TRUE","303200","10"
"http://stackoverflow.com/users/63051","http://stackoverflow.com/questions/2229757","http://stackoverflow.com/questions/2229757/#2230464","2014-07-31 08:03:34","98","70827","87","6","Maven: add a dependency to a jar by relative path","<p>I have a proprietary jar that I want to add to my pom as a dependency.</p>
<p>But I don't want to add it to a repository. The reason is that I want my usual maven commands such as <code>mvn compile</code>, etc, to work out of the box. (Without demanding from the developers a to add it to some repository by themselves).</p>
<p>I want the jar to be in a 3rdparty lib in source control, and link to it by relative path from the pom.xml file.</p>
<p>Can this be done? How?</p>
","49","481","<java><maven-2><build-process><build><dependencies>","2010-02-09 14:30:22","FALSE","FALSE","2230464","2010-05-27 01:48:51","165","<blockquote>
<p>I want the jar to be in a 3rdparty lib in source control, and link to it by relative path from the pom.xml file.</p>
</blockquote>
<p>If you really want this (understand, if you can't use a corporate repository), then my advice would be to use a ""file repository"" local to the project and to <strong>not use</strong> a <code>system</code> scoped dependency. The <code>system</code> scoped should be avoided, such dependencies don't work well in many situation (e.g. in assembly), they cause more troubles than benefits. </p>
<p>So, instead, declare a repository local to the project:</p>
<pre><code>&lt;repositories&gt;
&lt;repository&gt;
&lt;id&gt;my-local-repo&lt;/id&gt;
&lt;url&gt;file://${basedir}/my-repo&lt;/url&gt;
&lt;/repository&gt;
&lt;/repositories&gt;
</code></pre>
<p>Install your third party lib in there using <code>install:install-file</code> with the <a href=""http://maven.apache.org/plugins/maven-install-plugin/install-file-mojo.html#localRepositoryPath""><code>localRepositoryPath</code></a> parameter:</p>
<p><strike></p>
<pre><code>mvn install:install-file -Dfile=&lt;path-to-file&gt; -DgroupId=&lt;myGroup&gt; \
-DartifactId=&lt;myArtifactId&gt; -Dversion=&lt;myVersion&gt; \
-Dpackaging=&lt;myPackaging&gt; -DlocalRepositoryPath=&lt;path&gt;
</code></pre>
<p></strike></p>
<p><strong>Update:</strong> It appears that <code>install:install-file</code> ignores the <code>localRepositoryPath</code> when using the version 2.2 of the plugin. However, it works with version 2.3 and later of the plugin. So use the fully qualified name of the plugin to specify the version:</p>
<pre><code>mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file \
-Dfile=&lt;path-to-file&gt; -DgroupId=&lt;myGroup&gt; \
-DartifactId=&lt;myArtifactId&gt; -Dversion=&lt;myVersion&gt; \
-Dpackaging=&lt;myPackaging&gt; -DlocalRepositoryPath=&lt;path&gt;
</code></pre>
<p>Finally, declare it like any other dependency (but without the <code>system</code> scope):</p>
<pre><code>&lt;dependency&gt;
&lt;groupId&gt;your.group.id&lt;/groupId&gt;
&lt;artifactId&gt;3rdparty&lt;/artifactId&gt;
&lt;version&gt;X.Y.Z&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<p>This is IMHO a better solution than using a <code>system</code> scope as your dependency will be treated like a good citizen (e.g. it will be included in an assembly and so on).</p>
<p>Now, I have to mention that the ""right way"" to deal with this situation in a corporate environment (maybe not the case here) would be to use a corporate repository.</p>
","2703","10","4","10","2010-02-09 16:05:31","95","TRUE","301973","0"
"http://stackoverflow.com/users/84818","http://stackoverflow.com/questions/1114026","http://stackoverflow.com/questions/1114026/#3899772","2012-10-07 10:26:10","90","38180","43","5","Maven Modules + Building a Single Specific Module","<p>I have a multi-module Maven project with a parent project <code>P</code> and three sub-modules <code>A</code>, <code>B</code>, and <code>C</code>. Both <code>B</code> and <code>C</code> are war projects and both depend on <code>A</code>. </p>
<p>I can type <code>mvn compile</code> in <code>P</code> and have all of the sub-modules properly compiled. The problem comes when I want to do operations for specific modules.</p>
<p>I'd like to be able to package a war for project <code>B</code>, but when I run the package command from <code>B</code>'s directory, it complains that it can't find the dependencies for <code>A</code>. </p>
<p>I understand from this question: <a href=""http://stackoverflow.com/questions/808516/maven-and-dependent-modules"">Maven and dependent modules</a> that perhaps Maven isn't really designed for this type of dependency resolution, but that begs the question of how do I package <code>B</code>? </p>
<ol>
<li><p>Do I have to run <code>mvn package</code> for the entire project hierarchy when I really just want <code>B</code>? </p></li>
<li><p>Do I have to install snapshots of A into my local repository every time I want to package <code>B</code>? </p></li>
</ol>
<p>This second scenario isn't much fun when <code>A</code> is still under active development.</p>
<p>Any best practices here?</p>
","49","1342","<java><maven-2><build-process>","2009-07-11 16:12:05","FALSE","FALSE","3899772","2012-10-07 10:26:10","151","<blockquote>
<p>Any best practices here?</p>
</blockquote>
<p>Use the Maven <a href=""http://www.sonatype.com/people/2009/10/maven-tips-and-tricks-advanced-reactor-options/"">advanced reactor options</a>, more specifically:</p>
<pre><code>-pl, --projects
Build specified reactor projects instead of all projects
-am, --also-make
If project list is specified, also build projects required by the list
</code></pre>
<p>So just <code>cd</code> into the parent P directory and run:</p>
<pre><code>mvn install -pl B -am
</code></pre>
<p>And this will build B and the modules required by B. </p>
","611","4","2","3","2010-10-10 09:33:44","656241","TRUE","301973","0"
"http://stackoverflow.com/users/166850","http://stackoverflow.com/questions/1814526","http://stackoverflow.com/questions/1814526/#1814697","2013-09-04 14:08:37","61","52130","56","3","Problem building executable jar with maven","<p>I am trying to generate an executable jar for a small home project called ""logmanager"" using maven, just like this:</p>
<p><a href=""http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven"">http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven</a></p>
<p>I added the snippet shown there to the pom.xml, and ran mvn assembly:assembly. It generates two jar files in logmanager/target: logmanager-0.1.0.jar, and logmanager-0.1.0-jar-with-dependencies.jar. I get an error when I double-click on the first jar:</p>
<pre><code>Could not find the main class: com.gorkwobble.logmanager.LogManager. Program will exit.
</code></pre>
<p>A slightly different error when I double-click the jar-with-dependencies.jar:</p>
<pre><code>Failed to load Main-Class manifest attribute from: C:\EclipseProjects\logmanager\target\logmanager-0.1.0-jar-with-dependencies.jar
</code></pre>
<p>I copied and pasted the path and classname, and checked the spelling in the POM. My main class launches fine from an eclipse launch configuration. Can someone help me figure out why my jar file won't run? Also, why are there two jars to begin with? Let me know if you need more information.</p>
<p>Thanks!</p>
<p>[Edit: my POM is now as follows:]</p>
<pre><code>&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd""&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.gorkwobble&lt;/groupId&gt;
&lt;artifactId&gt;logmanager&lt;/artifactId&gt;
&lt;name&gt;LogManager&lt;/name&gt;
&lt;version&gt;0.1.0&lt;/version&gt;
&lt;description&gt;Systematically renames specified log files on a scheduled basis. Designed to help manage MUSHClient logging and prevent long, continuous log files.&lt;/description&gt;
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;
&lt;version&gt;2.2&lt;/version&gt;
&lt;!-- nothing here --&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
&lt;version&gt;2.2-beta-4&lt;/version&gt;
&lt;configuration&gt;
&lt;descriptorRefs&gt;
&lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;
&lt;/descriptorRefs&gt;
&lt;archive&gt;
&lt;manifest&gt;
&lt;mainClass&gt;com.gorkwobble.logmanager.LogManager&lt;/mainClass&gt;
&lt;/manifest&gt;
&lt;/archive&gt;
&lt;/configuration&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;
&lt;goal&gt;single&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;source&gt;1.6&lt;/source&gt;
&lt;target&gt;1.6&lt;/target&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;dependencies&gt;
&lt;!-- commons-lang --&gt;
&lt;dependency&gt;
&lt;groupId&gt;commons-lang&lt;/groupId&gt;
&lt;artifactId&gt;commons-lang&lt;/artifactId&gt;
&lt;version&gt;2.4&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- Quartz scheduler --&gt;
&lt;dependency&gt;
&lt;groupId&gt;opensymphony&lt;/groupId&gt;
&lt;artifactId&gt;quartz&lt;/artifactId&gt;
&lt;version&gt;1.6.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- Quartz 1.6.0 depends on commons collections --&gt;
&lt;dependency&gt;
&lt;groupId&gt;commons-collections&lt;/groupId&gt;
&lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
&lt;version&gt;3.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- Quartz 1.6.0 depends on commons logging --&gt;
&lt;dependency&gt;
&lt;groupId&gt;commons-logging&lt;/groupId&gt;
&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
&lt;version&gt;1.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- Quartz 1.6.0 requires JTA in non J2EE environments --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.transaction&lt;/groupId&gt;
&lt;artifactId&gt;jta&lt;/artifactId&gt;
&lt;version&gt;1.1&lt;/version&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- junitx test assertions --&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit-addons&lt;/groupId&gt;
&lt;artifactId&gt;junit-addons&lt;/artifactId&gt;
&lt;version&gt;1.4&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- junit dependency; FIXME: make this a separate POM --&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;4.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;dependencyManagement&gt;
&lt;/dependencyManagement&gt;
&lt;/project&gt;
</code></pre>
","42","5484","<java><eclipse><maven-2><build-process><executable-jar>","2009-11-29 03:14:29","TRUE","FALSE","1814697","2011-09-22 17:28:19","132","<p>Actually, I think that the answer given in the <a href=""http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven"">question</a> you mentioned is just <strong>wrong</strong> (<strong>UPDATE - 20101106:</strong> someone fixed it, <em>this</em> answer refers to the version preceding the edit) and this explains, at least partially, why you run into troubles.</p>
<hr>
<blockquote>
<p>It generates two jar files in logmanager/target: logmanager-0.1.0.jar, and logmanager-0.1.0-jar-with-dependencies.jar.</p>
</blockquote>
<p>The first one is the JAR of the logmanager module generated during the <code>package</code> phase by <code>jar:jar</code> (because the module has a packaging of type <code>jar</code>). The second one is the assembly generated by <code>assembly:assembly</code> and should contain the classes from the current module and its dependencies (if you used the descriptor <code>jar-with-dependencies</code>).</p>
<blockquote>
<p>I get an error when I double-click on the first jar:</p>
<pre><code>Could not find the main class: com.gorkwobble.logmanager.LogManager. Program will exit.
</code></pre>
</blockquote>
<p>If you applied the suggested configuration of the link posted as reference, you configured the jar plugin to produce an executable artifact, something like this: </p>
<pre><code> &lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;archive&gt;
&lt;manifest&gt;
&lt;addClasspath&gt;true&lt;/addClasspath&gt;
&lt;mainClass&gt;com.gorkwobble.logmanager.LogManager&lt;/mainClass&gt;
&lt;/manifest&gt;
&lt;/archive&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
</code></pre>
<p>So <code>logmanager-0.1.0.jar</code> is indeed executable but 1. this is not what you want (because it doesn't have all dependencies) and 2. it doesn't contain <code>com.gorkwobble.logmanager.LogManager</code> (this is what the error is saying, check the content of the jar).</p>
<blockquote>
<p>A slightly different error when I double-click the jar-with-dependencies.jar:</p>
<pre><code>Failed to load Main-Class manifest attribute from: C:\EclipseProjects\logmanager\target\logmanager-0.1.0-jar-with-dependencies.jar
</code></pre>
</blockquote>
<p>Again, if you configured the assembly plugin as suggested, you have something like this:</p>
<pre><code> &lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;descriptorRefs&gt;
&lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;
&lt;/descriptorRefs&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
</code></pre>
<p>With this setup, <code>logmanager-0.1.0-jar-with-dependencies.jar</code> contains the classes from the current module <strong>and</strong> its dependencies but, according to the error, its <code>META-INF/MANIFEST.MF</code> <strong>doesn't</strong> contain a <code>Main-Class</code> entry (its likely not the same MANIFEST.MF as in logmanager-0.1.0.jar). The jar is actually <strong>not</strong> executable, which again is not what you want.</p>
<hr>
<p>So, my suggestion would be to remove the <code>configuration</code> element from the maven-jar-plugin and to configure the maven-assembly-plugin like this:</p>
<pre><code> &lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;
&lt;version&gt;2.2&lt;/version&gt;
&lt;!-- nothing here --&gt;
&lt;/plugin&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
&lt;version&gt;2.2-beta-4&lt;/version&gt;
&lt;configuration&gt;
&lt;descriptorRefs&gt;
&lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt;
&lt;/descriptorRefs&gt;
&lt;archive&gt;
&lt;manifest&gt;
&lt;mainClass&gt;org.sample.App&lt;/mainClass&gt;
&lt;/manifest&gt;
&lt;/archive&gt;
&lt;/configuration&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;
&lt;goal&gt;single&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
</code></pre>
<p>Of course, replace <code>org.sample.App</code> with the class you want to have executed. Little bonus, I've bound <code>assembly:single</code> to the <code>package</code> phase so you don't have to run <code>assembly:assembly</code> anymore. Just run <code>mvn install</code> and the assembly will be produced during the standard build.</p>
<p>So, please update your pom.xml with the configuration given above and run <code>mvn clean install</code>. Then, cd into the <code>target</code> directory and try again:</p>
<pre><code>java -jar logmanager-0.1.0-jar-with-dependencies.jar
</code></pre>
<p>If you get an error, please update your question with it and post the content of the <code>META-INF/MANIFEST.MF</code> file and the relevant part of your <code>pom.xml</code> (the plugins configuration parts). Also please post the result of:</p>
<pre><code>java -cp logmanager-0.1.0-jar-with-dependencies.jar com.gorkwobble.logmanager.LogManager
</code></pre>
<p>to demonstrate it's working fine on the command line (regardless of what eclipse is saying).</p>
<p>EDIT: For Java 6, you need to configure the maven-compiler-plugin. Add this to your pom.xml:</p>
<pre><code> &lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;source&gt;1.6&lt;/source&gt;
&lt;target&gt;1.6&lt;/target&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
</code></pre>
","5970","15","8","14","2009-11-29 05:00:27","106","TRUE","301973","14"
"http://stackoverflow.com/users/3713995","http://stackoverflow.com/questions/24427056","http://stackoverflow.com/questions/24427056/#24427197","2014-06-27 06:25:39","23","969","4","3","What is an operand stack?","<p>I am reading about JVM architecture. Today I read about the concept of the Operand Stack. According to an article:</p>
<blockquote>
<p>The operand stack is used during the execution of byte code instructions
in a similar way that general-purpose registers are used in a native CPU.</p>
</blockquote>
<p>I can't understand: What exactly is an Operand Stack, and how does it work in jvm?</p>
","25","399","<java><jvm>","2014-06-26 09:35:07","FALSE","FALSE","24427197","2014-06-26 09:57:27","35","<p>It's how the various individual bytecode operations get their input, and how they provide their output.</p>
<p>For instance, consider the <code>iadd</code> operation, which adds two <code>int</code>s together. To use it, you push two values on the stack and then use it:</p>
<pre><code>iload_0 # Push the value from local variable 0 onto the stack
iload_1 # Push the value from local variable 1 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>Now the top value on the stack is the sum of those two local variables. The next operation might take that top stack value and store it somewhere, or we might push another value on the stack to do something else.</p>
<p>Suppose you want to add three values together. The stack makes that easy:</p>
<pre><code>iload_0 # Push the value from local variable 0 onto the stack
iload_1 # Push the value from local variable 1 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
iload_2 # Push the value from local variable 2 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>Now the top value on the stack is the result of adding together those three local variables.</p>
<p>Let's look at that second example in more detail:</p>
<p>We'll assume:</p>
<ul>
<li>The stack is empty to start with <em>(which is almost never actually true, but we don't care what's on it before we start)</em></li>
<li>Local variable 0 contains <code>27</code></li>
<li>Local variable 1 contains <code>10</code></li>
<li>Local variable 2 contains <code>5</code></li>
</ul>
<p>So initially:</p>
<pre>+-------+
| stack |
+-------+
+-------+</pre>
<p>Then we do</p>
<pre><code>iload_0 # Push the value from local variable 0 onto the stack
</code></pre>
<p>Now we have</p>
<pre>+-------+
| stack |
+-------+
| 27 |
+-------+</pre>
<p>Next</p>
<pre><code>iload_1 # Push the value from local variable 1 onto the stack
</code></pre>
<pre>+-------+
| stack |
+-------+
| 10 |
| 27 |
+-------+</pre>
<p>Now we do the addition:</p>
<pre><code>iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>It ""pops"" the <code>10</code> and <code>27</code> off the stack, adds them together, and pushes the result (<code>37</code>). Now we have:</p>
<pre>+-------+
| stack |
+-------+
| 37 |
+-------+</pre>
<p>Time for our third <code>int</code>:</p>
<pre><code>iload_2 # Push the value from local variable 2 onto the stack
</code></pre>
<pre>+-------+
| stack |
+-------+
| 5 |
| 37 |
+-------+</pre>
<p>We do our second <code>iadd</code>:</p>
<pre><code>iadd # Pops those off the stack, adds them, and pushes the result
</code></pre>
<p>That gives us:</p>
<pre>+-------+
| stack |
+-------+
| 42 |
+-------+</pre>
<p><em>(Which is, of course, the <a href=""http://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29"">Answer to the Ultimate Question of Life the Universe and Everything</a>.)</em></p>
","3177","17","7","1","2014-06-26 09:42:14","7","TRUE","299237","0"
"http://stackoverflow.com/users/560204","http://stackoverflow.com/questions/6579442","http://stackoverflow.com/questions/6579442/#6579512","2011-07-05 13:41:48","21","877","4","4","== operator with Strings","<p>The code below should not print ""Bye"", since == operator is used to compare references, but oddly enough, ""Bye"" is still printed. Why does this happen? I'm using Netbeans 6.9.1 as the IDE.</p>
<pre><code>public class Test {
public static void main(String [] args) {
String test =""Hi"";
if(test==""Hi""){
System.out.println(""Bye"");
}
}
}
</code></pre>
","24","396","<java><string>","2011-07-05 07:51:36","TRUE","FALSE","6579512","2011-07-05 13:41:48","40","<p>This behavior is because of <strong>interning</strong>. The behavior is described in the docs for <a href=""http://download.oracle.com/javase/6/docs/api/java/lang/String.html#intern%28%29""><code>String#intern</code></a> (including why it's showing up in your code even though you never call <code>String#intern</code>):</p>
<blockquote>
<p>A pool of strings, initially empty, is maintained privately by the class <code>String</code>.</p>
<p>When the <code>intern</code> method is invoked, if the pool already contains a string equal to this <code>String</code> object as determined by the <code>equals(Object)</code> method, then the string from the pool is returned. Otherwise, this <code>String</code> object is added to the pool and a reference to this <code>String</code> object is returned.</p>
<p>It follows that for any two strings <code>s</code> and <code>t</code>, <code>s.intern() == t.intern()</code> is <code>true</code> if and only if <code>s.equals(t)</code> is true.</p>
<p>All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the <a href=""http://java.sun.com/docs/books/jls/html/"">Java Language Specification</a>.</p>
</blockquote>
<p>So for example:</p>
<pre><code>public class Test {
private String s1 = ""Hi"";
public static void main(String [] args) {
new Test().test();
System.exit(0);
}
public void test() {
String s2 =""Hi"";
String s3;
System.out.println(""[statics] s2 == s1? "" + (s2 == s1));
s3 = ""H"" + part2();
System.out.println(""[before interning] s3 == s1? "" + (s3 == s1));
s3 = s3.intern();
System.out.println(""[after interning] s3 == s1? "" + (s3 == s1));
System.exit(0);
}
protected String part2() {
return ""i"";
}
}
</code></pre>
<p>Output:</p>
<pre>[statics] s2 == s1? true
[before interning] s3 == s1? false
[after interning] s3 == s1? true</pre>
<p>Walking through that:</p>
<ol>
<li>The literal assigned to <code>s1</code> is automatically interned, so <code>s1</code> ends up referring to a string in the pool.</li>
<li>The literal assigned to <code>s2</code> is also auto-interned, and so <code>s2</code> ends up pointing to the same instance <code>s1</code> points to. This is fine even though the two bits of code may be completely unknown to each other, because Java's <code>String</code> instances are <em>immutable</em>. You can't change them. You can use methods like <code>toLowerCase</code> to get back a <em>new</em> string with changes, but the original you called <code>toLowerCase</code> (etc.) on remains unchanged. So they can safely be shared amongst unrelated code.</li>
<li>We create a <em>new</em> <code>String</code> instance via a runtime operation. Even though the new instance has the same sequence of characters as the interned one, it's a <em>separate</em> instance. The runtime doesn't intern dynamically-created strings automatically, because there's a cost involved: The work of finding the string in the pool. (Whereas when compiling, the compiler can take that cost onto itself.) So now we have two instances, the one <code>s1</code> and <code>s2</code> point to, and the one <code>s3</code> points to. So the code shows that <code>s3 != s1</code>.</li>
<li>Then we explicitly intern <code>s3</code>. Perhaps it's a large string we're planning to hold onto for a long time, and we think it's likely that it's going to be duplicated in other places. So we accept the work of interning it in return for the potential memory savings. Since interning by definition means we may get back a new reference, we assign the result back to <code>s3</code>.</li>
<li>And we can see that indeed, <code>s3</code> now points to the same instance <code>s1</code> and <code>s2</code> point to.</li>
</ol>
","3880","8","1","6","2011-07-05 07:58:02","7","TRUE","299237","0"
"http://stackoverflow.com/users/368186","http://stackoverflow.com/questions/4501061","http://stackoverflow.com/questions/4501061/#4501084","2012-08-16 14:27:23","17","30715","4","9","Java null check why use == instead of .equals()","<p>In Java I am told that when doing a null check one should use == instead of .equals(). What are the reasons for this?</p>
","47","125","<java><null>","2010-12-21 15:47:41","FALSE","FALSE","4501084","2010-12-21 16:37:55","32","<p>They're two completely different things. <code>==</code> compares the object reference, if any, contained by a variable. <code>.equals()</code> checks to see if two objects are <em>equal</em> according to their contract for what equality means. It's entirely possible for two distinct object instances to be ""equal"" according to their contract. And then there's the minor detail that since <code>equals</code> is a method, if you try to invoke it on a <code>null</code> reference, you'll get a <code>NullPointerException</code>.</p>
<p>For instance:</p>
<pre><code>class Foo {
private int data;
Foo(int d) {
this.data = d;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}
/* In a real class, you'd override `hashCode` here as well */
}
Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances
System.out.println(f1.equals(f2));
// outputs true, they're ""equal"" according to their definition
Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it
System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything
System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null
</code></pre>
","1650","2","1","4","2010-12-21 15:50:22","3","TRUE","299237","0"
"http://stackoverflow.com/users/419377","http://stackoverflow.com/questions/8725739","http://stackoverflow.com/questions/8725739/#8725765","2014-07-28 22:34:05","17","50396","5","7","Correct way to use StringBuilder","<p><code>return (new StringBuilder(""select id1, "" + "" id2 "" + "" from "" + "" table"")).toString();</code></p>
<p>I just found some sql query build like the above im my project. The aim of using <code>StringBuilder</code>, i.e reducing memory. Is it achieved? </p>
<p>I doubt that. Because in the constructor, String concat operator '+' is used. Will that take memory equal to using String like below? Using <code>StringBuilder.append()</code>, it differs I understood.</p>
<p><code>return ""select id1, "" + "" id2 "" + "" from "" + "" table"";</code></p>
<p>Both statements are equal in memory usage or not? Please clarify. </p>
<p>Thanks in advance!</p>
<p>Edit:</p>
<p>BTW, <strong>it is not my code</strong>. Found it in old project. Also, query is not small like my example. :)</p>
","32","783","<java><string><stringbuilder>","2012-01-04 11:03:02","FALSE","FALSE","8725765","2012-01-04 12:10:38","56","<blockquote>
<p>The aim of using StringBuilder, i.e reducing memory. Is it achieved?</p>
</blockquote>
<p>No, not at all. That code is not using <code>StringBuilder</code> correctly. (I think you've misquoted it, though; surely there aren't quotes around <code>id2</code> and <code>table</code>?)</p>
<p>Note that the aim (usually) is to reduce memory <em>churn</em> rather than total memory used, to make life a bit easier on the garbage collector.</p>
<blockquote>
<p>Will that take memory equal to using String like below?</p>
</blockquote>
<p>No, it'll cause <em>more</em> memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit <code>StringBuilder</code> in the code is unnecessary and optimizes it out, if it can.)</p>
<p>If the author of that code wants to use <code>StringBuilder</code> (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around <code>id2</code> and <code>table</code>):</p>
<pre><code>StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append(""select id1, "");
sb.append(id2);
sb.append("" from "");
sb.append(table);
return sb.toString();
</code></pre>
<p>Note that I've listed <code>some_appropriate_size</code> in the <code>StringBuilder</code> constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is <a href=""http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html#StringBuilder%28%29"">16 characters</a>, which is usually too small and results in the <code>StringBuilder</code> having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific <code>append</code>] each time it runs out of room).</p>
<p>You may have heard that string concatenation <em>will</em> use a <code>StringBuilder</code> under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one <code>StringBuilder</code> for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is <em>not</em> true of a <em>series</em> of concatenations. So for instance, this uses one <code>StringBuilder</code>:</p>
<pre><code>return ""prefix "" + variable1 + "" middle "" + variable2 + "" end"";
</code></pre>
<p>It roughly translates to:</p>
<pre><code>StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append(""prefix "");
tmp.append(variable1);
tmp.append("" middle "");
tmp.append(variable2);
tmp.append("" end"");
return tmp.toString();
</code></pre>
<p>So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough&nbsp;&mdash; and the concatenation is a <em>lot</em> more readable.</p>
<p>But that's only for a single expression. Multiple <code>StringBuilder</code>s are used for this:</p>
<pre><code>String s;
s = ""prefix "";
s += variable1;
s += "" middle "";
s += variable2;
s += "" end"";
return s;
</code></pre>
<p>That ends up becoming something like this:</p>
<pre><code>String s;
StringBuilder tmp;
s = ""prefix "";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append("" middle "");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append("" end"");
s = tmp.toString();
return s;
</code></pre>
<p>...which is pretty ugly.</p>
<p>It's important to remember, though, that in all but a very few cases <em>it doesn't matter</em> and going with readability (which enhances maintainability) is preferred barring a specific performance issue.</p>
","3933","14","5","11","2012-01-04 11:04:49","1","TRUE","299237","11"
"http://stackoverflow.com/users/2411565","http://stackoverflow.com/questions/18594177","http://stackoverflow.com/questions/18594177/#18595779","2013-09-03 15:41:56","4","390","0","2","Python encoded utf-8 string \xc4\x91 in Java","<p>How to get proper Java string from Python created string 'Oslobo\xc4\x91enja'?
How to decode it? I've tryed I think everything, looked everywhere, I've been stuck for 2 days with this problem. Please help!</p>
<p>Here is the Python's web service method that returns JSON from which Java client with Google Gson parses it.</p>
<pre><code>def list_of_suggestions(entry):
input = entry.encode('utf-8')
""""""Returns list of suggestions from auto-complete search""""""
json_result = { 'suggestions': [] }
resp = urllib2.urlopen('https://maps.googleapis.com/maps/api/place/autocomplete/json?input=' + urllib2.quote(input) + '&amp;location=45.268605,19.852924&amp;radius=3000&amp;components=country:rs&amp;sensor=false&amp;key=blahblahblahblah')
# make json object from response
json_resp = json.loads(resp.read())
if json_resp['status'] == u'OK':
for pred in json_resp['predictions']:
if pred['description'].find('Novi Sad') != -1 or pred['description'].find(u'Нови Сад') != -1:
obj = {}
obj['name'] = pred['description'].encode('utf-8').encode('string-escape')
obj['reference'] = pred['reference'].encode('utf-8').encode('string-escape')
json_result['suggestions'].append(obj)
return str(json_result)
</code></pre>
<p>Here is solution on Java client</p>
<pre><code>private String python2JavaStr(String pythonStr) throws UnsupportedEncodingException {
int charValue;
byte[] bytes = pythonStr.getBytes();
ByteBuffer decodedBytes = ByteBuffer.allocate(pythonStr.length());
for (int i = 0; i &lt; bytes.length; i++) {
if (bytes[i] == '\\' &amp;&amp; bytes[i + 1] == 'x') {
// \xc4 =&gt; c4 =&gt; 196
charValue = Integer.parseInt(pythonStr.substring(i + 2, i + 4), 16);
decodedBytes.put((byte) charValue);
i += 3;
} else
decodedBytes.put(bytes[i]);
}
return new String(decodedBytes.array(), ""UTF-8"");
}
</code></pre>
","44","1992","<java><python><string><utf-8><utf8-decode>","2013-09-03 13:56:04","TRUE","FALSE","18595779","2013-09-03 15:41:56","1","<p>You are returning the string version of the <em>python</em> data structure.</p>
<p>Return an actual JSON response instead; <em>leave</em> the values as Unicode:</p>
<pre><code>if json_resp['status'] == u'OK':
for pred in json_resp['predictions']:
desc = pred['description']
if u'Novi Sad' in desc or u'Нови Сад' in desc:
obj = {
'name': pred['description'],
'reference': pred['reference']
}
json_result['suggestions'].append(obj)
return json.dumps(json_result)
</code></pre>
<p>Now Java does not have to interpret Python escape codes, and can instead parse valid JSON instead.</p>
","677","3","1","1","2013-09-03 15:12:58","76","TRUE","289428","0"
"http://stackoverflow.com/users/1819402","http://stackoverflow.com/questions/13352389","http://stackoverflow.com/questions/13352389/#13352412","2012-11-12 22:39:15","4","154","0","3","One int for every python object","<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href=""http://stackoverflow.com/questions/8319910/auto-incrementing-ids-for-class-instances"">Auto-incrementing IDs for Class Instances</a> </p>
</blockquote>
<p>I want to something like the following Java class in Python:</p>
<pre><code>public class MyObject {
private static int ID = 0;
private final int id;
public MyObject() {
id = ID++;
}
}
</code></pre>
<p>In this Java code, every <code>myObject</code> will have <code>id</code> and there will be no way that two objects could have the same ID (it's a one-threaded application).</p>
<p>Can I do something like this in Python?</p>
","31","680","<java><python><static><int>","2012-11-12 22:07:43","TRUE","FALSE","13352412","2012-11-12 22:39:15","8","<p>In Python, you can just refer directly to the class attribute:</p>
<pre><code>class MyObject(object):
ID = 0
def __init__(self):
self.id = MyObject.ID = MyObject.ID + 1
</code></pre>
<p>Demo:</p>
<pre><code>&gt;&gt;&gt; class MyObject(object):
... ID = 0
... def __init__(self):
... self.id = MyObject.ID = MyObject.ID + 1
...
&gt;&gt;&gt; MyObject().id
1
&gt;&gt;&gt; MyObject().id
2
&gt;&gt;&gt; MyObject().id
3
&gt;&gt;&gt; MyObject.ID
3
</code></pre>
","493","2","2","6","2012-11-12 22:10:00","3","TRUE","289428","0"
"http://stackoverflow.com/users/1329402","http://stackoverflow.com/questions/12385711","http://stackoverflow.com/questions/12385711/#12385881","2012-09-12 10:14:15","3","134","2","2","How do i run the functions randomly in jython script?","<pre><code>class TestRunner:
def __call__(self):
user1()
user2()
user3()
user4()
</code></pre>
<p>How do I execute the users randomly in jython, to run in grinder tool?</p>
","53","210","<java><python><jython><grinder>","2012-09-12 10:02:51","TRUE","FALSE","12385881","2012-09-12 10:14:15","6","<p>Store the functions in a list (without calling them), then use <code>random.shuffle</code>:</p>
<pre><code>import random
class TestRunner:
def __call__(self):
users = [user1, user2, user3, user4]
random.shuffle(users)
for user in users:
user()
</code></pre>
","303","1","1","1","2012-09-12 10:12:58","10","TRUE","289428","0"
"http://stackoverflow.com/users/1663206","http://stackoverflow.com/questions/12372621","http://stackoverflow.com/questions/12372621/#12373158","2012-09-11 23:09:35","2","193","0","1","Android Python MySQL Datetime Parsing","<p>I need to pass datetimes between an android client, a python server and a mysql server.</p>
<p>It should work the following:</p>
<ul>
<li>the android client sends the exact time from the client to the cherrypy python server (I guess the datetime object should be sent as a string?)</li>
<li>the server has to parse this string into something useful to work with as a datetime object</li>
</ul>
<p>Now there a two cases:</p>
<ol>
<li>the datetime object should be written into a mysql database (there is an attribute of type DATETIME in the related database table)</li>
<li>the server should retrieve a datetime from the mysql database and compare it with the parsed datetime object</li>
</ol>
<p>After some background processes finished their work with the python datetime objects as input parameters, a new datetime object should be passed back to the android client</p>
<p>Does anyone know some good solution for solving these problems?</p>
","37","952","<java><android><python><mysql><datetime>","2012-09-11 14:57:15","FALSE","FALSE","12373158","2012-09-11 15:48:41","1","<p>The best format for transferring datetime values is the <a href=""https://en.wikipedia.org/wiki/ISO_8601"" rel=""nofollow"">ISO 8601 standard</a>; they come in the format <code>YYYY-mm-ddTHH:MM:SS+tz:tz</code>, where the <code>T</code> is optional.</p>
<p>Python's <code>datetime.datetime</code> class can parse these with a simple extra module (see <a href=""http://stackoverflow.com/questions/127803/how-to-parse-iso-formatted-date-in-python"">How to parse ISO formatted date in python?</a>). Output is just as easy with the <a href=""http://docs.python.org/library/datetime.html#datetime.datetime.isoformat"" rel=""nofollow""><code>.isoformat()</code> method</a>.</p>
<p>MySQL's DATETIME column type only deals with UTC values, but by default accepts ISO 8601 datetime strings (with a space instead of a <code>T</code>), so you'd have to cast your datetime objects to UTC (example with iso8601 module mentioned above):</p>
<pre><code>import iso8601
utciso8601 = dt.astimezone(iso8601.iso8601.UTC).isoformat(' ')[:19]
</code></pre>
<p>I'd insert the timezone offset into the database too; simply use the <a href=""http://docs.python.org/library/datetime.html#datetime.datetime.tzname"" rel=""nofollow""><code>tzname()</code> method</a> to retrieve it from the <code>datetime</code> object, then parse it out again when loading from MySQL with the <code>iso8601.iso8601.parse_timezone()</code> function.</p>
<pre><code># insertion:
cursor.execute('INSERT INTO dates VALUES(?, ?)', utciso8601, dt.tzname())
# querying
for row in query:
timezone = iso8601.iso8601.parse_timezone(row[1])
utcdt = iso8601.parse_date(row[0])
dt = utcdt.astimezone(timezone)
</code></pre>
<p>I don't know how well Android deals with dates and times, but surely it can handle ISO 8601 formats just fine.</p>
","1793","5","2","1","2012-09-11 15:29:33","32","TRUE","289428","0"
"http://stackoverflow.com/users/2426316","http://stackoverflow.com/questions/20530678","http://stackoverflow.com/questions/20530678/#20530734","2013-12-11 22:00:50","1","247","1","2","How can I convert a byte array to a double in python?","<p>I am using Java to convert a double into a byte array. Like this:</p>
<pre><code>public static byte[] toByteArray(double value) {
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putDouble(value);
return bytes;
}
</code></pre>
<p>Now, I would like to convert this byte array back into a double. In Java I would do it like this:</p>
<pre><code>public static double toDouble(byte[] bytes) {
return ByteBuffer.wrap(bytes).getDouble();
}
</code></pre>
<p>Now, how can I write the <code>toDouble()</code> method in Python?</p>
","53","547","<java><python><double><byte>","2013-12-11 21:52:58","TRUE","FALSE","20530734","2013-12-11 22:00:50","1","<p>Python has the <a href=""http://docs.python.org/2/library/struct.html"" rel=""nofollow""><code>struct</code> module</a> to convert bytes back to <code>float</code> values:</p>
<pre><code>import struct
value = struct.unpack('d', bytes)[0]
</code></pre>
<p>Here <code>'d'</code> signifies that a double value is expected (in native endianess, as 8 bytes). See the module documentation for more options, including specifying endianess.</p>
<p>Another option is to turn your <code>bytes</code> value into an <a href=""http://docs.python.org/2/library/array.html"" rel=""nofollow""><code>array</code> object</a>; you'd use this is if you had a homogenous sequence of doubles:</p>
<pre><code>import array
doubles_sequence = array.array('d', bytes)
</code></pre>
<p>where every 8 bytes is interpreted as a double value, making <code>doubles_sequence</code> a sequence of doubles, addressable by index. To support a different endianess, you can swap the byte order with <code>doubles_sequence.byteswap()</code>.</p>
","1010","4","2","2","2013-12-11 21:55:39","3","TRUE","289428","0"
"http://stackoverflow.com/users/2708477","http://stackoverflow.com/questions/18472336","http://stackoverflow.com/questions/18472336/#18472421","2013-08-27 18:43:22","1","169","0","4","why the list behaves differently in python and Java?","<p>I am learning the scripting language, python. I know Java quite a bit. I am trying to translate one bit of code from Java to python. but they behave erratically (or my understanding could be totally wrong)
I have the following code in Java, where I am adding elements to a ArrayList indefinitely.
so this causes outofmemory error, which I expect:</p>
<pre><code>import java.util.*;
public class Testing{
public static void main(String[] args){
ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();
list.add(5);
list.add(4);
for (int i=0;i&lt;list.size();i++){
list.add(5);
}
}
}
</code></pre>
<p>now the same code translated in python:</p>
<pre><code>lst = []
lst.append(5)
lst.append(4)
for i in range(len(lst)):
lst.append(5)
print lst
</code></pre>
<p>here I get the output: <code>[5, 4, 5, 5]</code></p>
<p>from what I see, is the list not passed as a reference to the <code>for</code> loop in python?</p>
<p>similarly here,</p>
<pre><code>&gt;&gt;&gt; l=[1,2,3]
&gt;&gt;&gt; for i in l[:]:
... l.append(4)
... print l
...
[1, 2, 3, 4]
[1, 2, 3, 4, 4]
[1, 2, 3, 4, 4, 4]
</code></pre>
<p>in each iteration inside the <code>for</code> loop, I am increasing the list size, so the iteration should go forever correct?</p>
","52","1307","<java><python><arrays><list><for-loop>","2013-08-27 17:52:56","TRUE","FALSE","18472421","2013-08-27 18:43:22","10","<p>A python <code>for</code> loop evaluates the expression that yields the iterable over which to loop <strong>once</strong> only. You can manipulate the <code>lst</code> object in the loop without affecting the outcome of what <code>for</code> is looping over. This differs from the Java <code>for</code> construct (which is a very different construct from the Python <code>for</code> statement, which is really a <a href=""http://en.wikipedia.org/wiki/Foreach_loop"" rel=""nofollow"">Foreach</a> construct), which evaluates the 3 associated expressions for each iteration.</p>
<p>In your first example, you created a <code>range()</code> result, and once that is created it is not updated for each loop iteration.</p>
<p>In your second example, you created a copy of <code>lst</code> using a full-length slice (<code>lst[:]</code>) for the loop to iterate over. The copy is not re-created for each loop iteration.</p>
<p>There is a caveat here, however. The <code>for</code> loop calls <a href=""http://docs.python.org/2/library/functions.html#iter"" rel=""nofollow""><code>iter()</code></a> on the object-to-be-iterated-over. For a list object, the resulting list iterator does keep a reference to the original list, as well as an iteration index. Every time the <code>for</code> loop advances the iterator (calling <a href=""http://docs.python.org/2/library/functions.html#next"" rel=""nofollow""><code>next()</code></a> on it), the iteration index is incremented and looked up on the original list, until the index is equal to the list length. If you keep adding to the list in the loop, that <em>would</em> create an infinite loop.</p>
<p>You can see this if you do <em>not</em> create a copy of the list to iterate over:</p>
<pre><code>&gt;&gt;&gt; L = [1, 2, 3]
&gt;&gt;&gt; for i in L:
... L.append(4)
... print L
... if len(L) &gt; 30:
... break
...
[1, 2, 3, 4]
[1, 2, 3, 4, 4]
[1, 2, 3, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
</code></pre>
<p>Here, the iterator created for <code>L</code> keeps yielding the next element as <code>L</code> is extended in the loop, and if I had not added a length limit in the loop this would have continued forever.</p>
","3600","6","1","2","2013-08-27 17:56:38","4","TRUE","289428","0"
"http://stackoverflow.com/users/717559","http://stackoverflow.com/questions/12763428","http://stackoverflow.com/questions/12763428/#12763435","2012-10-06 20:12:41","1","483","0","1","What encoding is this '\x00\x00\x00\x05'?","<p>I'm sending an Integer from my Java Client to my Python Server using:</p>
<pre><code>outputStream.writeInt(5);
</code></pre>
<p>And on the server:</p>
<pre><code>_id = self.request.recv(4)
</code></pre>
<p>I get: </p>
<pre><code>Name | Type| Value
_id | str | '\x00\x00\x00\x05'
</code></pre>
<p>How can i decode this and convert it back to Integer ?</p>
","41","371","<java><python><sockets><encoding><tcp>","2012-10-06 20:11:47","TRUE","FALSE","12763435","2012-10-06 20:12:41","4","<p>You can decode this with the python <a href=""http://docs.python.org/library/struct.html"" rel=""nofollow""><code>struct</code> module</a>:</p>
<pre><code>&gt;&gt;&gt; import struct
&gt;&gt;&gt; struct.unpack('&gt;i', '\x00\x00\x00\x05')
(5,)
</code></pre>
<p>The <code>&gt;i</code> pattern expects a big-endian signed integer (4 bytes).</p>
","343","2","1","4","2012-10-06 20:12:41","1","TRUE","289428","0"
"http://stackoverflow.com/users/2735409","http://stackoverflow.com/questions/19936178","http://stackoverflow.com/questions/19936178/#19936234","2013-11-12 18:07:11","0","61","0","1","Python Struct and reading values in Java","<p>I want to export a binary format and then I read the binary in Java, But i am not able to get correct values, for example</p>
<pre><code>f.write(struct.pack('&lt;f', 21.988))
</code></pre>
<p>in Java I have this value: <code>8.962863E27</code></p>
<p>I try to send a binary and match the output to ubjson library written in java, at first I use Big-endian mark but does not work, and when I use Little-endian it works like that.</p>
<p>Thanks for any guides. </p>
<p><strong>Edit: some part of library</strong></p>
<pre><code>public JsonValue parse(final DataInputStream din) throws IOException {
return parse(din, din.readByte());
}
protected JsonValue parse(final DataInputStream din, final byte type) throws IOException {
if (type == '[')
return parseArray(din);
else if (type == '{')
return parseObject(din);
else if (type == 'Z')
return new JsonValue(JsonValue.ValueType.nullValue);
else if (type == 'T')
return new JsonValue(true);
else if (type == 'F')
.....
</code></pre>
","40","1111","<java><python><binary>","2013-11-12 17:41:04","TRUE","FALSE","19936234","2013-11-12 17:51:08","1","<p>Your Java application is using the opposite endianess; you are writing little-endian, but Java interpreted the value as big endian:</p>
<pre><code>&gt;&gt;&gt; struct.unpack('&gt;f', struct.pack('&lt;f', 21.988))
(8.962863280123082e+27,)
</code></pre>
<p>Write big-endian and Java will read the values correctly:</p>
<pre><code>struct.pack('&gt;f', 21.988)
</code></pre>
<p>If that doesn't work there are <em>other</em> reasons that your output is not interpreted correctly. The <a href=""http://ubjson.org/#endian"" rel=""nofollow"">UBJSON specification</a> is quite clear about endianess, it should all be encoded big-endian.</p>
","635","3","2","9","2013-11-12 17:44:16","3","TRUE","289428","0"
"http://stackoverflow.com/users/1345655","http://stackoverflow.com/questions/21185459","http://stackoverflow.com/questions/21185459/#21185485","2014-01-17 12:00:26","0","86","0","1","Python equivalent to java.io.File","<p>I'm writing script to automate system administration tasks on my Linux system. </p>
<p>This involves compressing, moving, deleting, renaming and searching a lot of files. I learned doing these in Python by looking up examples on Internet and here on Stackoverflow.</p>
<p>The typical approach is to create a command string and pass it to the OS to have it executed. </p>
<pre><code>print Popen(""cat /home/kshitiz/myfile"", stdout=PIPE).stdout.read()
</code></pre>
<p>The directory paths are handled as strings.</p>
<p>Now consider following example: </p>
<p>We have a program that asks user for a dir and a file and creates a path. If a user enters <code>/home/kshitiz</code> and <code>myfile</code> the path becomes <code>/home/kshitizmyfile</code>. In Python I must do jugglery with strings to deal with this. In Java I can simply do: <code>new File(parentDir, filename)</code></p>
<p>Since Python is supposed to be better at OS administration it surprises me that it doesn't have object oriented abstractions over the file system. </p>
<p><strong>What are the other approaches in Python to deal with the file system?</strong></p>
","33","1143","<java><python>","2014-01-17 11:59:17","TRUE","FALSE","21185485","2014-01-17 12:00:26","1","<p>You are looking for the <a href=""http://docs.python.org/2/library/os.path.html"" rel=""nofollow""><code>os.path</code> module</a>:</p>
<pre><code>path = os.path.join(parentDir, filename)
</code></pre>
","202","1","1","3","2014-01-17 12:00:26","1","TRUE","289428","0"
"http://stackoverflow.com/users/613428","http://stackoverflow.com/questions/12580876","http://stackoverflow.com/questions/12580876/#12581005","2012-09-25 10:27:46","0","77","0","2","How to document a returned list in Python","<p>I have a piece of code that scrapes a college timetable webpage and generates a list of lists of lists (of lists) like so:</p>
<pre><code>[[[[start_time, end_time], [module_code, period_type, {period_number}], [room_code]], {next modules...}],{next_days...}]
</code></pre>
<p>If I wanted to document this kind of returned data in Python (and possibly Java or other languages) would there be a best practice for doing so? </p>
<p>Note: I've looked at PEP but haven't been able to find anything related to this</p>
","41","519","<java><python><list><javadoc><pep>","2012-09-25 10:18:13","TRUE","FALSE","12581005","2012-09-25 10:27:46","4","<p>You create simple classes to hold your data instead of using nested lists:</p>
<pre><code> class TimeTableEntry(object):
def __init__(self, start, end, module, room):
self.start = start
self.end = end
self.module = module
self.room = room
</code></pre>
<p>Then document that your method returns a list of those. The added advantage is that now you can add additional methods on these objects. Add a <code>__str__</code> method for easy display. Etc.</p>
<p>Most of all, you can document these entry objects far more clearly than you could document a nested structure of primitive types.</p>
","638","3","1","5","2012-09-25 10:25:59","7","TRUE","289428","0"
"http://stackoverflow.com/users/1329402","http://stackoverflow.com/questions/12366268","http://stackoverflow.com/questions/12366268/#12366567","2012-09-11 10:04:13","0","585","0","2","arg can't be coerced to java.util.List? Could any one tell me whats wrong in my code please?","<pre><code>myDict = {'itemkey1':'itemvalue1', 'itemkey2':'itemkey2','itemkey3':'itemvalue3','itemkey4':'itemvalue4'};
event = portTest.event(myDict);
</code></pre>
<p>I am getting the following error </p>
<p><code>Aborted run: Jython exception: TypeError:arg can't be coerced to java.util.List</code></p>
<p><code>myDict</code> is the array of key values. </p>
<p>i hope i am passing the correct syntax in <code>myDict</code> for <code>keyvalue[]</code> datalist as it just got key value pair.</p>
<pre><code>public Response event(KeyValue[] dataList)
</code></pre>
<p>I am calling the event function in java from jython script using grinder tool.</p>
","92","659","<java><python><jython><grinder>","2012-09-11 09:04:50","TRUE","FALSE","12366567","2012-09-11 10:04:13","1","<p>You'll need to turn your dictionary into a series of keys and values:</p>
<pre><code>def chainDict(mapping):
items = []
for item in mapping.iteritems():
items.extend(item)
return items
event = portTest.event(chainDict(myDict))
</code></pre>
<p>This'll pass a list of <code>[keyFoo, valueFoo keyBar, valueBar]</code> to the <code>event</code> method, where keys and values are paired but in arbitrary order.</p>
<p>If you don't have an <code>itertools</code> module available, <code>chain</code> can be defined as:</p>
","545","3","1","13","2012-09-11 09:22:53","18","TRUE","289428","0"
"http://stackoverflow.com/users/274473","http://stackoverflow.com/questions/2498635","http://stackoverflow.com/questions/2498635/#2498670","2010-03-23 09:28:38","5","4723","3","1","Java Regex for matching quoted string with escaped quotes","<p>I know there are already many questions like mine but I found no answer which works in Java. So I write a new question.</p>
<p>I have text files with content like this:</p>
<pre>
key1 = ""This is a \""test\"" text with escapes using '\\' characters"";
key2 = 'It must work with \'single\' quotes and ""double"" quotes';
</pre>
<p>I need a regular expression which matches the values in the double-quotes (or single-quotes). This regular expression must support the escaped quotes and escaped backslashes.
The regular expression must work with Java standard Pattern/Matcher classes.</p>
","57","587","<java><regex><escaping><quotes>","2010-03-23 09:15:37","FALSE","FALSE","2498670","2010-03-23 09:28:38","5","<p>Try this regular expression:</p>
<pre><code>'([^\\']+|\\([btnfr""'\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*'|""([^\\""]+|\\([btnfr""'\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*""
</code></pre>
<p>And as a string literal:</p>
<pre><code>""'([^\\\\']+|\\\\([btnfr\""'\\\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*'|\""([^\\\\\""]+|\\\\([btnfr\""'\\\\]|[0-3]?[0-7]{1,2}|u[0-9a-fA-F]{4}))*\""""
</code></pre>
","388","2","2","4","2010-03-23 09:20:42","5","TRUE","286826","0"
"http://stackoverflow.com/users/91098","http://stackoverflow.com/questions/2171900","http://stackoverflow.com/questions/2171900/#2171906","2010-01-31 14:00:47","3","73","0","1","Help constructing regex","<p>I need to know if a string matches a number of different criterias. I'm trying to solve this by using a regular expression and then see if it matches (in Java: str.matches(myRegex);), but I can't get it right.</p>
<p>The criterias are as follows:</p>
<ul>
<li>The string to match is constructed of 4 letters, [A-Z]</li>
<li>It may be preceeded (but not necessarily) by one of ""-"", ""+"" or ""VC""</li>
<li>It shall only match strings containing exactly 4 letters (and the possibly preceeding characters) </li>
</ul>
<p>Examples:</p>
<ul>
<li>""SHSN"" -> match</li>
<li>""+SHRA"" -> match</li>
<li>""VCSHRA"" -> match</li>
<li>""CAVOK"" -> no match</li>
<li>""-+SHSN"" -> no match</li>
</ul>
<p>Is this possible to do in one single regex? Or should it be done in code or a combination of the two?</p>
<p>Thanks,</p>
<p>Linus</p>
","23","824","<java><regex><string-matching>","2010-01-31 13:58:07","FALSE","FALSE","2171906","2010-01-31 14:00:47","7","<p>Try this regular expression:</p>
<pre><code>^([+-]|VC)?[A-Z]{4}$
</code></pre>
","83","1","1","3","2010-01-31 14:00:47","2","TRUE","286826","0"
"http://stackoverflow.com/users/10522","http://stackoverflow.com/questions/512342","http://stackoverflow.com/questions/512342/#512445","2014-01-12 08:26:37","1","6593","2","5","Regex in Java, finding start and end tag","<p>I am trying to find data within a HTML document. I don't need a full blown parser as it is just the data between one tag.</p>
<p>But, I want to detect the 'select' tag and the data in between. </p>
<pre><code>return Pattern.compile(pattern,
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE |
Pattern.DOTALL);
/// End right angle bracket left off intentionally:
track_pattern_buf.append(""&lt;select"");
track_pattern_buf.append(""(.*?)"");
track_pattern_buf.append(""&lt;/select"");
</code></pre>
<p>Is this the 'regex' that you would use?</p>
","40","589","<java><html><regex><matcher>","2009-02-04 17:15:07","TRUE","FALSE","512445","2014-01-12 08:26:37","4","<p>If you really want to stich with regular expressions (which are not the best choice) I’d use:</p>
<pre><code>""&lt;select[^&gt;]*&gt;(.+?)&lt;/select\s*&gt;""
</code></pre>
","175","1","1","3","2009-02-04 17:31:32","16","TRUE","286826","0"
"http://stackoverflow.com/users/205426","http://stackoverflow.com/questions/2357305","http://stackoverflow.com/questions/2357305/#2357321","2010-11-17 11:10:48","1","1876","1","4","Regex for checking > 1 upper, lower, digit, and special char","<pre><code>^.*(?=.{15,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*+=]).*$
</code></pre>
<p>This is the regex I am currently using which will evaluate on 1 of each: upper,lower,digit, and specials of my choosing. The question I have is how do I make it check for 2 of each of these? Also I ask because it is seemingly difficult to write a test case for this as I do not know if it is only evaluating the first set of criteria that it needs. This is for a password, however the requirement is that it needs to be in regex form based on the package we are utilizing. </p>
<p><em><strong>EDIT</em></strong></p>
<p>Well as it stands in my haste to validate the expression I forgot to validate my string length. Thanks to Ken and Gumbo on helping me with this.</p>
<p>This is the code I am executing:</p>
<p>I do apologize as regex is not my area.</p>
<p>The password I am using is the following string ""$$QiouWER1245"", the behavior I am experiencing at the moment is that it randomly chooses to pass or fail. Any thoughts on this?</p>
<pre><code>Pattern pattern = Pattern.compile(regEx);
Matcher match = pattern.matcher(password);
while(match.find()){
System.out.println(match.group());
}
</code></pre>
<p>From what I see if it evaluates to true it will throw the value in password back to me else it is an empty string.</p>
","60","1349","<java><regex>","2010-03-01 16:31:24","TRUE","FALSE","2357321","2010-03-01 16:51:41","2","<p>Try this:</p>
<pre><code>""^(?=(?:\\D*\\d){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^!@#$%^&amp;*+=]*[!@#$%^&amp;*+=]){2}).{15,}$""
</code></pre>
<p>Here non-capturing groups <code>(?:…)</code> are used to group the conditions and repeat them. I’ve also used the complements of each character class for optimization instead of the universal <code>.</code>.</p>
","379","2","1","7","2010-03-01 16:34:00","3","TRUE","286826","0"
"http://stackoverflow.com/users/238505","http://stackoverflow.com/questions/3381319","http://stackoverflow.com/questions/3381319/#3381328","2010-08-03 03:31:29","1","101","0","3","Which regex to use?","<p>i have expressions like :</p>
<pre><code>-3-5
or -3--5
or 3-5
or 3-+5
or -3-+5
</code></pre>
<p>I need to extact the numbers , splitting on the ""-"" sign between them i.e in the above cases i would need,
-3 and 5, -3 and -5 , 3 and 5, 3 and +5 , -3 and +5.
I have tried using this:</p>
<pre><code>String s[] = str.split(""[+-]?\\d+\\-[+-]?\\d+"");
int len = s.length;
for(int i=0;i&lt;len;i++)System.out.println(s[i]);
</code></pre>
<p>but it's not working </p>
","19","480","<java><regex>","2010-08-01 08:35:48","TRUE","FALSE","3381328","2010-08-03 03:31:29","8","<p>Try to split with this regular expression:</p>
<pre><code>str.split(""\\b-"")
</code></pre>
<p>The word boundary <code>\b</code> should only match before or after a digit so that in combination with <code>-</code> only the following <code>-</code> as the range indicator is matched:</p>
<pre><code>-3-5, -3--5 , 3-5,3-+5,-3-+5
^ ^ ^ ^ ^
</code></pre>
","372","2","2","8","2010-08-01 08:37:34","2","TRUE","286826","0"
"http://stackoverflow.com/users/298430","http://stackoverflow.com/questions/3333646","http://stackoverflow.com/questions/3333646/#3333692","2010-07-26 09:40:08","1","391","0","4","How to wrap ""<pre>"" tag around whitespaces in a java String?","<p>Suppose I have a long java String , I need to wrap all whitespaces (length >=2) with <code>&lt;pre&gt;&lt;/pre&gt;</code> tag... , How to achieve that ?</p>
<p>ex :</p>
<pre><code>before :
String str = ""&lt;font color=\""#000000\""&gt;A B C D&lt;/font&gt;""
after :
&lt;font color=\""#000000\""&gt;A B&lt;pre&gt; &lt;/pre&gt;C&lt;pre&gt; &lt;/pre&gt;D&lt;/font&gt;
Between A and B is one whitespace , and not wrapped.
Between B and C is two whitespaces , and it is wrapped.
Between C and D is three whitespaces , and it is wrapped,too.
</code></pre>
<p>How to achieve that in RegExp ? Thanks a lot !</p>
","60","613","<java><regex>","2010-07-26 09:32:48","TRUE","FALSE","3333692","2010-07-26 09:40:08","5","<p>How about a CSS solution using <a href=""http://www.w3.org/TR/CSS2/text.html#white-space-prop"" rel=""nofollow""><code>white-space</code></a>:</p>
<pre><code>white-space: pre
</code></pre>
<p>With this sequences of white space are not collapsed. So:</p>
<pre><code>&lt;font color=""#000000"" style=""white-space:pre""&gt;A B C D&lt;/font&gt;
</code></pre>
","357","2","2","4","2010-07-26 09:40:08","8","TRUE","286826","0"
"http://stackoverflow.com/users/330057","http://stackoverflow.com/questions/3477302","http://stackoverflow.com/questions/3477302/#3477313","2013-04-18 05:46:11","0","96","0","3","Combining two regex expressions into one","<p>I have a regex that works: <code>ABC-[0-9]+</code></p>
<p>I also have a regex: <code>DEF-[0-9]+</code></p>
<p>But I don't get how to combine the two so it will match them both</p>
<p>I tried <code>ABC-[0-9]+ | DEF-[0-9]+</code> but it didn't really work...</p>
<p>This is all in Java regex if it matters.</p>
","40","316","<java><regex>","2010-08-13 13:36:09","FALSE","FALSE","3477313","2010-08-13 13:46:53","7","<p>If you want a regular expression that matches sequences that start with either <code>ABC</code> or <code>DEF</code>, try this:</p>
<pre><code>(ABC|DEF)-[0-9]+
</code></pre>
<p>But except from the two space characters around <code>|</code>, your regular expression should match that too:</p>
<pre><code>ABC-[0-9]+|DEF-[0-9]+
</code></pre>
<p>These two regular expressions match the same set of strings.</p>
","413","3","2","3","2010-08-13 13:37:19","1","TRUE","286826","0"
"http://stackoverflow.com/users/139766","http://stackoverflow.com/questions/1482050","http://stackoverflow.com/questions/1482050/#1482052","2009-09-27 11:47:14","0","1110","0","4","Java Regexs: unexpected char: '('","<p>I am using processing 1.0.6, which runs on java 1.6. I have the following code:</p>
<pre><code>Pattern pattern = Pattern.compile(""func\((.*),(\-?[0-9\.]*),(\-?[0-9\.]*),(\-?[0-9\.]*)\)"");
</code></pre>
<p>but it gives the error:</p>
<pre><code>unexpected char: '('
</code></pre>
<p>and highlights the line I pasted above. If I change the offending <code>\(</code> to another character like <code>#</code>, it complains of the <code>\-</code> saying <code>unexpected char: '-'</code>. I should be able to use literals in a regex engine and it works in C#!</p>
","33","566","<java><regex><literals>","2009-09-26 19:57:45","TRUE","FALSE","1482052","2009-09-27 11:47:14","4","<p>You need to escape the backslashes too:</p>
<pre><code>""func\\((.*),(-?[0-9.]*),(-?[0-9.]*),(-?[0-9.]*)\\)""
</code></pre>
<p>That string expression will the be evaluated to:</p>
<pre><code>func\((.*),(-?[0-9.]*),(-?[0-9.]*),(-?[0-9.]*)\)
</code></pre>
<p>And that’s what you wanted.</p>
","294","3","2","4","2009-09-26 20:00:23","3","TRUE","286826","0"
"http://stackoverflow.com/users/60173","http://stackoverflow.com/questions/1026723","http://stackoverflow.com/questions/1026723/#1026736","2014-07-18 20:13:05","215","191081","56","9","How to convert a Map to List in Java?","<p>What is the best way to convert a <code>Map&lt;key,value&gt;</code> to a <code>List&lt;value&gt;</code>? Just iterate over all values and insert them in a list or am I overlooking something?</p>
","37","198","<java><list><collections><map>","2009-06-22 11:45:28","FALSE","FALSE","1026736","2014-07-18 20:13:05","408","<pre><code>List&lt;Value&gt; list = new ArrayList&lt;Value&gt;(map.values());
</code></pre>
<p>assuming:</p>
<pre><code>Map&lt;Key,Value&gt; map;
</code></pre>
","162","1","2","2","2009-06-22 11:48:42","3","TRUE","283778","0"
"http://stackoverflow.com/users/54466","http://stackoverflow.com/questions/454908","http://stackoverflow.com/questions/454908/#454913","2014-03-06 21:58:10","135","144348","30","7","Split Java String by New Line","<p>I'm trying to split text in a <code>JTextArea</code> using a regex to split the String by <code>\n</code> However, this does not work and I also tried by <code>\r\n|\r|n</code> and many other combination of regexes.
Code:</p>
<pre><code>public void insertUpdate(DocumentEvent e) {
String split[], docStr = null;
Document textAreaDoc = (Document)e.getDocument();
try {
docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
split = docStr.split(""\\n"");
}
</code></pre>
","29","678","<java><regex><split><newline>","2009-01-18 10:13:56","TRUE","FALSE","454913","2014-03-06 21:58:10","246","<p>This should cover you:</p>
<pre><code>String lines[] = String.split(""\\r?\\n"");
</code></pre>
<p>There's only really two newlines (UNIX and Windows) that you need to worry about.</p>
","188","2","1","7","2009-01-18 10:18:19","5","TRUE","283778","0"
"http://stackoverflow.com/users/482568","http://stackoverflow.com/questions/4042434","http://stackoverflow.com/questions/4042434/#4042464","2014-06-10 19:28:24","158","129129","36","5","Convert ArrayList containing Strings to an array of Strings in Java?","<p>How might I convert a <code>String ArrayList</code> object to a <code>String[]</code> array object in Java?</p>
","68","115","<java><collections>","2010-10-28 11:30:53","FALSE","FALSE","4042464","2014-06-10 19:28:24","404","<pre><code>List&lt;String&gt; list = ..;
String[] array = list.toArray(new String[list.size()]);
</code></pre>
<p>For example:</p>
<pre><code>List&lt;String&gt; list =new ArrayList&lt;String&gt;();
//add some stuff
list.add(""android"");
list.add(""apple"");
String[] stringArray = list.toArray(new String[list.size()]);
</code></pre>
<p>The <code>toArray()</code> method without passing any argument returns <code>Object[]</code>. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.</p>
","635","2","2","5","2010-10-28 11:34:52","4","TRUE","280250","15"
"http://stackoverflow.com/users/195176","http://stackoverflow.com/questions/4334970","http://stackoverflow.com/questions/4334970/#4335514","2014-09-04 20:29:58","135","79355","53","6","Hibernate cannot simultaneously fetch multiple bags","<p>Hibernate throws this exception during SessionFactory creation:</p>
<blockquote>
<p>org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags</p>
</blockquote>
<p>This is my test case:</p>
<p><strong>Parent.java</strong></p>
<pre><code>@Entity
public Parent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy=""parent"", fetch=FetchType.EAGER)
// @IndexColumn(name=""INDEX_COL"") if I had this the problem solve but I retrieve more children than I have, one child is null.
private List&lt;Child&gt; children;
}
</code></pre>
<p><strong>Child.java</strong></p>
<pre><code>@Entity
public Child {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Parent parent;
}
</code></pre>
<p>How about this problem? What can I do?</p>
<hr>
<p><strong>EDIT</strong></p>
<p>OK, the problem I have is that another ""parent"" entity is inside my parent, my real behavior is this:</p>
<p><strong>Parent.java</strong></p>
<pre><code>@Entity
public Parent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
private AntoherParent anotherParent;
@OneToMany(mappedBy=""parent"", fetch=FetchType.EAGER)
private List&lt;Child&gt; children;
}
</code></pre>
<p><strong>AnotherParent.java</strong></p>
<pre><code>@Entity
public AntoherParent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy=""parent"", fetch=FetchType.EAGER)
private List&lt;AnotherChild&gt; anotherChildren;
}
</code></pre>
<p>Hibernate doesn't like two collections with <code>FetchType.EAGER</code>, but this seems to be a bug, I'm not doing unusual things...</p>
<p>Removing <code>FetchType.EAGER</code> from <code>Parent</code> or <code>AnotherParent</code> solves the problem, but I need it, so real solution is to use <code>@LazyCollection(LazyCollectionOption.FALSE)</code> instead of <code>FetchType</code> (thanks to <a href=""http://stackoverflow.com/users/203907/bozho"">Bozho</a> for the solution).</p>
","51","2089","<java><hibernate><jpa>","2010-12-02 12:28:19","TRUE","FALSE","4335514","2011-10-11 07:45:46","178","<p>I think a newer version of hibernate (supporting JPA 2.0) should handle this. But otherwise you can work it around by annotating the collection fields with:</p>
<pre><code>@LazyCollection(LazyCollectionOption.FALSE)
</code></pre>
<p>Remember to remove the <code>fetchType</code> attribute from the <code>@*ToMany</code> annotation.</p>
<p>But note that in most cases a <code>Set&lt;Child&gt;</code> is more appropriate than <code>List&lt;Child&gt;</code>, so unless you really need a <code>List</code> - go for <code>Set</code></p>
","538","3","1","13","2010-12-02 13:30:30","62","TRUE","280250","0"
"http://stackoverflow.com/users/39677","http://stackoverflow.com/questions/3153546","http://stackoverflow.com/questions/3153546/#3153617","2014-05-05 20:23:35","101","79729","65","2","How does autowiring work in spring?","<p>I'm a little confused as to how the IOC works in spring.</p>
<p><strong>Say I have a service class called <code>UserServiceImpl</code> that implements <code>UserService</code> interface.</strong></p>
<p>How would this be auto-wired?</p>
<p>And in my Controllers action, how would I instantiate an instance of this service?</p>
<p>Would I just do:</p>
<pre><code>UserService userService = new UserServiceImpl();
</code></pre>
","35","433","<java><spring><spring-mvc><ioc-container>","2010-06-30 21:26:06","TRUE","FALSE","3153617","2012-10-10 14:28:45","178","<p>First, and most important - all spring beans are managed - they ""live"" inside a container, called ""application context"".</p>
<p>Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.</p>
<p>Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.</p>
<p>What is ""living"" in the application context? This means that the context <em>instantiates</em> the objects, not you. I.e. - you never make <code>new UserServiceImpl()</code> - the container finds each injection point and sets an instance there.</p>
<p>In your controllers, you just have the following:</p>
<pre><code>@Controller // defines that this class is a spring bean
@RequestMapping(""/users"")
public class SomeController {
// tells the application context to inject an instance of UserService here
@Autowired
private UserService userService;
@RequestMapping(""/login"")
public void login(@RequestParam(""username"") String username,
@RequestParam(""password"") password) {
// the UserServiceImpl is already injected and you can use it
userService.login(username, password);
}
}
</code></pre>
<p>A few notes:</p>
<ul>
<li>in your <code>applicationContext.xml</code> you should enable the <code>&lt;context:component-scan&gt;</code> so that classes are scanned for the <code>@Controller</code>, <code>@Service</code>, etc. annotations.</li>
<li>the entry point for a spring-mvc application is the DispatcherServlet, but it is hidden from you, and hence the direct interaction and bootstrapping of the application context happens behind the scene.</li>
<li><code>UserServiceImpl</code> should also be defined as bean - either using <code>&lt;bean id="".."" class=""..""&gt;</code> or using the <code>@Service</code> annotation. Since it will be the only implementor or <code>UserService</code>, it will be injected.</li>
<li>apart from the <code>@Autowired</code> annotation, spring can use xml-configurable autowiring. In that case all fields that have a name or type matching the one of an existing bean is automatically gets a bean injected. In fact, that was the initial idea of autowiring - to have fields injected with dependencies without any configuration. </li>
</ul>
","2551","6","1","8","2010-06-30 21:36:05","10","TRUE","280250","0"
"http://stackoverflow.com/users/1413969","http://stackoverflow.com/questions/19498561","http://stackoverflow.com/questions/19498561/#19498655","2013-10-28 12:57:03","29","3305","1","10","return in try-catch's finally block in java. Is there any good point in this example?","<p>I'm not familiar with java and I've been recently looking at some code written by some colleagues that's baffling me. Here's the gist of it:</p>
<pre><code>public response newStuff(//random data inside) {
try {
response or = //gives it a value
log.info(or.toString());
return or;
}
catch ( Exception e) {
e.printStackTrace();
}
finally {
return null;
}
}
</code></pre>
<p>Is there really any point in adding a finally block here? Couldn't I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?</p>
","85","614","<java><try-catch>","2013-10-21 15:24:30","TRUE","FALSE","19498655","2013-10-22 13:22:53","26","<blockquote>
<p>Is there really any point in adding a finally block here?</p>
</blockquote>
<p>The answer to this is a resounding ""no"": putting a <code>return</code> statement in the <code>finally</code> block is a very bad idea.</p>
<blockquote>
<p>I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?</p>
</blockquote>
<p>It wouldn't match the original behavior, but that's a good thing, because it would fix it. Rather than returning <code>null</code> unconditionally the way the original code does, the code with the <code>return</code> inside the <code>catch</code> block would return <code>null</code> only on errors. In other words, the value returned in the <code>try</code> branch would be returned to the caller unless there is an exception.</p>
<p>Moreover, if you add <code>return null</code> <em>after</em> the <code>catch</code> block, you would see the correct effect of returning <code>null</code> on exception. I would go even further, and put a single <code>return</code> in the method, like this:</p>
<pre><code>response or = null;
try {
or = //gives it a value
log.info(or.toString());
} catch ( Exception e) {
e.printStackTrace();
}
return or;
</code></pre>
","1250","5","1","11","2013-10-21 15:27:55","3","TRUE","277660","11"
"http://stackoverflow.com/users/1688571","http://stackoverflow.com/questions/20498610","http://stackoverflow.com/questions/20498610/#20498872","2013-12-18 08:22:55","26","338","3","1","Enum and static variable in constructor","<p>Access to static fields in enum constructor is forbidden by the compiler. The source code below works, it uses a static field:</p>
<pre><code>public enum TrickyEnum
{
TrickyEnum1, TrickyEnum2;
static int count;
TrickyEnum()
{
incrementCount();
}
private static void incrementCount()
{
count++;
}
public static void main(String... args)
{
System.out.println(""Count: "" + count);
}
}
</code></pre>
<p>Output:</p>
<blockquote>
<p>Count: 2.</p>
</blockquote>
<p>But the code below does not work despite there being very little difference:</p>
<pre><code>public enum TrickyEnum
{
TrickyEnum1, TrickyEnum2;
static int count;
TrickyEnum()
{
count++; //compiler error
}
public static void main(String... args)
{
System.out.println(""Count: "" + count);
}
}
</code></pre>
<p>From my search, people usually claim that the problem is due to the order in which static fields are initialized. But first example works, so why do Java developers forbid the second example? It should also work.</p>
","39","1114","<java><constructor><static><enums>","2013-12-10 15:36:50","TRUE","FALSE","20498872","2013-12-18 08:22:55","23","<p>The compiler allows a call to a static function, because it is not smart enough to prohibit it: the legitimacy of the call cannot be deduced without looking into the body of the <code>incrementCount</code> method.</p>
<p>The reason this is prohibited becomes clear when you run the following code:</p>
<pre><code>enum TrickyEnum
{
TrickyEnum1, TrickyEnum2;
static int count = 123; // Added an initial value
TrickyEnum()
{
incrementCount();
}
private static void incrementCount()
{
count++;
System.out.println(""Count: "" + count);
}
public static void showCount()
{
System.out.println(""Count: "" + count);
}
}
public static void main (String[] args) throws java.lang.Exception
{
TrickyEnum te = TrickyEnum.TrickyEnum1;
TrickyEnum.showCount();
}
</code></pre>
<p>This prints</p>
<pre><code>1
2
123
</code></pre>
<p>which is extremely confusing to a programmer reading your code: essentially, <code>incrementCount</code> does its modifications to the static field <em>before</em> it has been initialized.</p>
<p>Here is a <a href=""http://ideone.com/8wdUnT"">demo of this code on ideone</a>.</p>
","1187","5","2","1","2013-12-10 15:47:31","11","TRUE","277660","0"
"http://stackoverflow.com/users/831923","http://stackoverflow.com/questions/9406025","http://stackoverflow.com/questions/9406025/#9406049","2013-09-21 02:41:14","15","4184","7","4","What does the generic nature of the class Class<T> mean? What is T?","<p>I understand generics when it comes to collections. But what does it mean in the case of the <code>Class&lt;T&gt;</code> class? When you instantiate a <code>Class</code> object, there's only one object. So why the <code>T</code> parameter? What is it specifying? And why is it necessary (if it is)?</p>
","67","306","<java><class><generics><reflection>","2012-02-23 01:50:29","FALSE","FALSE","9406049","2012-08-31 12:41:37","28","<p>Type parameter <code>&lt;T&gt;</code> has been added to <code>java.lang.Class</code> to enable one specific idiom<sup>1</sup> - use of <code>Class</code> objects as type-safe object factories. Essentially, the addition of <code>&lt;T&gt;</code> lets you instantiate classes in a type-safe manner, like this:</p>
<pre><code>T instance = myClass.newInstance();
</code></pre>
<p>Type parameter <code>&lt;T&gt;</code> represents the class itself, enabling you to avoid unpleasant effects of type erasure by storing <code>Class&lt;T&gt;</code> in a generic class or passing it in as a parameter to a generic method. Note that <code>T</code> by itself would not be sufficient to complete this task<sup>2</sup>: the type of <code>T</code> is erased, so it becomes <code>java.lang.Object</code> under the hood.</p>
<p>Here is a classic example where <code>&lt;T&gt;</code> parameter of the class becomes important. In the example below, Java compiler is able to ensure type safety, letting you produce a typed collection from a SQL string and an instance of <code>Class&lt;T&gt;</code>. Note that the class is used as a <em>factory</em>, and that its type safety can be verified at compile time:</p>
<pre><code>public static &lt;T&gt; Collection&lt;T&gt; select(Class&lt;T&gt; c, String sqlStatement) {
Collection&lt;T&gt; result = new ArrayList&lt;T&gt;();
/* run sql query using jdbc */
for ( /* iterate over jdbc results */ ) {
T item = c.newInstance();
/* use reflection and set all of item’s fields from sql results */
result.add(item);
}
return result;
}
</code></pre>
<p>Since Java erases the type parameter, making it a <code>java.lang.Object</code> or a class specified as the generic's <a href=""http://en.wikipedia.org/wiki/Bounded_quantification"">upper bound</a>, it is important to have access to the <code>Class&lt;T&gt;</code> object inside the <code>select</code> method. Since <code>newInstance</code> returns an object of type <code>&lt;T&gt;</code>, the compiler can perform type checking, eliminating a cast.</p>
<p><hr/>
<sup>1</sup> <strike>SUN</strike> Oracle has published <a href=""http://docs.oracle.com/javase/tutorial/extra/generics/literals.html"">a good article explaining all this</a>.</p>
<p><sup>2</sup> This is different from implementations of generics without type erasure, such as one in .NET.</p>
","2376","6","2","5","2012-02-23 01:54:41","4","TRUE","277660","0"
"http://stackoverflow.com/users/205463","http://stackoverflow.com/questions/8680442","http://stackoverflow.com/questions/8680442/#8680462","2011-12-31 18:19:16","13","11237","1","2","how to create a generic constructor for a generic class in java?","<p>I want to create a KeyValue class but in generic manner and this is what I've written:</p>
<pre><code>public class KeyValue&lt;T,E&gt;
{
private T key;
private E value;
/**
* @return the key
*/
public T getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(T key) {
this.key = key;
}
/**
* @return the value
*/
public E getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(E value) {
this.value = value;
}
public KeyValue &lt;T, E&gt;(T k , E v) // I get compile error here
{
setKey(k);
setValue(v);
}
}
</code></pre>
<p>the error says : ""Syntax error on token "">"", Identifier expected after this token""</p>
<p>how should I create a generic constructor in java then?</p>
","64","897","<java><generics>","2011-12-30 14:25:05","TRUE","FALSE","8680462","2011-12-31 18:19:16","32","<p>You need to remove <code>&lt;T, E&gt;</code> from the constructor's signature: it's already there implicitly.</p>
<pre><code>public KeyValue(T k , E v) // No compile errors here :)
{
setKey(k);
setValue(v);
}
</code></pre>
","235","1","1","4","2011-12-30 14:28:09","3","TRUE","277660","0"
"http://stackoverflow.com/users/1019978","http://stackoverflow.com/questions/9097181","http://stackoverflow.com/questions/9097181/#9097261","2012-02-01 18:16:36","13","549","1","5","Creation of Arrays in Java (The C++ Style)","<p>Why can't we make arrays in Java like this:</p>
<pre><code>int marks[5];
</code></pre>
<p>And assign values after this declaration?</p>
<p>Anyone please explain the terminology or difference.</p>
","42","202","<java><c++><arrays>","2012-02-01 14:10:19","TRUE","FALSE","9097261","2012-02-01 18:16:36","19","<p>This is because there are no stack arrays in Java. Here is Java equivalent:</p>
<pre><code>int[] marks = new int[5];
</code></pre>
<p>It looks a lot like allocating dynamically-sized arrays in C++. Of course you don't have to worry about calling a <code>delete[]</code>, because it's garbage collected.</p>
","312","2","1","1","2012-02-01 14:14:20","4","TRUE","277660","0"
"http://stackoverflow.com/users/2187257","http://stackoverflow.com/questions/18833407","http://stackoverflow.com/questions/18833407/#18833449","2013-09-16 17:35:21","8","182","3","3","Why program is not allowing to initialize the static final variable?","<p>I came across the Java code below which looks good at first but never compiles :</p>
<pre><code>public class UnwelcomeGuest {
public static final long GUEST_USER_ID = -1;
private static final long USER_ID;
static {
try {
USER_ID = getUserIdFromEnvironment();
} catch (IdUnavailableException e) {
USER_ID = GUEST_USER_ID;
System.out.println(""Logging in as guest"");
}
}
private static long getUserIdFromEnvironment()
throws IdUnavailableException {
throw new IdUnavailableException(); // Simulate an error
}
public static void main(String[] args) {
System.out.println(""User ID: "" + USER_ID);
}
}//Class ends here
//User defined Exception
class IdUnavailableException extends Exception {
IdUnavailableException() { }
}//Class ends here
</code></pre>
<p>Below is the error message which comes in the IDE :
<strong>variable USER_ID might already have been assigned.</strong></p>
<p>Is there any problem with the value assignment to the static final variable ?</p>
","68","1098","<java><static><final>","2013-09-16 16:57:07","TRUE","FALSE","18833449","2013-09-16 17:35:21","19","<p>Final variables allow at most one assignment in the constructor or the initializer block. The reason this does not compile is that Java code analyzer sees two assignments to <code>USER_ID</code> in branches that do not look mutually exclusive to it.</p>
<p>Working around this problem is simple:</p>
<pre><code>static {
long theId;
try {
theId = getUserIdFromEnvironment();
} catch (IdUnavailableException e) {
theId = GUEST_USER_ID;
System.out.println(""Logging in as guest"");
}
USER_ID = theId;
}
</code></pre>
","561","2","1","7","2013-09-16 16:59:56","2","TRUE","277660","0"
"http://stackoverflow.com/users/20654","http://stackoverflow.com/questions/1463597","http://stackoverflow.com/questions/1463597/#1463620","2013-02-15 08:28:55","66","82069","14","2","Evaluate if list is empty JSTL","<p>I've been trying to evaluate if this array list is empty or not but none of these have even compiled:</p>
<pre><code>&lt;c:if test=""${myObject.featuresList.size == 0 }""&gt;
&lt;c:if test=""${myObject.featuresList.length == 0 }""&gt;
&lt;c:if test=""${myObject.featuresList.size() == 0 }""&gt;
&lt;c:if test=""${myObject.featuresList.length() == 0 }""&gt;
&lt;c:if test=""${myObject.featuresList.empty}""&gt;
&lt;c:if test=""${myObject.featuresList.empty()}""&gt;
&lt;c:if test=""${myObject.featuresList.isEmpty}""&gt;
</code></pre>
<p>How can I evaluate if an ArrayList is empty? </p>
","30","622","<java><jsp><jstl>","2009-09-23 01:54:17","TRUE","FALSE","1463620","2013-02-15 08:28:55","135","<p><a href=""http://docs.oracle.com/cd/E17904_01/web.1111/e13712/reference.htm#i67520"">empty</a> is an operator.</p>
<pre><code>&lt;c:if test=""${empty myObject.featuresList}""&gt;
</code></pre>
","193","1","1","3","2009-09-23 02:05:02","11","TRUE","277501","3"
"http://stackoverflow.com/users/80907","http://stackoverflow.com/questions/754307","http://stackoverflow.com/questions/754307/#754483","2013-07-11 11:57:42","17","17807","6","7","Regex to replace characters that Windows doesn't accept in a filename","<p>I'm trying to build a regular expression that will detect any character that Windows does not accept as part of a file name (are these the same for other OS? I don't know, to be honest).</p>
<p>These symbols are: </p>
<pre> \ / : * ? "" | </pre>
<p>Anyway, this is what I have: <code>[\\/:*?\""&lt;&gt;|]</code></p>
<p>The tester over at <a href=""http://gskinner.com/RegExr/"">http://gskinner.com/RegExr/</a> shows this to be working.
For the string <code>Allo*ha</code>, the <code>*</code> symbol lights up, signalling it's been found. Should I enter <code>Allo**ha</code> however, only the first <code>*</code> will light up. So I think I need to modify this regex to find all appearances of the mentioned characters, but I'm not sure.</p>
<p>You see, in Java, I'm lucky enough to have the function <a href=""http://java.sun.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29"">String.replaceAll(String regex, String replacement)</a>.
The description says: </p>
<blockquote>
<p>Replaces each substring of this string that matches the given regular expression with the given replacement.</p>
</blockquote>
<p>So in other words, even if the regex only finds the first and then stops searching, this function will still find them all.</p>
<p>For instance: <code>String.replaceAll(""[\\/:*?\""&lt;&gt;|]"","""")</code></p>
<p>However, I don't feel like I can take that risk. So does anybody know how I can extend this?</p>
","69","1472","<java><regex>","2009-04-16 00:23:25","FALSE","FALSE","754483","2013-07-11 11:57:42","9","<p>Windows filename rules are <em>tricky</em>. You're only scratching the surface.</p>
<p>For example here are some things that are not valid filenames, in addition to the chracters you listed:</p>
<pre><code> (yes, that's an empty string)
.
.a
a.
a (that's a leading space)
a (or a trailing space)
com
prn.txt
[anything over 240 characters]
[any control characters]
[any non-ASCII chracters that don't fit in the system codepage,
if the filesystem is FAT32]
</code></pre>
<p>Removing special characters in a single regex sub like String.replaceAll() isn't enough; you can easily end up with something invalid like an empty string or trailing ‘.’ or ‘ ’. Replacing something like “[^A-Za-z0-9_.]*” with ‘_’ would be a better first step. But you will still need higher-level processing on whatever platform you're using.</p>
","931","3","1","6","2009-04-16 01:54:09","91","TRUE","277501","0"
"http://stackoverflow.com/users/163439","http://stackoverflow.com/questions/2191186","http://stackoverflow.com/questions/2191186/#2191288","2010-02-03 11:11:53","5","7620","4","3","java regex to exclude specific strings from a larger one","<p>I have been banging my head against this for some time now:
I want to capture all <code>[a-z]+[0-9]?</code> character sequences excluding strings such as <code>sin|cos|tan</code> etc.
So having done my regex homework the following regex should work:</p>
<pre><code>(?:(?!(sin|cos|tan)))\b[a-z]+[0-9]?
</code></pre>
<p>As you see I am using negative lookahead along with alternation - the <code>\b</code> after the non-capturing group closing parenthesis is critical to avoid matching the <code>in</code> of <code>sin</code> etc. The regex makes sense and as a matter of fact I have tried it with RegexBuddy and Java as the target implementation and get the wanted result but it doesn't work using Java Matcher and Pattern objects!
Any thoughts?</p>
<p>cheers</p>
","56","769","<java><regex><regexbuddy><matcher>","2010-02-03 10:21:57","TRUE","FALSE","2191288","2010-02-03 11:11:53","6","<p>The <code>\b</code> is in the wrong place. It would be looking for a word boundary that didn't have sin/cos/tan <em>before</em> it. But a boundary just <em>after</em> any of those would have a letter at the end, so it would have to be an end-of-word boundary, which is can't be if the next character is a-z.</p>
<p>Also, the negative lookahead would (if it worked) exclude strings like <code>cost</code>, which I'm not sure you want if you're just filtering out keywords.</p>
<p>I suggest:</p>
<pre><code>\b(?!sin\b|cos\b|tan\b)[a-z]+[0-9]?\b
</code></pre>
<p>Or, more simply, you could just match <code>\b[a-z]+[0-9]?\b</code> and filter out the strings in the keyword list afterwards. You don't always have to do everything in regex.</p>
","747","4","1","8","2010-02-03 10:42:49","21","TRUE","277501","0"
"http://stackoverflow.com/users/10522","http://stackoverflow.com/questions/465979","http://stackoverflow.com/questions/465979/#466218","2012-12-06 17:25:52","4","9692","0","2","Regex in java question, multiple matches","<p>I am trying to match multiple CSS style code blocks in a HTML document. This code will match the first one but won't match the second. What code would I need to match the second. Can I just get a list of the groups that are inside of my 'style' brackets? Should I call the 'find' method to get the next match?</p>
<p>Here is my regex pattern</p>
<pre><code>^.*(&lt;style type=""text/css""&gt;)(.*)(&lt;/style&gt;).*$
</code></pre>
<p>Usage:</p>
<pre><code>final Pattern pattern_css = Pattern.compile(css_pattern_buf.toString(),
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
final Matcher match_css = pattern_css.matcher(text);
if (match_css.matches() &amp;&amp; (match_css.groupCount() &gt;= 3)) {
System.out.println(""Woot ==&gt;"" + match_css.groupCount());
System.out.println(match_css.group(2));
} else {
System.out.println(""No Match"");
}
</code></pre>
","40","965","<java><regex>","2009-01-21 16:33:13","TRUE","FALSE","466218","2009-01-21 17:53:51","14","<blockquote>
<p>I am trying to match multiple CSS style code blocks in a HTML document.</p>
</blockquote>
<p>Standard Answer: don't use regex to parse HTML. regex cannot parse HTML reliably, no matter how complicated and clever you make your expression. Unless you are absolutely sure the exact format of the target document is totally fixed, string or regex processing is insufficient and you must use an HTML parser.</p>
<pre><code>(&lt;style type=""text/css""&gt;)(.*)(&lt;/style&gt;)
</code></pre>
<p>That's a greedy expression. The (.*) in the middle will match as much as it possibly can. If you have two style blocks:</p>
<pre><code>&lt;style type=""text/css""&gt;1&lt;/style&gt; &lt;style type=""text/css""&gt;2&lt;/style&gt;
</code></pre>
<p>then it will happily match '1&lt;/style> &lt;style type=""text/css"">2'.</p>
<p>Use (.*?) to get a non-greedy expression, which will allow the trailing (&lt;/style>) to match at the first opportunity.</p>
<blockquote>
<p>Should I call the 'find' method to get the next match?</p>
</blockquote>
<p>Yes, and you should have used it to get the first match too. The usual idiom is:</p>
<pre><code>while (matcher.find()) {
s= matcher.group(n);
}
</code></pre>
<p>Note that standard string processing (indexOf, etc) may be a simpler approach for you than regex, since you're only using completely fixed strings. However, the Standard Answer still applies.</p>
","1415","8","3","1","2009-01-21 17:28:06","55","TRUE","277501","0"
"http://stackoverflow.com/users/179467","http://stackoverflow.com/questions/1907376","http://stackoverflow.com/questions/1907376/#1908248","2009-12-15 15:37:20","2","2447","2","4","Java: Turkish Encoding Mac/Windows","<p>I have a problem with turkish special characters on different machines. The following code:</p>
<pre><code>String turkish = ""ğüşçĞÜŞÇı"";
String test1 = new String(turkish.getBytes());
String test2 = new String(turkish.getBytes(""UTF-8""));
String test3 = new String(turkish.getBytes(""UTF-8""), ""UTF-8"");
System.out.println(test1);
System.out.println(test2);
System.out.println(test3);
</code></pre>
<p>On a Mac the three Strings are the same as the original string. On a Windows machine the three lines are (Printed with the Netbeans 6.7 console): </p>
<pre><code>?ü?ç?Ü?Ç?
ğüşçĞÜŞÇı
?ü?ç?Ü?Ç?
</code></pre>
<p>I don't get the problem. </p>
","34","656","<java><encoding><turkish>","2009-12-15 13:13:35","TRUE","FALSE","1908248","2009-12-15 15:37:20","10","<pre><code>String test1 = new String(turkish.getBytes());
</code></pre>
<p>You're taking the Unicode String including the Turkish characters, and turning it into bytes using the default encoding (using the default encoding is usually a mistake). You're then taking those bytes and decoding them back into a String, again using the default encoding. The result is you've achieved nothing (except losing any characters that don't fit in the default encoding); whether you have put a String through an encode/decode cycle has <em>no effect</em> on what the following <code>System.out.println(test1)</code> does because that's still printing a String and not bytes.</p>
<pre><code>String test2 = new String(turkish.getBytes(""UTF-8""));
</code></pre>
<p>Encodes as UTF-8 and then decodes using the default encoding. On Mac the default encoding is UTF-8 so this does nothing. On Windows the default encoding is never UTF-8 so the result is the wrong characters.</p>
<pre><code>String test3 = new String(turkish.getBytes(""UTF-8""), ""UTF-8"");
</code></pre>
<p>Does precisely nothing.</p>
<p>To write Strings to stdout with a different encoding than the default encoding, you'd create a encoder something like <code>new OutputStreamWriter(System.out, ""cp1252"")</code> and send the string content to that.</p>
<p>However in this case, it looks like the console is using Windows code page 1252 Western European (+1 ATorres). There is no encoding mismatch issue here at all, so you won't be able to solve it by re-encoding strings!</p>
<p>The default encoding cp1252 matches the console's encoding, it's just that cp1252 doesn't contain the Turkish characters <code>ğşĞŞı</code> at all. You can see the other characters that <em>are</em> in cp1252, <code>üçÜÇ</code>, come through just fine. Unless you can reconfigure the console to use a different encoding that does include all the characters you want, there is no way you'll be able to output those characters.</p>
<p>Presumably on a Turkish Windows install, the default code page will be cp1254 instead and you will get the characters you expect (but other characters don't work). You can test this by changing the ‘Language to use for non-Unicode applications’ setting in the Regional and Language Options Control Panel app.</p>
<p>Unfortunately no Windows locale uses UTF-8 as the default code page. Putting non-ASCII output onto the console with the stdio stream functions is not something that's really reliable at all. There is a Win32 API to write Unicode directly to the console, but unfortunately nothing much uses it.</p>
","2582","8","3","1","2009-12-15 15:37:20","144","TRUE","277501","0"
"http://stackoverflow.com/users/149080","http://stackoverflow.com/questions/3432548","http://stackoverflow.com/questions/3432548/#3432663","2010-08-08 00:51:19","1","2909","3","1","AntiSamy is allowing An encoded Script alert to get by? How to block?","<p>I'm using AntiSamy with the available antisamy-1.4.1.xml policy. The policy is working nicely to block most XSS attacked but the following below is not being blocked. Any suggestions on how to block the following below to prevent XSS attacks?</p>
<pre><code>1234%27%2Balert%2873918%29%2B%27
</code></pre>
<p>Thanks</p>
","69","324","<java><xss><policy><owasp>","2010-08-08 00:04:34","TRUE","FALSE","3432663","2010-08-08 00:51:19","12","<p>Antisamy is an HTML content filter meant for allowing an untrusted user to input a limited subset of ‘safe’ HTML. It is <strong>not</strong> an all-purpose input filter that can save you from having to think about string escaping and XSS issues.</p>
<p>You should use antisamy only to clean up content that will contain HTML that you wish to output verbatim on a page. Most user input is generally not HTML: when a user types <code>a&lt;b or c&gt;d</code>, they should usually get the literal less-than and greater-than characters and not a bold tag. To ensure this happens correctly, you must HTML-escape all text content that gets inserted into your page at the output stage, instead of anything to do with antisamy.</p>
<pre><code>1234%27%2Balert%2873918%29%2B%27
</code></pre>
<p>This looks nothing like a typical HTML injection attack. The only ‘special’ character it contains is an apostrophe, which isn't usually special in HTML, and can't practically be filtered out of input because users do generally need to use apostrophes for writing in English.</p>
<p>If this is causing script injection for your application, you've got bigger problems than anything antisamy can solve. If this is causing your page to pop up an <code>alert()</code> dialogue, you are probably using the value unescaped in a JavaScript string literal, for example something like:</p>
<pre><code>&lt;a href=""..."" onclick=""callfunc('hello &lt;%= somevar %&gt;');""&gt;
</code></pre>
<p>Putting text content into JavaScript code as a string literal requires another form of escaping; one that turns the <code>'</code> character (the <code>%27</code> in the URL-encoded input) into a backslash-escaped <code>\'</code>, and <code>\</code> itself into <code>\\</code> (as well as a few other replacements).</p>
<p>The easy way to get values (strings or otherwise) from a server-side scripting language into a JavaScript literal is to use a standard JSON encoder.</p>
<p>However, in the above case, the JavaScript string literal is itself contained inside an HTML attribute, so you would have to HTML-encode <em>the results of</em> the JSON encoder. This is a bit ugly; it's best to avoid inline event handler attributes. Use external scripts and <code>&lt;script&gt;</code> elements instead, binding events from JS instead of HTML.</p>
<p>Even in a <code>&lt;script&gt;</code> block, where you don't generally need to HTML-encode, you have to beware of a string <code>&lt;/script&gt;</code> (or, generally, anything beginning <code>&lt;/</code>, which can end the block). To avoid that sequence you should replace the <code>&lt;</code> character with something else, eg. <code>\x3C</code>. Some JSON encoders may have an option to do this for you to save the trouble.</p>
<p>There are many other places where inserting content into a containing language requires special sorts of encoding. Each has its own rules. You can't avoid the difficulty of string encoding by using a general-purpose input filter. Some “anti-XSS” filters try, but they invariably fail miserably.</p>
","3061","9","2","16","2010-08-08 00:51:19","47","TRUE","277501","0"
"http://stackoverflow.com/users/252701","http://stackoverflow.com/questions/18937325","http://stackoverflow.com/questions/18937325/#18937422","2013-09-26 19:19:41","0","116","0","3","How to properly truncate a double","<p>How to properly truncate a double in Java, so for example 1.99999999999999999 is always truncated to 1 and not rounded upto 2 as is the case in the sample below.</p>
<pre><code> double d1 = 1.999999999999999999;
double d2 = 1.0;
long i1 = (long)Math.floor(d1);
long i2 = (long)Math.floor(d2);
System.out.println(""i1=""+i1 + "" i2=""+i2); //i1 == 2
</code></pre>
<p>Running sample here: <a href=""http://www.browxy.com/SubmittedCode/42603"" rel=""nofollow"">http://www.browxy.com/SubmittedCode/42603</a></p>
<h2>Solution</h2>
<p>Use <code>BigDecimal</code> which has arbitary precision</p>
<pre><code>BigDecimal bd = new BigDecimal(""0.9999999999999999999999999999"");
bd = bd.setScale(0, BigDecimal.ROUND_DOWN); //truncate
</code></pre>
","33","756","<java><precision><truncate>","2013-09-21 20:33:13","TRUE","FALSE","18937422","2013-09-21 20:48:21","7","<p><code>1.99999999999999999</code> is not rounded up to <code>2</code>, it <em>is</em> <code>2</code>.</p>
<pre><code>System.out.println(1.999999999999999999); // 2
System.out.println(1.999999999999999999 == 2); // true
</code></pre>
<p>Floating-point numbers aren't infinitely precise. There aren't enough bits in the storage format Java uses (IEEE <code>double</code>) to distinguish between <code>1.999999999999999999</code> and <code>2</code>.</p>
<p>If you need more accuracy than that, try a different number format, such as <code>BigDecimal</code>.</p>
","569","3","1","3","2013-09-21 20:42:47","9","TRUE","277501","0"
"http://stackoverflow.com/users/385387","http://stackoverflow.com/questions/3465465","http://stackoverflow.com/questions/3465465/#3465492","2013-09-18 10:07:04","21","10746","2","7","How to use Java-style throws keyword in C#?","<p>In Java, the <a href=""http://download.oracle.com/javase/tutorial/essential/exceptions/declaring.html""><code>throws</code></a> keyword allows for a method to declare that it will not handle an exception on its own, but rather throw it to the calling method.</p>
<p>Is there a similar keyword/attribute in C#?</p>
<p>If there is no equivalent, how can you accomplish the same (or a similar) effect?</p>
","43","406","<c#><java><exception-handling><throws>","2010-08-12 07:13:33","FALSE","FALSE","3465492","2010-08-12 13:52:10","25","<p>In Java, you must either handle an exception or mark the method as one that may throw it using the <code>throws</code> keyword.</p>
<p>C# does not have this keyword or an equivalent one, as in C#, if you don't handle an exception, it will bubble up, until caught or if not caught it will terminate the program.</p>
<p>If you want to handle it then re-throw you can do the following:</p>
<pre><code>try
{
// code that throws an exception
}
catch(ArgumentNullException ex)
{
// code that handles the exception
throw;
}
</code></pre>
","543","3","1","8","2010-08-12 07:17:06","4","TRUE","276602","0"
"http://stackoverflow.com/users/1031322","http://stackoverflow.com/questions/8270321","http://stackoverflow.com/questions/8270321/#8270331","2011-12-06 10:03:37","3","179","0","6","How to translate java ""?"" operator in C#?","<p>I would like to know the translation of this java code in C#</p>
<pre><code>n = (length &gt; 0) ? Math.min(length, buffer.length) : buffer.length;//Java code
</code></pre>
<p>Can it be equivalent to this in C# ?</p>
<pre><code>if(length &gt;0)
{
n = Math.min(length, buffer.length);
}
else
{
n = buffer.length;
}
</code></pre>
","41","339","<c#><java>","2011-11-25 14:12:40","TRUE","FALSE","8270331","2011-11-25 14:18:37","18","<p>C# has the <a href=""http://msdn.microsoft.com/en-us/library/ty67wk28.aspx"">conditional operator</a> as well.</p>
<p>In C#:</p>
<pre><code>n = (length &gt; 0) ? Math.Min(length, buffer.Length) : buffer.Length;
</code></pre>
<p>The only difference would be that method names are normally capitalized in .NET (<a href=""http://c2.com/cgi/wiki?PascalCase"">PascalCase</a>, instead of <a href=""http://c2.com/cgi/wiki?CamelCase"">camelCase</a>).</p>
<p>If you are going to be working with C#, I suggest taking a look at the <a href=""http://msdn.microsoft.com/en-us/library/6a71f45d.aspx"">available operators</a>.</p>
","615","4","1","2","2011-11-25 14:13:31","1","TRUE","276602","0"
"http://stackoverflow.com/users/1326400","http://stackoverflow.com/questions/10104886","http://stackoverflow.com/questions/10104886/#10104931","2012-04-11 11:23:11","0","762","0","1","Call Java code from C#","<p>I'm stuck on one thing i can't get solved. I have part of code, which is executed from command line like a charm. Works without any problem.</p>
<p>So, i will to try to call this command (same) out from C#.</p>
<p>That's the code i'm run from commandline.</p>
<blockquote>
<p>java -Xincgc -Xmx1024m -cp
""%APPDATA%.minecraft\bin\minecraft.jar;%APPDATA%.minecraft\bin\lwjgl.jar;%APPDATA%.minecraft\bin\lwjgl_util.jar;%APPDATA%.minecraft\bin\jinput.jar""
-Djava.library.path=""%APPDATA%.minecraft\bin\natives"" net.minecraft.client.Minecraft ""NAME""</p>
</blockquote>
<p>The part i'm trying to get it in C# looks like:</p>
<pre><code>proc.StartInfo.FileName = ""java"";
proc.StartInfo.Arguments = ""-Xincgc -Xmx1024m -cp \""%APPDATA%\\.minecraft\\bin\\minecraft.jar;%APPDATA%\\.minecraft\\bin\\lwjgl.jar;%APPDATA%\\.minecraft\\bin\\lwjgl_util.jar;%APPDATA%\\.minecraft\\bin\\jinput.jar\"" -Djava.library.path=\""%APPDATA%\\.minecraft\\bin\\natives\"" net.minecraft.client.Minecraft \""NAME\"""";
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
</code></pre>
<p>But, nothing happens at all. Is there something i'm doing wrong?
Thanks for any help!</p>
","22","1297","<c#><java><class><parameters>","2012-04-11 11:20:37","TRUE","FALSE","10104931","2012-04-11 11:23:11","4","<p>Expand the environment variables in the <code>Arguments</code> using <a href=""http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx"" rel=""nofollow""><code>Environment.ExpandEnvironmentVariables</code></a>.</p>
<pre><code>string args = ""-Xincgc -Xmx1024m -cp \""%APPDATA%\\.minecraft\\bin\\minecraft.jar;%APPDATA%\\.minecraft\\bin\\lwjgl.jar;%APPDATA%\\.minecraft\\bin\\lwjgl_util.jar;%APPDATA%\\.minecraft\\bin\\jinput.jar\"" -Djava.library.path=\""%APPDATA%\\.minecraft\\bin\\natives\"" net.minecraft.client.Minecraft \""NAME\"""";
proc.StartInfo.Arguments = Environment.ExpandEnvironmentVariables(args);
</code></pre>
<p>BTW - you can use a <a href=""http://msdn.microsoft.com/en-us/library/362314fe.aspx"" rel=""nofollow"">verbatim string literal</a> to make that argument string more readable.</p>
<pre><code>@""-Xincgc -Xmx1024m -cp """"%APPDATA%\.minecraft\bin\minecraft.jar;%APPDATA%\.minecraft\bin\lwjgl.jar;%APPDATA%\.minecraft\bin\lwjgl_util.jar;%APPDATA%\.minecraft\bin\jinput.jar"""" -Djava.library.path=""""%APPDATA%\.minecraft\bin\natives"""" net.minecraft.client.Minecraft """"NAME"""""";
</code></pre>
","1135","2","2","1","2012-04-11 11:23:11","3","TRUE","276602","0"
"http://stackoverflow.com/users/776456","http://stackoverflow.com/questions/10968104","http://stackoverflow.com/questions/10968104/#10968117","2012-06-10 11:21:59","-2","192","0","4","confusion between && and || in java","<pre><code> import javax.swing.JOptionPane;
public class Insurance {
final static String INPUT_GENDER = ""Please enter your gender: (Male or Female)"";
final static String MALE = ""male"";
final static String FEMALE = ""female"";
static String gender;
public static void main(String args[])
{
do
{
gender = JOptionPane.showInputDialog(INPUT_GENDER).toLowerCase();
System.out.println(gender);
}
while(!gender.equals(MALE) &amp;&amp; !gender.equals(FEMALE));
}
}
</code></pre>
<p>The above piece of code is the beginning to a revision assignment, but I came across something I don't understand. The user is asked to enter their gender, as ""Male"" or ""Female"", and the program should only continue if the input satisfies one of these inputs. This is done by comparing the input to the final strings for MALE and FEMALE. </p>
<p>What I don't understand is why it only works using &amp;&amp; in the while statement. I expected it to need ||, because we want it to continue if the input matches either of the two gender strings. I understood that &amp;&amp; should only allow the code to continue if both arguments are true.</p>
<p>TL;DR</p>
<pre><code> while(!gender.equals(MALE) &amp;&amp; !gender.equals(FEMALE)); //This works
while(!gender.equals(MALE) || !gender.equals(FEMALE)); //This does not work
while(gender.equals(MALE) || gender.equals(FEMALE)); //This does not work
</code></pre>
","35","1497","<java>","2012-06-10 10:56:20","TRUE","FALSE","10968117","2012-06-10 11:06:49","8","<ul>
<li><p><code>&amp;&amp;</code> is a logical <code>and</code> operator</p></li>
<li><p><code>||</code> is the logical <code>or</code> operator</p></li>
</ul>
<p>Using <a href=""http://en.wikipedia.org/wiki/De_Morgan%27s_laws"" rel=""nofollow"">De Morgan</a>, the following:</p>
<pre><code>while(!gender.equals(MALE) &amp;&amp; !gender.equals(FEMALE))
</code></pre>
<p>Can be translated to:</p>
<pre><code>while(!(gender.equals(MALE) || gender.equals(FEMALE)))
</code></pre>
<p>(note the additional parenthesis and the placement of the <code>!</code> before them).</p>
<p>Both the above mean that the <code>gender</code> is neither <code>MALE</code> or <code>FEMALE</code>.</p>
<p>Your other code:</p>
<pre><code>while(!gender.equals(MALE) || !gender.equals(FEMALE))
</code></pre>
<p>The above means - <code>gender</code> is not <code>MALE</code> <em>or</em> <code>gender</code> is not <code>FEMALE</code>.</p>
<pre><code>while(gender.equals(MALE) || gender.equals(FEMALE));
</code></pre>
<p>Similarly, the above means - <code>gender</code> is <code>MALE</code> <em>or</em> <code>gender</code> is <code>FEMALE</code>.</p>
","1134","9","4","4","2012-06-10 10:58:11","2","TRUE","276602","0"
"http://stackoverflow.com/users/106281","http://stackoverflow.com/questions/1293355","http://stackoverflow.com/questions/1293355/#1293394","2013-05-24 13:30:37","6","8613","1","3","How to wait for a Java applet to finish loading on Safari?","<p>This doesn't work in Safari:</p>
<pre><code>&lt;html&gt;
&lt;body&gt;
&lt;applet id=""MyApplet"" code=""MyAppletClass"" archive=""MyApplet.jar""&gt;
&lt;script type=""text/javascript""&gt;
alert(document.getElementById('MyApplet').myMethod);
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p><code>myMethod</code> is a public method declared in <code>MyAppletClass</code>.</p>
<p>When I first load the page in Safari, it shows the alert before the applet has finished loading (so the message box displays <code>undefined</code>) . If I refresh the page, the applet has already been loaded and the alert displays <code>function myMethod() { [native code] }</code>, as you'd expect.</p>
<p>Of course, this means that the applet methods are not available until it has loaded, but Safari isn't blocking the JavaScript from running. The same problem happens with <code>&lt;body onLoad&gt;</code>.</p>
<p>What I need is something like <code>&lt;body onAppletLoad=""doSomething()""&gt;</code>. How do I work around this issue?</p>
<p>Thanks</p>
<p>PS: I'm not sure if it's relevant, but the JAR is signed.</p>
","58","1117","<java><javascript><javascript-events><safari>","2009-08-18 11:45:55","TRUE","FALSE","1293394","2013-05-24 13:30:37","8","<p>I use a timer that resets and keeps checking a number of times before it gives up.</p>
<pre><code>&lt;script language=""text/javascript"" defer&gt;
function performAppletCode(count) {
var applet = document.getElementById('MyApplet');
if (!applet.myMethod &amp;&amp; count &gt; 0) {
setTimeout( function() { performAppletCode( --count ); }, 2000 );
}
else if (applet.myMethod) {
// use the applet for something
}
else {
alert( 'applet failed to load' );
}
}
performAppletCode( 10 );
&lt;/script&gt;
</code></pre>
<p>Note that this assumes that the applet will run in Safari. I've had some instances where an applet required Java 6 that simply hangs Safari even with code similar to the above. I chose to do browser detection on the server and redirect the user to an error page when the browser doesn't support the applet.</p>
","901","2","1","2","2009-08-18 11:56:14","11","TRUE","275271","2"
"http://stackoverflow.com/users/19825","http://stackoverflow.com/questions/405826","http://stackoverflow.com/questions/405826/#405840","2009-01-02 03:20:56","4","1031","0","4","Quick Java Question: Instantiating a given class only from another?","<p>My problem is thus: I need a way to ensure only one given class can instantiate another. I don't want to have to make the other a nested inner class or something dumb like that. How do I do this? I forget offhand.</p>
","67","224","<java><class><instantiation>","2009-01-02 01:37:36","FALSE","FALSE","405840","2009-01-02 03:20:56","1","<p>Make the constructor private. Create a static factory method that takes an instance of the class that is allowed access. Have the factory method create a suitable object and use a settor on the object that is allowed access to the created object to give that class the created copy.</p>
<pre><code>public class AllowedAccess
{
private SecureClass secure;
public setSecureClass( SecureClass secure )
{
this.secure = secure;
}
...
}
public class SecureClass
{
private SecureClass() {}
public static void Create( AllowedAccess allowed )
{
allowed.setSecureClass( new SecureClass() );
}
...
}
</code></pre>
<p>BTW, I'm suspicious of this design. Seems too highly coupled to me.</p>
","753","2","1","5","2009-01-02 01:48:38","11","TRUE","275271","0"
"http://stackoverflow.com/users/175338","http://stackoverflow.com/questions/2165711","http://stackoverflow.com/questions/2165711/#2165790","2010-01-29 23:24:34","1","158","0","1","Accordion and jQueryCycle prevent href's from working","<p>Checkout <a href=""http://sensenich.bythepixel.com/"" rel=""nofollow"">this site</a> that I'm working on. </p>
<p>The idea is as follows:</p>
<p>-That the slide show is supposed to rotate - this works</p>
<p>-When hovering over the menu on the right the appropriate slide appears - this works</p>
<p>-Also when hovering the nav should expand to show a brief description - this works</p>
<p>-When clicking on Airboat, Aircraft, UAV, or the ""view"" link it then takes you to that page - this doesn't work. I'm sure what's happening here is that the javascripts are fighting it out, as disabling one makes the links work, reenabling breaks it.</p>
<p>Your help is greatly appreciated,</p>
","53","692","<java><html><accordion><jquery-cycle>","2010-01-29 22:40:38","FALSE","FALSE","2165790","2010-01-29 23:24:34","1","<p>Try using this:</p>
<pre><code> return '#nav li:eq(' + (idx) + ') &gt; a';}
</code></pre>
<p>instead of</p>
<pre><code>return '#nav li:eq(' + (idx) + ') a';}
</code></pre>
<p>in your cycle plugin. Using the direct descendent selector instead of the descendent selector will keep it from matching on the links contained in the accordion for the page anchors.</p>
","370","3","2","5","2010-01-29 22:54:32","14","TRUE","275271","0"
"http://stackoverflow.com/users/478197","http://stackoverflow.com/questions/11071967","http://stackoverflow.com/questions/11071967/#11071994","2012-06-17 14:31:16","0","111","0","1","JUnit Testing - What am I doing Wrong","<p>I am very new to JUnit testing, I am trying to test the following very simple class</p>
<pre><code>public interface IItemsService extends IService {
public final String NAME = ""IItemsService"";
/** Places items into the database
* @return
* @throws ItemNotStoredException
*/
public boolean storeItem(Items items) throws ItemNotStoredException;
/** Retrieves items from the database
*
* @param category
* @param amount
* @param color
* @param type
* @return
* @throws ItemNotFoundException
*/
public Items getItems (String category, float amount, String color, String type) throws ItemNotFoundException;
}
</code></pre>
<p>This is what I have for the test but I keep getting null pointer, and another error about it not being applicable for the argument... obviously I am doing something stupid but I am not seeing it. Could someone point me in the right direction?</p>
<pre><code>public class ItemsServiceTest extends TestCase {
/**
* @throws java.lang.Exception
*/
private Items items;
private IItemsService itemSrvc;
protected void setUp() throws Exception {
super.setUp();
items = new Items (""red"", 15, ""pens"", ""gel"");
}
IItemsService itemsService;
@Test
public void testStore() throws ItemNotStoredException {
try {
Assert.assertTrue(itemSrvc.storeItem(items));
} catch (ItemNotStoredException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println (""Item not stored"");
}
}
@Test
public void testGet() throws ItemNotStoredException {
try {
Assert.assertFalse(itemSrvc.getItems(getName(), 0, getName(), getName()));
} catch (ItemNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre>
","37","2018","<java><junit>","2012-06-17 14:17:37","TRUE","FALSE","11071994","2012-06-17 14:31:16","6","<p>You're not creating an instance of the class under test, you're only declaring it as the interface. In each of your tests you should create an instance of the class under test and test it's implementation of the method. Note also, your tests should not be dependent on one another. You shouldn't rely on them running in particular order; any set up for a test should be done in the test set up method, not by another test.</p>
<p>Generally you want to use the AAA (Arrange, Act, Assert) pattern in your tests. The setUp (arrange) and tearDown (assert) can be part of this, but the pattern should also be reflected in each test method.</p>
<pre><code>@Test
public void testStore() throws ItemNotStoredException {
// Arrange
ISomeDependency serviceDependency = // create a mock dependency
IItemsService itemSvc = new ItemsService(someDependency);
// Act
bool result = itemSrvc.storeItem(items);
// Assert
Assert.assertTrue(result);
// assert that your dependency was used properly if appropriate
}
</code></pre>
","1053","2","1","2","2012-06-17 14:22:33","5","TRUE","275271","0"
"http://stackoverflow.com/users/2016689","http://stackoverflow.com/questions/14554276","http://stackoverflow.com/questions/14554276/#14554316","2013-01-28 01:36:31","-1","35","0","1","Checking if a method is set","<p>""a fourth field to keep track of whether or not the alarm is set; alternatively, you could set the alarm fields to a negative value (-1 is my favorite)."" Please help, I am trying to create a field which checks if my method is set. I've tried an if and statement so far but it probably is not the way to go. I need to check that my alarm is set. Probably going to need a return value then right?</p>
<pre><code>public void setAlarm (int hours, int minutes, int seconds)
{
if(hours minutes seconds &gt; 0) {
alarmHour = hours;
alarmMinute = minutes;
alarmSecond = seconds;
}
else {
System.out.println(""Please set the alarm."");
}
}
</code></pre>
","27","695","<java>","2013-01-28 01:30:52","TRUE","FALSE","14554316","2013-01-28 01:36:31","2","<p>I believe this is what is intended.</p>
<pre><code>private boolean isSet;
public boolean isAlarmSet()
{
return isSet;
}
public void setAlarm (int hours, int minutes, int seconds)
{
alarmHour = hours;
alarmMinute = minutes;
alarmSecond = seconds;
isSet = true;
}
</code></pre>
","302","1","1","13","2013-01-28 01:36:31","6","TRUE","275271","0"
"http://stackoverflow.com/users/191995","http://stackoverflow.com/questions/5483047","http://stackoverflow.com/questions/5483047/#5483105","2014-02-12 20:21:57","71","10346","27","6","Why is creating a Thread said to be expensive?","<p>The Java tutorials say that creating a Thread is expensive. But why exactly is it expensive? What exactly is happening when a Java Thread is created that makes its creation expensive? I'm taking the statement as true, but I'm just interested in mechanics of Thread creation in JVM. </p>
<blockquote>
<p>Thread lifecycle overhead. Thread creation and teardown are not free. The actual overhead varies across platforms, but thread creation takes time, introducing latency into request processing, and requires some processing activity by the JVM and OS. If requests are frequent and lightweight, as in most server applications, creating a new thread for each request can consume significant computing resources.</p>
</blockquote>
<p>From <em>Java Concurrency in Practice</em><br>
By Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea<br>
Print ISBN-10: 0-321-34960-1</p>
","46","904","<java><multithreading><performance><concurrency>","2011-03-30 07:08:34","FALSE","FALSE","5483105","2013-12-05 02:55:45","70","<p>Java thread creation is expensive because there is a fair bit of work involved:</p>
<ul>
<li>A large block of memory has to be allocated and initialized for the thread stack.</li>
<li>System calls need to be made to create / register the native thread with the host OS.</li>
<li>Descriptors needs to be created, initialized and added to JVM internal data structures.</li>
</ul>
<p>It is also expensive in the sense that the thread ties down resources as long as it is alive; e.g. the thread stack, any objects reachable from the stack, the JVM thread descriptors, the OS native thread descriptors.</p>
<p>All these things are platform specific, but they are not cheap on any Java platform I've ever come across.</p>
<hr>
<p>A Google search found me an <a href=""http://www.mail-archive.com/java-linux@java.blackdown.org/msg15146.html"">old benchmark</a> that reports a thread creation rate of ~4000 per second on a Sun Java 1.4.1 on a 2002 vintage dual processor Xeon running 2002 vintage Linux. A more modern platform will give better numbers ... and I can't comment on the methodology ... but at least it gives a ballpark for <em>how expensive</em> thread creation is likely to be.</p>
<p>Peter Lawrey's benchmarking indicates that thread creation is significantly faster these days in absolute terms, but it is unclear how much of this is due improvements in Java and/or the OS ... or faster processor speeds. But his numbers <em>still</em> indicate a 150+ fold improvement if you use a thread pool versus creating/starting a new thread each time. (And he makes the point that this is all relative ...)</p>
<hr>
<p>(The above assumes ""native threads"" rather than ""green threads"", but modern JVMs all use native threads for performance reasons. Green threads are possibly cheaper to create, but you pay for it in other areas.)</p>
<hr>
<p>I've done a bit of digging to see how a Java thread's stack really gets allocated. In the case of OpenJDK 6 on Linux, the thread stack is allocated by the call to <code>pthread_create</code> that creates the native thread. (The JVM does not pass <code>pthread_create</code> a preallocated stack.)</p>
<p>Then, within <code>pthread_create</code> the stack is allocated by a call to <code>mmap</code> as follows:</p>
<pre><code>mmap(0, attr.__stacksize,
PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
</code></pre>
<p>According to <code>man mmap</code>, the <code>MAP_ANONYMOUS</code> flag causes the memory to be initialized to zero.</p>
<p>Thus, even though it might not be essential that new Java thread stacks are zeroed (per the JVM spec), in practice (at least with OpenJDK 6 on Linux) they are zeroed.</p>
","2704","10","1","12","2011-03-30 07:16:00","8","TRUE","267012","0"
"http://stackoverflow.com/users/440336","http://stackoverflow.com/questions/5387643","http://stackoverflow.com/questions/5387643/#5387693","2014-08-21 17:38:20","67","113107","19","4","Array initialization syntax when not in a declaration","<p>Simple question that has been bugging me since I learned how to play with arrays in Java</p>
<p>I can write:</p>
<pre><code>AClass[] array = {object1, object2}
</code></pre>
<p>I can also write: </p>
<pre><code>AClass[] array = new AClass[2];
...
array[0] = object1;
array[1] = object2;
</code></pre>
<p>but I can't write : </p>
<pre><code>AClass[] array;
...
array = {object1,object2};
</code></pre>
<p><strong>And I would like to know why this is blocked by java.</strong></p>
<p>I know how to work around it but form time to time it would be simpler</p>
<p>for example: </p>
<pre><code>public void selectedPointsToMove(cpVect coord){
if(tab == null){
if(arePointsClose(coord, point1, 10)){
cpVect[] tempTab = {point1};
tab = tempTab;
}else if(arePointsClose(point2, coord, 10)){
cpVect[] tempTab = {point2};
tab = tempTab;
}else{
cpVect[] tempTab = {point1,point2};
tab = tempTab;
}
}
}
</code></pre>
","53","1081","<java><arrays>","2011-03-22 06:32:07","TRUE","FALSE","5387693","2011-03-22 06:46:03","66","<blockquote>
<p>And I would like to know why this is blocked by java.</p>
</blockquote>
<p>You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.</p>
<p>But ""why"" is immaterial ... the restriction is there, and you have to live with it.</p>
<blockquote>
<p>I know how to work around it but form time to time it would be simpler</p>
</blockquote>
<p>You can write this:</p>
<pre><code>AClass[] array;
...
array = new AClass[]{object1, object2};
</code></pre>
","641","5","1","2","2011-03-22 06:40:30","8","TRUE","267012","0"
"http://stackoverflow.com/users/710818","http://stackoverflow.com/questions/11211286","http://stackoverflow.com/questions/11211286/#11211334","2014-08-17 12:03:07","42","20999","4","6","Is it possible in Java to catch two exceptions in the same catch block?","<p>I need to catch two exceptions because they require the same handling logic. I would like to do something like:</p>
<pre><code>catch (Exception e, ExtendsRuntimeException re) {
// common logic to handle both exceptions
}
</code></pre>
<p>Is it possible to avoid duplicating the handler code in each catch block?</p>
","71","325","<java><exception-handling><try-catch>","2012-06-26 15:56:50","TRUE","FALSE","11211334","2014-08-17 12:03:07","78","<h2>Java 7 and later</h2>
<p><a href=""http://www.oracle.com/technetwork/articles/java/java7exceptions-486908.html"" rel=""nofollow"">Multiple-exception catches</a> are supported, starting in Java 7.</p>
<p>The syntax is:</p>
<pre><code>try {
// stuff
} catch (Exception1 | Exception2 ex) {
// Handle both exceptions
}
</code></pre>
<p>The static type of <code>ex</code> is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow <code>ex</code> in the catch, the compiler knows that only one of the listed exceptions can be thrown.</p>
<hr>
<h2>Java 6 and earlier</h2>
<p>Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.</p>
<h2>Approach #1</h2>
<pre><code>try {
// stuff
} catch (Exception1 ex) {
handleException(ex);
} catch (Exception2 ex) {
handleException(ex);
}
public void handleException(SuperException ex) {
// handle exception here
}
</code></pre>
<p>This gets messy if the exception handler needs to access local variables declared before the <code>try</code>. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, <code>handleException</code> has to be declared as throwing <code>SuperException</code> ... which potentially means you have to change the signature of the enclosing method, and so on.</p>
<h2>Approach #2</h2>
<pre><code>try {
// stuff
} catch (SuperException ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
// handle exception
} else {
throw ex;
}
}
</code></pre>
<p>Once again, we have a potential problem with signatures. </p>
<h2>Approach #3</h2>
<pre><code>try {
// stuff
} catch (SuperException ex) {
if (ex instanceof Exception1 || ex instanceof Exception2) {
// handle exception
}
}
</code></pre>
<p>If you leave out the <code>else</code> part (e.g. because there are no other subtypes of <code>SuperException</code> at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an <code>else</code> may end up silently eating exceptions!</p>
","2262","7","4","6","2012-06-26 15:58:45","2","TRUE","267012","6"
"http://stackoverflow.com/users/5849","http://stackoverflow.com/questions/1583940","http://stackoverflow.com/questions/1583940/#1583968","2014-09-26 13:56:51","22","38660","1","6","up to first N characters","<p>How do I get up to the first n characters of a string in java without doing a size check first(inline is acceptable) or risking an <code>IndexOutOfBoundsException</code>?</p>
","24","178","<java><string>","2009-10-18 03:43:23","FALSE","FALSE","1583968","2012-05-08 03:03:14","83","<p>Here's a neat solution:</p>
<pre><code>String upToNCharacters = s.substring(0, Math.min(s.length(), n));
</code></pre>
<hr>
<p><sup>Opinion: while this solution is ""neat"", I think it is actually <em>less readable</em> than a solution that uses <code>if</code> / <code>else</code> in the obvious way. If the reader hasn't seen this trick, he/she has to <em>think harder</em> to understand the code. IMO, the code's meaning is more obvious in the <code>if</code> / <code>else</code> version.</sup></p>
","508","2","1","9","2009-10-18 04:00:37","17","TRUE","267012","0"
"http://stackoverflow.com/users/2644","http://stackoverflow.com/questions/315846","http://stackoverflow.com/questions/315846/#315853","2011-09-10 03:31:38","59","14554","15","2","Why null cast?","<p>I saw this piece of code somewhere and wondered: when and why would somebody do the following:</p>
<pre><code>doSomething( (MyClass) null );
</code></pre>
<p>Have you ever done this? Could you please share your experience?</p>
","14","232","<java><null>","2008-11-24 23:16:42","TRUE","FALSE","315853","2008-11-25 17:36:07","108","<p>If <code>doSomething</code> is overloaded, you need to cast the null explicitly to <code>MyClass</code> so the right overload is chosen:</p>
<pre><code>public void doSomething(MyClass c) {
// ...
}
public void doSomething(MyOtherClass c) {
// ...
}
</code></pre>
<p>A non-contrived situation where you need to cast is when you call a varargs function:</p>
<pre><code>class Example {
static void test(String code, String... s) {
System.out.println(""code: "" + code);
if(s == null) {
System.out.println(""array is null"");
return;
}
for(String str: s) {
if(str != null) {
System.out.println(str);
} else {
System.out.println(""element is null"");
}
}
System.out.println(""---"");
}
public static void main(String... args) {
/* the array will contain two elements */
test(""numbers"", ""one"", ""two"");
/* the array will contain zero elements */
test(""nothing"");
/* the array will be null in test */
test(""null-array"", (String[])null);
/* first argument of the array is null */
test(""one-null-element"", (String)null);
/* will produce a warning. passes a null array */
test(""warning"", null);
}
}
</code></pre>
<p>The last line will produce the following warning:</p>
<blockquote>
<p>Example.java:26: warning: non-varargs
call of varargs method with inexact
argument type for last parameter;<br />
cast to <code>java.lang.String</code> for a varargs
call<br />cast to <code>java.lang.String[]</code> for a
non-varargs call and to suppress this
warning</p>
</blockquote>
","1723","4","2","3","2008-11-24 23:19:37","3","TRUE","261962","0"
"http://stackoverflow.com/users/43756","http://stackoverflow.com/questions/467815","http://stackoverflow.com/questions/467815/#467830","2014-05-05 19:59:05","10","10737","4","5","Class method and variable with same name, compile error in C++ not in Java?","<pre><code>class Test {
bool isVal() const {
return isVal;
}
private:
bool isVal;
};
</code></pre>
<p>On Compiling this file it says </p>
<blockquote>
<p>testClass.cpp:9: declaration of `bool
Test::isVal'</p>
<p>testClass.cpp:3: conflicts with
previous declaration `bool
Test::isVal()'</p>
</blockquote>
<p>Although the same would work for java </p>
<pre><code>class Test {
private boolean isVal;
public boolean isVal() {
return isVal;
}
}
</code></pre>
<p>Not sure why C++ cannot handle this.</p>
","75","564","<java><c++><compiler-construction>","2009-01-22 02:01:32","TRUE","FALSE","467830","2014-05-05 19:59:05","29","<p>Because C++ is not Java. You can take the address of a member:</p>
<pre><code>&amp;Test::isVal
</code></pre>
<p>So you can't have two members have the same name, except that you can overload member functions. Even if you could disambiguate that by some kind of cast, the next problem would already arise at other places. </p>
<p>In C++, a lot of people including me usually call data members specially, like putting a <code>m</code> before their name. This avoids the problem:</p>
<pre><code>class Test {
public:
bool IsVal() const { return mIsVal; }
private:
bool mIsVal;
};
</code></pre>
","605","3","2","12","2009-01-22 02:07:27","6","TRUE","261962","0"
"http://stackoverflow.com/users/5303","http://stackoverflow.com/questions/314800","http://stackoverflow.com/questions/314800/#314809","2008-11-24 18:29:49","10","7542","1","7","Best way to define true, false, unset state","<p>If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.</p>
<p>What's the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?</p>
","43","444","<java><boolean>","2008-11-24 17:11:18","FALSE","FALSE","314809","2008-11-24 17:36:52","19","<pre><code>Boolean a = true;
Boolean b = false;
Boolean c = null;
</code></pre>
<p>I would use that. It's the most straight-forward.</p>
<p>Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:</p>
<pre><code>public enum ThreeState {
TRUE,
FALSE,
TRALSE
};
</code></pre>
<p>There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass <code>true</code> and <code>false</code>. If you don't like the <code>null</code>, since it's telling rather little about its meaning here, you can still make a <code>public static final Boolean tralse = null;</code> in your class.</p>
","710","3","2","6","2008-11-24 17:13:12","2","TRUE","261962","0"
"http://stackoverflow.com/users/36253","http://stackoverflow.com/questions/339245","http://stackoverflow.com/questions/339245/#339285","2009-05-03 04:53:07","6","16073","1","4","Two questions on inner classes in Java (class A { class B { } })","<p>Sorry for the bad title, but I couldn't think of a better one.</p>
<p>I'm having a class A and a class B which is kind of a sub class of A, like so:</p>
<p>(Is there actually a correct name for it? Isn't ""sub class"" reserved for inheritance?)</p>
<pre><code>class A {
int i = 0;
class B {
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
B b = a.new B();
A c = ??? b ??? // get ""a"" back
}
}
</code></pre>
<p>From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick.</p>
<p>Second one:</p>
<pre><code>class A {
void print() {
System.out.println(""This is class A."");
}
class B {
void print() {
// &lt;--- How to access print() of class A (like this.A.print() or smth)?
System.out.println(""This is class B."");
}
}
}
</code></pre>
<p>You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far.</p>
<p>Thanks in advance. :)</p>
","64","1263","<java><class>","2008-12-04 00:31:34","TRUE","FALSE","339285","2008-12-04 14:33:05","20","<p>There doesn't seem to be a way to access the outer class from outside. But you can do it like this:</p>
<pre><code>class A {
int i = 0;
class B {
final A outer = A.this;
int j = 1;
}
}
class Test {
public static void main() {
A a = new A();
A.B b = a.new B();
A c = b.outer // get ""a"" back
}
}
</code></pre>
<p><code>ClassName.this</code> will be the instance of the outerclass associated with the instance of an inner class.</p>
","496","2","1","9","2008-12-04 00:50:10","19","TRUE","261962","0"
"http://stackoverflow.com/users/24545","http://stackoverflow.com/questions/465953","http://stackoverflow.com/questions/465953/#466036","2013-02-20 20:59:19","6","3491","3","16","Throwing exceptions to control flow - code smell?","<p>Consider this code (Java, specifically):</p>
<pre><code>public int doSomething()
{
doA();
try {
doB();
} catch (MyException e) {
return ERROR;
}
doC();
return SUCCESS;
}
</code></pre>
<p>Where <code>doB()</code> is defined as:</p>
<pre><code>private void doB() throws MyException
</code></pre>
<p>Basically, <code>MyException</code> exists only in case <code>doB()</code> meets some condition (which is not catastrophic, but does need to somehow raise this condition) so that <code>doSomething()</code> will know to exit with an error.</p>
<p>Do you find the use of an exception, in this case to control flow, acceptable? Or is this a code smell? If so, how would you refactor this?</p>
","49","737","<java><design><exception-handling>","2009-01-21 16:26:55","TRUE","FALSE","466036","2009-01-21 16:59:08","10","<p>It entirely depends on what that error condition is, and what the method's job is. If returning <code>ERROR</code> is a valid way of handling that error for the calling function, why would it be bad? </p>
<p>Often, however, it <em>is</em> a smell. Consider this:</p>
<pre><code>bool isDouble(string someString) {
try {
double d = Convert.ParseInt32(someString);
} catch(FormatException e) {
return false;
}
return true;
}
</code></pre>
<p>That is a very big code smell, because you don't expect a double value. You just want to know whether a string contains a double. </p>
<p>Sometimes, the framework you use doesn't have other ways of doing what you want. For the above, there is a better way:</p>
<pre><code>bool isDouble(string someString) {
bool success;
Convert.TryParseInt32(someString, ref success);
return success;
}
</code></pre>
<p>That kind of exceptions have a special name, coined by some dude whose blog i read recently. But sadly, i forgot its name. Please comment if you know it. Last but not least, the above is pseudo code. I'm not a c# developer so the above doesn't compile, I'm sure, but TryParseInt32 / ParseInt32 demonstrates that well i think so i'm going with C#.</p>
<p>Now, to your code. Let's inspect two functions. One smells, and the other doesn't:</p>
<h3>1. Smell</h3>
<pre><code>public int setupSystem() {
doA();
try { doB(); }
catch (MyException e)
{ return ERROR; }
doC();
return SUCCESS;
}
</code></pre>
<p>That's a <em>code smell</em>, because when you want to setup a system, you don't want it to fail. Failing to setup a system means you can't continue without handling that error. </p>
<h3>2. Ok</h3>
<pre><code>public int pingWorkstation() {
doA();
try { doB(); }
catch (MyException e)
{ return ERROR; }
doC();
return SUCCESS;
}
</code></pre>
<p>That is ok, because the purpose of that method is to test whether the workstation is still reachable. If it's not, then that is part of the result of that method, and not an exceptional case that needs an alternative return path.</p>
","2136","8","4","4","2009-01-21 16:44:42","18","TRUE","261962","0"
"http://stackoverflow.com/users/49018","http://stackoverflow.com/questions/395816","http://stackoverflow.com/questions/395816/#395823","2013-01-15 06:00:35","5","4609","0","8","Function pointers/delegates in Java?","<p>For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function. Is there a way of doing this without using a switch?</p>
","36","233","<java><delegates><function-pointers>","2008-12-28 04:22:21","FALSE","FALSE","395823","2008-12-28 04:36:30","12","<p>What about this one?</p>
<pre><code>HashMap&lt;Integer, Runnable&gt; map = new HashMap&lt;Integer, Runnable&gt;();
map.put(Register.ID, new Runnable() {
public void run() { functionA(); }
});
map.put(NotifyMessage.ID, new Runnable() {
public void run() { functionB(); }
});
// ...
map.get(id).run();
</code></pre>
<p>(If you need to pass some arguments, define your own interface with a function having a suitable parameter, and use that instead of Runnable).</p>
","479","2","1","6","2008-12-28 04:30:39","8","TRUE","261962","0"
"http://stackoverflow.com/users/234712","http://stackoverflow.com/questions/2709852","http://stackoverflow.com/questions/2709852/#2709861","2013-02-13 13:17:25","0","146","0","3","Why is false being returned in this function","<p>In my program below, I set the variable <code>th</code> as <code>true</code> in the second <code>if</code> statement.
I'm curious why it later returns as <code>false</code>.</p>
<pre><code>public boolean nodeExist(TreeNode Tree, T value){
boolean th = false;
if(Tree.getValue()!= null){
if(value == Tree.getValue()){
th = true;
}else{
if(value.compareTo((T) Tree.getValue()) &lt; 0){
nodeExist(Tree.getLeft(), value);
}else{
nodeExist(Tree.getRight(), value);
}
}
}else{
th = false;
}
return th;
}
</code></pre>
","44","663","<java>","2010-04-25 20:29:55","TRUE","FALSE","2709861","2013-02-13 13:17:25","5","<p>You probably look at a recursive call which sets <code>th</code> to true. But when that call returns to its caller, <em>that</em> <code>th</code> is still at false, and that's then returned. You need to assign the recursive callee's result:</p>
<pre><code> if(value.compareTo((T) Tree.getValue()) &lt; 0){
th = nodeExist(Tree.getLeft(), value);
}else{
th = nodeExist(Tree.getRight(), value);
}
</code></pre>
","462","1","1","2","2010-04-25 20:32:47","3","TRUE","261962","0"
"http://stackoverflow.com/users/1776310","http://stackoverflow.com/questions/13786607","http://stackoverflow.com/questions/13786607/#13787629","2014-07-23 07:52:40","84","37586","22","1","Normalization in DOM parsing with java - how does it work?","<p>I saw the line below in code for a DOM parser at <a href=""http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/"">this tutorial</a>.</p>
<pre><code>doc.getDocumentElement().normalize();
</code></pre>
<p>Why do we do this normalization ?<br>
I read the <a href=""http://docs.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html#normalize%28%29"">docs</a> but I could not understand a word.</p>
<blockquote>
<p>Puts all Text nodes in the full depth of the sub-tree underneath this Node</p>
</blockquote>
<p>Okay, then can someone show me (preferably with a picture) what this tree looks like ?</p>
<p>Can anyone explain me why normalization is needed?<br>
What happens if we don't normalize ?</p>
","58","714","<java><xml><computer-science>","2012-12-09 10:21:52","TRUE","FALSE","13787629","2013-05-14 09:31:20","150","<p>The rest of the sentence is:</p>
<blockquote>
<p>where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.</p>
</blockquote>
<p>This basically means that the following XML element</p>
<pre><code>&lt;foo&gt;hello
wor
ld&lt;/foo&gt;
</code></pre>
<p>could be represented like this in a denormalized node:</p>
<pre><code>Element foo
Text node: """"
Text node: ""Hello ""
Text node: ""wor""
Text node: ""ld""
</code></pre>
<p>When normalized, the node will look like this</p>
<pre><code>Element foo
Text node: ""Hello world""
</code></pre>
<p>And the same goes for attributes: <code>&lt;foo bar=""Hello world""/&gt;</code>, comments, etc.</p>
","803","6","3","5","2012-12-09 13:07:41","166","TRUE","260223","0"
"http://stackoverflow.com/users/500774","http://stackoverflow.com/questions/5003285","http://stackoverflow.com/questions/5003285/#5003384","2013-11-05 21:49:13","36","24654","12","9","How can interfaces replace the need for multiple inheritance when have existing classes","<p>First of all... Sorry for this post. I know that there are many many posts on stackoverflow which are discussing multiple inheritance. But I already know that Java does not support multiple inheritance and I know that using interfaces should be an alternative. But I don't get it and see my dilemma:</p>
<p>I have to make changes on a very very large and complex tool written in Java. In this tool there is a data structure built with many different class objects with a linked member hierarchy. Anyway...</p>
<ul>
<li>I have one class <code>Tagged</code> which has multiple methods and returns an object tag depending on the object's class. It needs members and static variables.</li>
<li>And a second class called <code>XMLElement</code> allows to link objects and in the end generate a XML file. I also need member and static variables here.</li>
<li>Finally, I have these many many data classes which nearly all should extend <code>XMLElement</code> and some of them <code>Tagged</code>.</li>
</ul>
<p>Ok ok, this won't work since it's only possible to extend just one class. I read very often that everything with Java is ok and there is no need for having multiple inheritance. I believe, but I don't see how an interface should replace inheritance. </p>
<ol>
<li>It makes no sense to put the real implementation in all data classes since it is the same every time but this would be necessary with interfaces (I think). </li>
<li>I don't see how I could change one of my inheritance classes to an interface. I have variables in here and they have to be exactly there.</li>
</ol>
<p>I really don't get it so please can somebody explain me how to handle this?</p>
","87","1676","<java><inheritance><interface><multiple-inheritance>","2011-02-15 11:51:55","FALSE","FALSE","5003384","2012-12-05 16:38:06","49","<p>You should probably favor composition (and delegation) over inheritance :</p>
<pre><code>public interface TaggedInterface {
void foo();
}
public interface XMLElementInterface {
void bar();
}
public class Tagged implements TaggedInterface {
// ...
}
public class XMLElement implements XMLElementInterface {
// ...
}
public class TaggedXmlElement implements TaggedInterface, XMLElementInterface {
private TaggedInterface tagged;
private XMLElementInterface xmlElement;
public TaggedXmlElement(TaggedInterface tagged, XMLElementInterface xmlElement) {
this.tagged = tagged;
this.xmlElement = xmlElement;
}
public void foo() {
this.tagged.foo();
}
public void bar() {
this.xmlElement.bar();
}
public static void main(String[] args) {
TaggedXmlElement t = new TaggedXmlElement(new Tagged(), new XMLElement());
t.foo();
t.bar();
}
}
</code></pre>
","965","1","1","2","2011-02-15 12:02:22","11","TRUE","260223","0"
"http://stackoverflow.com/users/2104910","http://stackoverflow.com/questions/15054086","http://stackoverflow.com/questions/15054086/#15054186","2014-09-03 18:41:16","31","9964","5","5","What does ""atomic"" mean in programming?","<p>In the Effective Java book, it states: </p>
<blockquote>
<p>The language specification guarantees that reading or writing a
variable is atomic unless the variable is of type <code>long</code> or <code>double</code> [JLS,
17.4.7].</p>
</blockquote>
<p>What does ""atomic"" in the context of Java programming, or programming in general?</p>
","39","348","<java><atomic>","2013-02-24 16:57:37","FALSE","FALSE","15054186","2013-02-24 17:15:00","43","<p>Here's an example, because an example is often clearer than a long explanation. Suppose <code>foo</code> is a variable of type <code>long</code>. The following operation is not an atomic operation:</p>
<pre><code>foo = 65465498L;
</code></pre>
<p>Indeed, the variable is written using two separate operations: one that writes the first 32 bits, and a second one which writes the last 32 bits. That means that another thread might read the value of <code>foo</code>, and see the intermediate state. Making the operation atomic consists in using synchronization mechanisms in order to make sure that the operation is seen, from any other thread, as a single, atomic (i.e. not splittable in parts), operation. That means that any other thread, once the operation is made atomic, will either see the value of <code>foo</code> before the assignment, or after the assignment. But never the intermediate value.</p>
<p>A simple way of doing this is to make the variable volatile:</p>
<pre><code>private volatile long foo;
</code></pre>
<p>Or to synchronize every access to the variable:</p>
<pre><code>public synchronized void setFoo(long value) {
this.foo = value;
}
public synchronized void getFoo() {
return this.foo;
}
// no other use of foo outside of these two methods, unless also synchronized
</code></pre>
<p>Or to replace it with an AtomicLong:</p>
<pre><code>private AtomicLong foo;
</code></pre>
","1420","5","4","3","2013-02-24 17:07:55","10","TRUE","260223","0"
"http://stackoverflow.com/users/26943","http://stackoverflow.com/questions/11758982","http://stackoverflow.com/questions/11758982/#11759056","2014-09-24 00:17:46","21","5845","5","3","How to get max() element from List in Guava","<p>Let's say we have a Collection of Items:</p>
<pre><code>class Item {
public String title;
public int price;
}
List&lt;Item&gt; list = getListOfItems();
</code></pre>
<p>I would like to get an Item with a maximum price out of that list with Guava library (with <a href=""http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Ordering.html"" rel=""nofollow"">Ordering</a>, I presume). I mean something similar to this Groovy code: </p>
<pre><code>list.max{it.price}
</code></pre>
<p>How do I do that? How efficient is it?</p>
","43","563","<java><guava>","2012-08-01 12:15:21","TRUE","FALSE","11759056","2014-09-24 00:17:46","36","<pre><code>Ordering&lt;Item&gt; o = new Ordering&lt;Item&gt;() {
@Override
public int compare(Item left, Item right) {
return Ints.compare(left.price, right.price);
}
};
return o.max(list);
</code></pre>
<p>It's as efficient as it can be: it iterates through the items of the list, and returns the first of the Items having the maximum price: O(n).</p>
","374","1","1","2","2012-08-01 12:18:51","3","TRUE","260223","0"
"http://stackoverflow.com/users/680441","http://stackoverflow.com/questions/7401550","http://stackoverflow.com/questions/7401550/#7401635","2013-07-11 06:57:01","18","30402","3","6","How to Convert Int to Unsigned Byte and Back","<p>I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.</p>
<p>I also need to convert that byte back into that number. How would I do that in Java? I've tried several ways and none work. Here's what I'm trying to do now:</p>
<pre><code>int size = 5;
// Convert size int to binary
String sizeStr = Integer.toString(size);
byte binaryByte = Byte.valueOf(sizeStr);
</code></pre>
<p>and now to convert that byte back into the number:</p>
<pre><code>Byte test = new Byte(binaryByte);
int msgSize = test.intValue();
</code></pre>
<p>Clearly, this does not work. For some reason, it always converts the number into <code>65</code>. Any suggestions?</p>
","44","728","<java><byte><int>","2011-09-13 12:04:22","TRUE","FALSE","7401635","2013-07-11 06:57:01","41","<p>A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:</p>
<pre><code>int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b &amp; 0xFF;
System.out.println(i2); // 234
</code></pre>
","252","1","1","6","2011-09-13 12:10:03","6","TRUE","260223","0"
"http://stackoverflow.com/users/3045","http://stackoverflow.com/questions/11474729","http://stackoverflow.com/questions/11474729/#11475089","2014-08-06 19:24:00","14","7897","5","1","How to build sources jar with gradle","<p>I am working with an open source project that is built with gradle. I would like to generate a (project)-sources.jar file that I can load into my IDE (IntelliJ IDEA) and debug through the project. I know how to load the file if I can generate it.</p>
<p>I have looked through the available gradle tasks for the project and there isn't one that generates a sources jar file.</p>
<p>What is the easiest way to generate a sources jar file for this project?</p>
<p>Adding the source into the jar file that contains the compiled class files would be fine as well.</p>
","36","571","<java><jar><gradle>","2012-07-13 16:40:40","FALSE","FALSE","11475089","2014-08-06 19:24:00","37","<pre><code>task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives sourcesJar
archives javadocJar
}
</code></pre>
","312","0","1","6","2012-07-13 17:05:53","25","TRUE","260223","0"
"http://stackoverflow.com/users/1960543","http://stackoverflow.com/questions/24968960","http://stackoverflow.com/questions/24968960/#24968983","2014-07-26 19:33:43","10","624","0","2","Why is declaring an array as an object correct in Java?","<p>The following expression compiles:</p>
<pre><code>Object oa = new float[20];
</code></pre>
<p>How is this expression valid?</p>
<p>As per my opinion, the correct syntax would be </p>
<pre><code>Object [] oa = new float[20];
</code></pre>
","55","247","<java>","2014-07-26 08:09:55","TRUE","FALSE","24968983","2014-07-26 08:18:56","31","<p>Arrays are objects in Java. So an array of floats is an object. </p>
<p>BTW, <code>Object o = new Object[20];</code> is also valid, since an array of objects is an object.</p>
<p>Also note that <code>Object[] oa = new float[20];</code> is invalid, since primitive floats are not objects, and an array of floats is thus not an array of objects. What would be correct is</p>
<pre><code>Object[] oa = new Float[20];
</code></pre>
<p>Regarding arrays, since they are objects, they have all the methods of java.lang.Object. They also have a public final attribute <code>length</code>, and they are Cloneable and Serializable:</p>
<pre><code>Object o = new float[20];
System.out.println(""o instanceof Serializable = "" + (o instanceof Serializable)); // true
System.out.println(""o instanceof Cloneable = "" + (o instanceof Cloneable)); // true
</code></pre>
","858","4","2","8","2014-07-26 08:12:32","3","TRUE","260223","0"
"http://stackoverflow.com/users/202020","http://stackoverflow.com/questions/2396902","http://stackoverflow.com/questions/2396902/#2396934","2010-03-07 17:30:44","2","663","1","1","Distinguish between HTML/XHTML and plain text in a RSS description-element","<p><strong>Long version:</strong></p>
<p>Those familiar to the standardization nightmare of the RSS-family, may know
that RSS does not provide you with information if for example the ""description"" element
contains just plain text or html or xhtml.</p>
<p>I currently use the ROME-API to convert from various RSS versions to Atom 1.0.
The Rome-API will happily
parse the RSS and later output an Atom feed. Atom fortunately has a means to declare a summary to contain text, html or xhtml.</p>
<p>Example.
RSS:</p>
<pre><code> &lt;item&gt;
&lt;link&gt;http://www.schwarzwaelder-bote.de/wm?catId=79039&amp;amp;artId=14737088&amp;amp;rss=true&lt;/link&gt;
&lt;title&gt;Analyse: Winter reißt Löcher in Straßen und Kassen&lt;/title&gt;
&lt;description&gt;&amp;lt;img src=""http://www.schwarzwaelder-bote.de/cms_images/swol/dpa-InfoLine_rs-images/20100306/1192a_24128948.thumbnail.jpg"" alt=""Schlagloch"" title="""" border=""0""&amp;gt;&amp;amp;nbsp;&amp;amp ;nbsp;&amp;amp;nbsp;Berlin (dpa) - Von Schnee und Eis befreit sind Deutschlands Straßen, und jetzt geht es ans große Aufräumen....&lt;/description&gt;
&lt;/item&gt;
</code></pre>
<p>becomes:
ATOM:</p>
<pre><code>&lt;entry&gt;
&lt;title&gt;Analyse: Winter reißt Löcher in Straßen und Kassen&lt;/title&gt;
&lt;link rel=""alternate"" href=""http://www.schwarzwaelder-bote.de/wm?catId=79039&amp;amp;artId=14737088&amp;amp;rss=true"" /&gt;
&lt;author&gt;
&lt;name /&gt;
&lt;/author&gt;
&lt;id&gt;http://www.schwarzwaelder-bote.de/wm?catId=79039&amp;amp;artId=14737088&amp;amp;rss=true&lt;/id&gt;
&lt;summary type=""text""&gt;&amp;lt;img src=""http://www.schwarzwaelder-bote.de/cms_images/swol/dpa-InfoLine_rs-images/20100306/1192a_24128948.thumbnail.jpg"" alt=""Schlagloch"" title="""" border=""0""&amp;gt;&amp;amp;nbs p;&amp;amp;nbsp;&amp;amp;nbsp;Berlin (dpa) - Von Schnee und Eis befreit sind Deutschlands Straßen, und jetzt geht es ans große Aufräumen....&lt;/summary&gt;
&lt;/entry&gt;
</code></pre>
<p>The problem is <code>type=""text""</code> which tells feed-readers like firefox to render the content of the summary as text --> you get to see all the html-source.</p>
<p><strong>Short version</strong>: How do I detect that the content of the description element is (X)HTML so I can set the correct type attribute?</p>
","74","2312","<java><html><rss><atom><rome>","2010-03-07 16:08:45","TRUE","FALSE","2396934","2010-03-07 17:30:44","0","<p>Heh, my grandad used to read that newspaper :) </p>
<p>A very primitive approach to detecting HTML could be stripping any tags out of the source (in PHP, you would do that with <code>strip_tags()</code>) and see whether the result differs from the original. With reference to the chaos that is RSS, you may have to run this twice, once before, once after a <code>html_entity_decode()</code>, though, so both entity-encoded and non-encoding tags get detected reliably.</p>
<p>Usually, that should produce half-way reliable results but then I saw the <code>ö</code> in this:</p>
<pre><code> &lt;title&gt;Analyse: Dem Mutigen geh&lt;F6&gt;rt die Urne&lt;/title&gt;
</code></pre>
<p>What kind of encoding method is this? I've never seen that before. That would of course be (mis)interpreted as a HTML tag. Is this something atom specific?</p>
","849","4","1","5","2010-03-07 16:17:41","9","TRUE","257086","0"
"http://stackoverflow.com/users/576709","http://stackoverflow.com/questions/4699735","http://stackoverflow.com/questions/4699735/#4699858","2011-01-15 13:55:46","2","361","1","3","Encoding problems in Mysql database","<p>I have a table in a Mysql 5.1 schema. Statement for create this table is:</p>
<pre><code>CREATE TABLE `prova` (
`id` varchar(150) NOT NULL,
`name` varchar(150) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDb DEFAULT CHARSET=ucs2;
</code></pre>
<p>I have also a Java application, running on Ubuntu 10.10, that writes records in this table interfaced by Connector/J 5.1.14. Inserting records is done with Prepared Statement class.</p>
<p>When inserting a couple of records that differ for a marked char (e.g. ('aki kaurismäki','aki kaurismäki') and ('aki kaurismaki','aki kaurismaki')) I get a Duplicate key exception on second record. I tried to print query in the PreparedStatement before execution and it seems to be correct (I tried to execute this query manually from mysql command line client and get any error).</p>
<p>How could I solve this problem?
Thanks in advance,
Antonio</p>
","35","933","<java><mysql><unicode><mysql-connector>","2011-01-15 13:10:13","TRUE","FALSE","4699858","2011-01-15 13:55:46","0","<p>This is because - as said in the comment - mySQL's Unicode encodings normalize accented characters internally in comparisons, leading to </p>
<pre><code> kaurismäki = kaurismaki
</code></pre>
<p>from the <a href=""http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html"" rel=""nofollow"">manual</a>:</p>
<blockquote>
<p>To further illustrate, the following
equalities hold in both
utf8_general_ci and utf8_unicode_ci
(for the effect this has in
comparisons or when doing searches,
see Section 9.1.7.8, “Examples of the
Effect of Collation”):</p>
<pre><code>Ä = A
Ö = O
Ü = U
</code></pre>
</blockquote>
<p>in my understanding, making the index column <code>ucs2_bin</code> should sort it out. A binary comparison will not normalize accented characters.</p>
","787","4","2","1","2011-01-15 13:39:14","29","TRUE","257086","0"
"http://stackoverflow.com/users/156775","http://stackoverflow.com/questions/6205818","http://stackoverflow.com/questions/6205818/#6205833","2011-06-01 18:23:37","0","1001","0","1","Setting HTTP_REFERER for URLS on webpages?","<p>I have a webpage which refers other pages.</p>
<p>I want to be able to set the HTTP_REFERER on the URL's that are clicked.</p>
<p>What options do I have? </p>
","42","164","<java><javascript><http><http-headers>","2011-06-01 18:16:32","FALSE","FALSE","6205833","2011-06-01 18:23:37","4","<blockquote>
<p>What options do I have?</p>
</blockquote>
<p>None really. The browser sets this automatically.</p>
<p>The only thing you can do is redirect to a script (under your control) like</p>
<pre><code>http://example.com/redirect.php?url=........
</code></pre>
<p>That file (in this case, PHP) would then do a header redirect to the target, and show up in the receiving site's HTTP_REFERER header.</p>
<p>Also, linking to a <code>https://</code> page from a <code>http://</code> one or vice versa will <strong>drop</strong> the referrer. See the Wikipedia article on <a href=""http://en.wikipedia.org/wiki/HTTP_referrer"" rel=""nofollow"">referrer hiding.</a> </p>
<p>Other than that, there is nothing you can do to alter it. There is definitely no way to set it to an arbitrary value from within a web site.</p>
","825","6","1","1","2011-06-01 18:18:22","2","TRUE","257086","0"
"http://stackoverflow.com/users/471516","http://stackoverflow.com/questions/3907384","http://stackoverflow.com/questions/3907384/#3907396","2014-04-21 17:18:33","12","7422","0","5","What's the most concise way to get the inverse of a Java boolean value?","<p>If you have a boolean variable:</p>
<pre><code>boolean myBool = true;
</code></pre>
<p>I could get the inverse of this with an if/else clause:</p>
<pre><code>if (myBool == true)
myBool = false;
else
myBool = true;
</code></pre>
<p>Is there a more concise way to do this?</p>
","71","284","<java><boolean><inverse>","2010-10-11 14:59:29","TRUE","FALSE","3907396","2010-12-10 02:18:00","46","<p>Just assign using the logical NOT operator <code>!</code> like you tend to do in your condition statements (<code>if</code>, <code>for</code>, <code>while</code>...). You're working with a boolean value already, so it'll flip <code>true</code> to <code>false</code> (and vice versa):</p>
<pre><code>myBool = !myBool;
</code></pre>
","335","1","1","1","2010-10-11 15:00:27","1","TRUE","255173","0"
"http://stackoverflow.com/users/743655","http://stackoverflow.com/questions/5925913","http://stackoverflow.com/questions/5925913/#5925923","2011-05-08 06:13:28","4","3597","0","1","Java PatternSyntaxException when trying to split },{","<p>I'm trying to break up an array I got through an API on a site, which Java has retrieved as a String. Whenever I run the following code: </p>
<pre><code>String[] ex = exampleString.split(""},{"");
</code></pre>
<p>Java gives me a PatternSyntaxException. For some reason, it really doesn't like },{. I've tried escaping it, but it says </p>
<pre><code>\{
</code></pre>
<p>is an illegal escape. What is the proper way to escape this String?</p>
","52","448","<java><regex><exception><escaping><split>","2011-05-08 06:08:08","TRUE","FALSE","5925923","2011-05-08 06:13:28","8","<blockquote>
<p>For some reason, it really doesn't like },{.</p>
</blockquote>
<p>This is because braces (<code>}</code> and <code>{</code>) are special characters in Java regular expressions. If you try to use them literally without escaping, it's considered a syntax error, hence your exception.</p>
<blockquote>
<p>What is the proper way to escape this String?</p>
</blockquote>
<p>Escape the backslashes too, by doubling them. This is for Java string escapes. The escaped backslashes will then escape the braces for the regex.</p>
<pre><code>String[] ex = exampleString.split(""\\},\\{"");
</code></pre>
","614","4","1","1","2011-05-08 06:11:37","3","TRUE","255173","0"
"http://stackoverflow.com/users/364746","http://stackoverflow.com/questions/4638023","http://stackoverflow.com/questions/4638023/#4638038","2012-02-04 06:56:54","3","610","0","3","Strange Wrapper Classes behavior with == and !=","<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href=""http://stackoverflow.com/questions/3130311/weird-java-boxing"">Weird Java Boxing</a> </p>
</blockquote>
<p>Recently while I was reading about wrapper classes I came through this strange case:</p>
<pre><code>Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println(""different objects"");
if(i1 == i2) System.out.println(""same object"");
</code></pre>
<p>Which prints:</p>
<pre><code>different objects
</code></pre>
<p>and </p>
<pre><code>Integer i1 = 10;
Integer i2 = 10;
if(i1 != i2) System.out.println(""different objects"");
if(i1 == i2) System.out.println(""same object"");
</code></pre>
<p>Which prints:</p>
<pre><code>same object
</code></pre>
<p>Is there any reasonable explanation for this case?</p>
<p>Thanks</p>
","47","814","<java><wrapper>","2011-01-09 06:45:58","TRUE","FALSE","4638038","2011-01-09 07:24:33","9","<p>The reason why <code>==</code> returns true for the second case is because the primitive values boxed by the wrappers are sufficiently small to be interned to the same value at runtime. Therefore they're equal.</p>
<p>In the first case, Java's integer cache is not large enough to contain the number 1000, so you end up creating two distinct wrapper objects, comparing which by reference returns false.</p>
<p>The use of said cache can be found in the <code>Integer#valueOf(int)</code> method (where <code>IntegerCache.high</code> defaults to 127):</p>
<pre><code>public static Integer valueOf(int i) {
if(i &gt;= -128 &amp;&amp; i &lt;= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
</code></pre>
<p>As Amber says, if you use <code>.equals()</code> then both cases will invariably return true because it unboxes them where necessary, then compares their primitive values.</p>
","947","4","1","3","2011-01-09 06:50:30","5","TRUE","255173","0"
"http://stackoverflow.com/users/458960","http://stackoverflow.com/questions/3950439","http://stackoverflow.com/questions/3950439/#3950452","2010-10-16 19:59:02","3","454","0","4","Equals method for objects","<p>I'm trying to write an equals method for objects that compares their fields, and if equal, then true:</p>
<pre><code> public boolean equals(Ghost other){
if (this.x == other.x &amp;&amp; this.y == other.y &amp;&amp; this.direction==other.direction &amp;&amp; this.color==other.color)
return true;
else
return false;
}
</code></pre>
<p>What would be wrong with this?</p>
","25","444","<java><object><equals>","2010-10-16 19:32:39","TRUE","FALSE","3950452","2010-10-16 19:59:02","7","<p>I looked at <a href=""http://stackoverflow.com/questions/3939274/java-initializing-objects"">one of your previous questions</a>, and it seems the <code>color</code> field is a <a href=""http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Color.html"" rel=""nofollow""><code>Color</code></a>. I'm going to assume that you haven't changed the type of that field.</p>
<p>That's a class, and therefore a reference type, which means you need to use <code>equals()</code> or a similar method to compare the colors (I haven't used that class before, so I can't tell you exactly which method to use).</p>
<pre><code>if (/* ... &amp;&amp; */ this.color.equals(other.color)) {
</code></pre>
<p>As in the comments, using <code>==</code> to compare reference types is really comparing memory addresses in Java. It'll only return <code>true</code> if they both refer to the same object in memory.</p>
<hr>
<p><strong>EDIT:</strong> <a href=""http://stackoverflow.com/questions/3950439/equals-method-for-objects/3950483#3950483"">akf points out</a> that you need to use the base <code>Object</code> class for your parameter, otherwise you're not overriding <code>Object.equals()</code>, but actually overloading it, i.e. providing a different way of calling the same-named method. If you happen to pass an object of a totally different class by accident, unexpected behavior might occur (although then again if they are of different classes it will return <code>false</code> correctly anyway).</p>
<pre><code>@Override
public boolean equals(Object obj) {
if (!(obj instanceof Ghost))
return false;
// Cast Object to Ghost so the comparison below will work
Ghost other = (Ghost) obj;
return this.x == other.x
&amp;&amp; this.y == other.y
&amp;&amp; this.direction == other.direction
&amp;&amp; this.color.equals(other.color);
}
</code></pre>
","1884","4","2","1","2010-10-16 19:37:12","5","TRUE","255173","0"
"http://stackoverflow.com/users/152135","http://stackoverflow.com/questions/4129706","http://stackoverflow.com/questions/4129706/#4129717","2011-10-19 13:11:05","2","5389","0","6","Java static context ","<p>I am using a package that has a method call that is non-static.
It will not let me call this method from a static context.
I can't change the non-static method, how can I call this method?</p>
","19","197","<java><static>","2010-11-09 01:30:41","FALSE","FALSE","4129717","2010-11-09 01:54:05","5","<p>Create an object out of that class and call the method on the object?</p>
<pre><code>import com.acme.myclass;
...
MyClass obj = new MyClass();
obj.nonStaticMethod();
</code></pre>
<p>If the package you're using has any documentation, be sure to look through it to see how you're expected to use that class and its non-static method. You may also want to read up more on static versus non-static in object-oriented programming in general, to get a better idea of the differences.</p>
","490","2","1","2","2010-11-09 01:32:29","2","TRUE","255173","0"
"http://stackoverflow.com/users/456809","http://stackoverflow.com/questions/3798695","http://stackoverflow.com/questions/3798695/#3798706","2010-09-27 06:46:41","2","268","0","3","Program Runs Continually, but never actually executes anything","<p>I run the program, but none of my lines execute. When I tell it to stop it prints a red error message.</p>
<pre><code>Exception in thread ""main"" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
</code></pre>
<p>Here's my code, nothing really seems to be out of the ordinary to my limited experience and my IDE doesn't report any errors while I'm writing it.</p>
<pre><code>import java.util.Scanner;
public class 312easf2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int grade = 0; // initial value to satify loop condition
double averageGrade = 0.0;
int max = keyboard.nextInt();
int min = max;
int next = keyboard.nextInt();
System.out.println(""Enter a nonnegative integer (negative to stop): "");
while(next &gt;= 0);
{
if(next &gt; max)
max = next;
else if(next &lt; min);
min = next;
next = keyboard.nextInt();
}
}
}
</code></pre>
","62","1211","<java>","2010-09-26 16:23:16","TRUE","FALSE","3798706","2010-09-27 06:46:41","12","<p><strong>EDIT:</strong> I point out a syntax gotcha in my answer, which you <em>still</em> have to fix before your program will work correctly, but for <em>now</em> the real problem lies in your first few lines:</p>
<pre><code> Scanner keyboard = new Scanner(System.in);
int grade = 0; // initial value to satify loop condition
double averageGrade = 0.0;
int max = keyboard.nextInt();
int min = max;
int next = keyboard.nextInt();
</code></pre>
<p>Your program is executing something but it's saying nothing, and printing the error only when you stop, all because of a mistake in your program's implementation. It's not a syntax error, however; it's just that you forgot something important here.</p>
<p><a href=""http://stackoverflow.com/questions/3798695/program-runs-continually-but-never-actually-executes-anything/3798854#3798854"">Wcrousse in his answer explains what's happening.</a></p>
<hr>
<p>There <del>is a syntax issue</del> are <strong>multiple</strong> similar syntax issues somewhere in your code that are actually legal syntax, which is why your IDE and the compiler aren't complaining. However, they're more often really a very common mistake that causes unintended behavior.</p>
<p>Pay particular attention to your semicolons, and try looking through your code again. Or, use your debugger as Gabe suggests, that'll give you a better idea what's happening.</p>
","1434","5","1","5","2010-09-26 16:24:52","1","TRUE","255173","0"
"http://stackoverflow.com/users/235692","http://stackoverflow.com/questions/4130208","http://stackoverflow.com/questions/4130208/#4130240","2010-11-09 03:22:24","2","171","0","1","IS php same as java in terms of pass by reference?","<p>As PHP borrows most of its object oriented features from java. I would like to know whether PHP and java both uses the same concept of pass by value?</p>
<p>I know Java is not pass by reference.Its just that object references are passed by value. How about PHP? Does PHP support pass by reference?</p>
","50","306","<java><php>","2010-11-09 03:17:06","FALSE","FALSE","4130240","2010-11-09 03:22:24","3","<p>In PHP, you only pass stuff by reference if you declare a function and litter it with ampersands:</p>
<pre><code>function &amp;return_by_reference() {
$something = make_something();
return $something;
}
function increment(&amp;$n) {
// This changes $n because it is a reference parameter
$n++;
}
</code></pre>
<p>There is call-time pass-by-reference as well (i.e. passing variables by reference when you <em>call</em> functions), but I shan't go on about it because it presents a risk for unexpected behavior. It's better practice to declare parameters to be passed by reference in your function signatures instead.</p>
<p>As for objects: in PHP 4, objects are all passed by value. In PHP 5, references to objects are passed by value, just like in Java.</p>
","781","3","1","4","2010-11-09 03:22:24","5","TRUE","255173","0"
"http://stackoverflow.com/users/20654","http://stackoverflow.com/questions/5836694","http://stackoverflow.com/questions/5836694/#5836708","2011-04-29 21:34:06","2","125","0","4","How to create a character class of the following set","<pre><code>+ - * / % &lt; &gt; = ! &amp; ^ | ? :
</code></pre>
<p>I've tried: </p>
<pre><code>[+-*/%&lt;&gt;=!&amp;^|?:]
</code></pre>
<p>But I think some of them will need to be scaped. How can I tell which ones?</p>
","52","221","<java><regex><character-class>","2011-04-29 19:49:09","TRUE","FALSE","5836708","2011-04-29 20:06:20","7","<p>You'll need to escape the <code>-</code> as otherwise it'd be interpreted as a character range between <code>+</code> and <code>*</code>, which isn't valid:</p>
<pre><code>[+\-*/%&lt;&gt;=!&amp;^|?:]
</code></pre>
<p>The other metacharacters, as far as I know, are taken literally in a character class.</p>
","312","2","1","6","2011-04-29 19:50:57","1","TRUE","255173","0"
"http://stackoverflow.com/users/51754","http://stackoverflow.com/questions/10861066","http://stackoverflow.com/questions/10861066/#10861246","2012-06-02 09:36:15","1","346","0","1","Using jsoup with dynamic id's","<p>I'm trying to use jsoup in order to parse a html file. It was done using tables to display products. Each product is inside one table whose id ranges from 1 to ""n"". Like the example bellow:</p>
<pre><code>&lt;table align=""center"" width=""98%"" id=""A + 1""&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td valign=""top"" style=""width: 03%;""&gt;
&lt;span class=""line""&gt;1&lt;/span&gt;
&lt;/td&gt;
&lt;td valign=""top"" style=""width: 56%;""&gt;
&lt;span class=""line""&gt;PRODNAME&lt;/span&gt;
&lt;/td&gt;
&lt;td valign=""top"" style=""width: 10%;""&gt;
&lt;span class=""line""&gt;850.000&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
</code></pre>
<p>So the first product will be on table with id ""A + 1"", the second one in ""A + 2"" and so on.</p>
<p>I'm not able to use selector to iterate over these tables. I'm doing:</p>
<pre><code>Document doc = Jsoup.parse(html);
Elements products = doc.select(""table[idˆ=A]"");
for (Element product : products) {
// do something
}
</code></pre>
<p>If I read it right (<a href=""http://jsoup.org/apidocs/org/jsoup/select/Selector.html"" rel=""nofollow"">http://jsoup.org/apidocs/org/jsoup/select/Selector.html</a>), <code>doc.select(""table[idˆ=A]"")</code> should retrieve all tables whose id attribute starts with an ""A""...</p>
<p>But my Elements object (products) is empty... What I'm doing wrong?</p>
<p>I'm using jsoup 1.6.3, java 1.6.0_31 over a Mac OS X (10.7.4) with Netbeans 7.1.2.</p>
<p>Any help appreciated.</p>
","29","1569","<java><css-selectors><html-parsing><jsoup>","2012-06-02 09:02:11","TRUE","FALSE","10861246","2012-06-02 09:36:15","3","<p>You seem to be using the wrong circumflex character in your selector, although I'm not sure if jsoup is supposed to return an empty result set or throw an exception on an invalid selector.</p>
<p>Anyway, try this instead:</p>
<pre><code>Document doc = Jsoup.parse(html);
Elements products = doc.select(""table[id^=A]"");
for (Element product : products) {
   // do something
}
</code></pre>
","394","2","1","4","2012-06-02 09:36:15","34","TRUE","255173","0"
"http://stackoverflow.com/users/685275","http://stackoverflow.com/questions/5931168","http://stackoverflow.com/questions/5931168/#5931184","2014-01-11 21:59:25","1","2909","0","1","java: use regular expression to extract a number in a string","<p>I have a string of format ""[232]......."" I want to extract the 232 out of the string, I did this</p>
<pre><code>public static int getNumber(String str) {
Pattern pattern = Pattern.compile(""\\[([0-9]+)\\]"");
Matcher matcher = pattern.matcher(str);
int number = 0;
while (matcher.find()) {
number = Integer.parseInt(matcher.group());
}
return number;
}
</code></pre>
<p>but it doesn't work, I got the following exception:</p>
<pre><code>Exception in thread ""main"" java.lang.NumberFormatException: For input string: ""[232]""
</code></pre>
<p>Anyone knows how could I solve this problem, and if there is a more efficient way for me to do this kind of pattern matching in java?</p>
","60","715","<java><regex><matching>","2011-05-08 23:46:39","TRUE","FALSE","5931184","2014-01-11 21:59:25","3","<p><code>group()</code> without any parameters returns the entire match (equivalent to <code>group(0)</code>). That includes the square brackets that you've specified in your regex.</p>
<p>To extract the number, pass <code>1</code> to return only the first capture group within your regex (the <code>([0-9]+)</code>):</p>
<pre><code>number = Integer.parseInt(matcher.group(1));
</code></pre>
","394","2","1","1","2011-05-08 23:49:12","3","TRUE","255173","0"
"http://stackoverflow.com/users/2752065","http://stackoverflow.com/questions/19360270","http://stackoverflow.com/questions/19360270/#19361800","2013-10-14 13:50:17","0","294","0","1","Escaping Special Characters on cssSelector webdriver","<p>how can I escape the following special character so i can use the ID on the div to get the form? This is my cssSelector: </p>
<pre><code>#form &gt; div:nth-child(4)&gt;div:nth-child(2) &gt; div:nth-of-type(2) &gt; div:nth-of-type(2)
</code></pre>
<p>And this is the html code:</p>
<pre><code>div id=""form:panelGridTransactionInfo"" class=""ui-panel ui-widget ui-widget-content ui-corner-all""
</code></pre>
<p>Thanks</p>
","52","425","<java><selenium><css-selectors><selenium-webdriver>","2013-10-14 12:28:22","TRUE","FALSE","19361800","2013-10-14 13:50:17","3","<p>You escape it with a backslash like so:</p>
<pre><code>#form\:panelGridTransactionInfo &gt; div:nth-child(4) &gt; div:nth-child(2) &gt; div:nth-of-type(2) &gt; div:nth-of-type(2)
</code></pre>
<p>In Java, repeat the backslash to escape itself within the string:</p>
<pre><code>""#form\\:panelGridTransactionInfo &gt; div:nth-child(4) &gt; div:nth-child(2) &gt; div:nth-of-type(2) &gt; div:nth-of-type(2)""
</code></pre>
","424","2","2","1","2013-10-14 13:50:17","82","TRUE","255173","0"
"http://stackoverflow.com/users/485529","http://stackoverflow.com/questions/4007822","http://stackoverflow.com/questions/4007822/#4007833","2010-10-24 10:19:20","0","284","0","2","""cannot find symbol"" on a wsdl Java Client","<p>This is part of a lab exercise for a course I'm doing, it's not assessable, just a learning exercise. Not sure why but the tut didn't go through it, so I just went through it at home but I'm stuck on the last part.</p>
<p>I'm trying to write a java WSDL client to access <a href=""http://www.nanonull.com/TimeService/TimeService.asmx?WSDL"" rel=""nofollow"">http://www.nanonull.com/TimeService/TimeService.asmx?WSDL</a> - I should input UTC+10 to display the current time. Below is the code that I have written:</p>
<pre><code>package time;
class Client {
public static void main(String args[]){
TimeService service = new TimeService();
TimeServiceSoap port= service.getTimeServiceSoap();
String result = port.GetTimeZoneTime(""UTC+10"");
System.out.println(""Time is ""+result);
}
}
</code></pre>
<p>When I try and compile the code I get the following error:</p>
<pre><code>C:\Program Files\Java\jdk1.6.0_22\bin&gt;javac -d . ""c:\Program Files\Java\jdk1.6.0
_22\bin\time\Client.java""
c:\Program Files\Java\jdk1.6.0_22\bin\time\Client.java:13: cannot find symbol
symbol : method GetTimeZoneTimeResponse(java.lang.String)
location: interface time.TimeServiceSoap
String result = port.GetTimeZoneTime(""UTC+10"");
^
1 error
</code></pre>
<p>Any thoughts on what I'm doing wrong?</p>
","42","1353","<java><wsdl>","2010-10-24 10:12:41","TRUE","FALSE","4007833","2010-10-24 10:19:20","2","<p>Did you mean </p>
<pre><code>String result = port.getTimeZoneTime(""UTC+10"");
</code></pre>
<p>with a lowercase <code>g</code>? Java method names are case-sensitive, so it won't recognize the method if you get its letter casing wrong. As per both <a href=""http://www.altova.com/library/wsdl/wsdl_documentation.html#Link03CB0A80"" rel=""nofollow"">WSDL's <code>TimeServiceSoap</code> documentation</a> and Java naming conventions, method names are in camel case beginning with a lowercase letter.</p>
","501","2","1","1","2010-10-24 10:17:43","5","TRUE","255173","0"
"http://stackoverflow.com/users/269931","http://stackoverflow.com/questions/4844419","http://stackoverflow.com/questions/4844419/#4844429","2011-01-31 21:52:57","0","122","0","3","Casting inner objects in java - unchecked exception","<p>I'm having a problem with inner classes. I build an object (let's say a train) with an inner class representing states (let's say the stops of the train).</p>
<p>I'm trying to run this code:</p>
<pre><code>private void CustomObjectBuilder (String [] origin) {
final int array_dim = origin.length;
InnerCustomObject[] tmp_bin = new InnerCustomObject[array_dim];
for (int ii = 0; ii &lt; array_dim; ii++) {
String debug = extractData(origin[ii]);
tmp_bin[ii].setData(debug);
}
}
</code></pre>
<p>It compiles just just fine but at runtime I get a null object exception.</p>
<p>What am I doing wrong?</p>
<p>Here you can finde the original code:</p>
<pre><code>public class CustomObject {
InnerCustomObject [] stops;
public class InnerCustomObject {
String name, station, schedTime, depTime, schedRail, depRail;
public void setData (String origin) {
this.station = origin;
}
}
}
</code></pre>
<p>Edit: I solved by calling </p>
<pre><code> CustomObject.InnerCustomObject ico = new CustomObject(). new InnerCustomObject();
</code></pre>
<p>why it needs to be so verbose? </p>
","51","1167","<java><arrays><inner-classes>","2011-01-30 17:42:51","TRUE","FALSE","4844429","2011-01-31 21:52:57","2","<p>Well, the most immediate thing I notice is you don't populate <code>tmp_bin[]</code> with any objects after you declare it. When you first create an array, all it contains are <code>null</code>s.</p>
<p>So when you do this in your loop:</p>
<pre><code>tmp_bin[ii].setData(debug);
</code></pre>
<p>There is nothing to invoke <code>setData()</code> on, resulting in the exception.</p>
<p>Re edit: you can just do</p>
<pre><code>InnerCustomObject ico = this.new InnerCustomObject();
</code></pre>
<p>since you're creating them within your outer <code>CustomObject</code> class's <code>CustomObjectBuilder()</code> instance method.</p>
","641","5","2","5","2011-01-30 17:45:04","3","TRUE","255173","0"
"http://stackoverflow.com/users/482312","http://stackoverflow.com/questions/3982519","http://stackoverflow.com/questions/3982519/#3982540","2010-10-20 21:52:32","0","520","0","7","Identifying syntax errors in Java","<p>Given this code in Java:</p>
<pre><code>int i,j;
String[] names;
names[0] = new String(""mary"");
names[1] = ""John"";
i = names.length;
j = names[0].length();
</code></pre>
<p>I need to find the error. As far as I can tell, lines 1, 2, 4, and 5 are correct because they involve simple instance variables, adding elements to arrays, and finding the length of an array. However lines 3 and 6 are weird. </p>
<p>Can you add a string to an array like the way done in line 3? If the array is full of strings, can you index one out and use the length() method on it?</p>
","33","568","<java><arrays><syntax-error>","2010-10-20 21:36:00","TRUE","FALSE","3982540","2010-10-20 21:45:28","7","<p>There are no syntax errors in the above code, however:</p>
<blockquote>
<p>they involve simple instance variables</p>
</blockquote>
<p>They're not instance variables unless you declare them as part of a class, outside its methods. If they're declared within methods, they're called <em>local</em> variables to the scope of whichever code blocks they're declared.</p>
<hr>
<p>Trying to add anything to an uninitialized array, as in</p>
<pre><code>String[] names;
names[0] = new String(""mary"");
names[1] = ""John"";
</code></pre>
<p>Will still cause a compile-time error, however it's not due to incorrect syntax but an attempt to manipulate an uninitialized variable. You need to initialize it, so for example as others have said, use:</p>
<pre><code>String[] names = new String[2];
</code></pre>
<hr>
<blockquote>
<p>If the array is full of strings, can you index one out and use the length() method on it?</p>
</blockquote>
<p>Sure, this line is perfectly legal:</p>
<pre><code>j = names[0].length();
</code></pre>
<p>And is equivalent to (assuming you fix the uninitialized-array error above yada yada):</p>
<pre><code>String firstElement = names[0];
j = firstElement.length();
</code></pre>
","1212","8","4","4","2010-10-20 21:38:46","2","TRUE","255173","0"
"http://stackoverflow.com/users/454848","http://stackoverflow.com/questions/3950480","http://stackoverflow.com/questions/3950480/#3950490","2010-10-16 19:47:37","0","67","0","2","Null pointer expection","<pre><code>String graphNameUsed = graphName.getName();
if (graphType.equals(""All"") || graphType.equals(""ALL""))
graphNameUsed += ""_ALL"";
</code></pre>
<p>If my String is null, then will it throw Null Pointer expection when i am checking whether it equals or not. To Avoid this expection, how should i check.</p>
","22","332","<java>","2010-10-16 19:45:21","TRUE","FALSE","3950490","2010-10-16 19:47:37","4","<p>Flip the comparisons the other way around so you're calling <code>equals()</code> on the string literals, which aren't null and thus won't cause the exception.</p>
<p>When null is passed to the <code>equals()</code> method, it simply returns <code>false</code> right away. However, if you try to call it on a variable that's null, the object isn't there for you to call that method on, which is why you get the exception.</p>
<pre><code>if (""All"".equals(graphType) || ""ALL"".equals(graphType))
</code></pre>
<p>If you just want to do case-insensitive matches, use the <code>equalsIgnoreCase()</code> method instead so you just perform one check:</p>
<pre><code>if (""All"".equalsIgnoreCase(graphType))
</code></pre>
","720","3","2","3","2010-10-16 19:47:37","2","TRUE","255173","0"
"http://stackoverflow.com/users/342303","http://stackoverflow.com/questions/3793918","http://stackoverflow.com/questions/3793918/#3793929","2011-05-08 09:51:18","0","417","0","1","Problem with java.util.Scanner & strings","<p>I tried to implement a simple yes/no input with java.util.Scanner. My code looks like this:</p>
<pre><code>public boolean ask(String quest){
String answ = scann(quest + "" (y/n)"");
answ = answ.split("""")[1].toLowerCase();
if(answ == ""y"") { return true; }
if(answ == ""n"") { return false;}
//if answer isnt understood
printOut(""Please enter 'y' or 'n'! Answered: "" + answ +""!"");
return ask(quest);
}
</code></pre>
<p>To make it short: It ends up with an infinite request for the answer. The answer is never understood, I got no clue what I did wrong.</p>
","40","571","<java><terminal><java-util-scanner>","2010-09-25 13:02:53","TRUE","FALSE","3793929","2011-05-08 09:51:18","3","<p>You cannot use <code>==</code> to compare strings in Java (well, you can, but it's not the right way to compare their literal values). You need to use <code>equals()</code>:</p>
<pre><code> if (""y"".equals(answ)) { return true; }
if (""n"".equals(answ)) { return false; }
</code></pre>
","290","1","1","3","2010-09-25 13:06:30","4","TRUE","255173","0"
"http://stackoverflow.com/users/479180","http://stackoverflow.com/questions/5972026","http://stackoverflow.com/questions/5972026/#5972041","2014-08-13 10:39:52","0","6316","1","2","Path to file on a Mac: FileNotFoundException","<p>I'm working on a mac and I'm trying to specify the path to a file on my desktop. </p>
<p>I just did it like this: <code>File file = new File(""/users/desktop/sample.json"");</code></p>
<p>When I tried running it I got a FileNotFoundException.</p>
<p>How do I correctly specify the path?</p>
","44","295","<java>","2011-05-12 00:21:14","FALSE","FALSE","5972041","2014-08-13 10:39:52","8","<p>Mac OS X's filesystem is case sensitive. <code>Users</code> and <code>Desktop</code> should start with capital letters, and your filename should also match case too.</p>
<p>Since you're looking for your desktop folder and not the root folder of a user with the name <code>desktop</code>, you need to add your username after the <code>Users</code> folder. For example:</p>
<pre><code>File file = new File(""/Users/LuxuryMode/Desktop/sample.json"");
</code></pre>
","465","2","1","3","2011-05-12 00:23:50","2","TRUE","255173","0"
"http://stackoverflow.com/users/1005607","http://stackoverflow.com/questions/8930921","http://stackoverflow.com/questions/8930921/#8930992","2014-07-31 19:58:55","2","6718","0","2","DOM getElementsByTagName() returning Nodes with NULL Values","<p>I have an XML file as follows.</p>
<p>When I use <code>getElementsByTagName(""LEVEL2_ID"")</code>, I do get a <code>NodeList</code> with <code>Nodes</code>, but those Nodes have NULL values (in other words, <code>getNodeValue()</code> on each result node will return <code>NULL</code>). Why is this? I need to get the contents value of each node, in this case <code>2000</code>.</p>
<p>XML:</p>
<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?&gt;
&lt;Root&gt;
&lt;Date&gt;01/17/2012&lt;/Date&gt;
&lt;LEVEL1&gt;
&lt;LEVEL1_ID&gt;1000&lt;/LEVEL1_ID&gt;
&lt;LEVEL2&gt;
&lt;LEVEL2_ID&gt;2000&lt;/LEVEL2_ID&gt;
&lt;/LEVEL2&gt;
&lt;/LEVEL1&gt;
&lt;/Root&gt;
</code></pre>
<p>In Java, printing the <strong>Value</strong> of the 1st node obtained with <strong>getElementsByTagName()</strong> returns <strong>NULL</strong>:</p>
<pre><code>NodeList nodes = document.getElementsByTagName(""LEVEL2_ID"");
System.out.println(""Value of 1st node: "" + nodes.item(0).getNodeValue());
</code></pre>
","59","1055","<java><xml><dom><nodelist>","2012-01-19 17:56:18","TRUE","FALSE","8930992","2012-01-19 18:22:48","2","<p><a href=""http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247"" rel=""nofollow"">That is defined in the specification</a>. Element nodes' <code>nodeValue</code> is <code>null</code>. </p>
<blockquote>
<p><code>nodeValue</code> of type <code>DOMString</code>: The value of this node, depending on its type; see the table above. When it is defined to be null, setting it has no effect.</p>
</blockquote>
<p>If you want to get the text content of each node, you have to iterate over all text node descendants and concatenate their value.</p>
<p>That said, the API implementation you are using might offer a method to directly retrieve the text content of an element. For example, PHP's <code>DOMNode</code> has a <a href=""http://www.php.net/manual/en/class.domnode.php#domnode.props.textcontent"" rel=""nofollow""><code>$textContent</code></a> property.</p>
<p>If, as in your case, the element's only child is actually the text node you want, you can simply access its value:</p>
<pre><code>element.getFirstChild().getNodeValue()
</code></pre>
","1054","5","1","1","2012-01-19 18:00:57","4","TRUE","252780","0"
"http://stackoverflow.com/users/205543","http://stackoverflow.com/questions/2294809","http://stackoverflow.com/questions/2294809/#2294851","2010-02-25 09:31:53","4","512","2","7","Going from Java imports to C++ includes","<p>I've been struggling with understanding how C++ classes include other classes. I'm guessing this is easier to understand without any preconceived notions. </p>
<p>Assume my two classes are Library and Book. I have a .h and .cpp file for each. My ""main.cpp"" runs a simple console app to use them. Here is a simple example:</p>
<pre><code>//Library.h
#ifndef LIBRARY_H_
#define LIBRARY_H_
#endif
class Library
{
public:
Library();
~ Library();
private:
Book *database;
};
</code></pre>
<p>This throws an error about how ""Book does not name a type"". In Java I would import some package like org.me.Domain.Book. Can someone please explain how this works in C++?</p>
","39","682","<java><c++><class>","2010-02-19 07:59:02","TRUE","FALSE","2294851","2010-02-19 08:18:35","7","<p>In C++ source files are conceptually completely separate from class definitions.</p>
<p><code>#include</code> and header files work at a basic text level. <code>#include ""myfile""</code> simply includes the contents of the file <code>myfile</code> at the point at which the include directive is placed.</p>
<p>Only after this process has happened is the resulting block of text interpreted as C++ code. There is no language requirement that a class called <code>Book</code> has to be defined in a file called <code>Book.h</code>. Although it is highly recommended that you do follow such a convention, it's essential to remember that it's not a given when debugging missing declaration or definition issues.</p>
<p>When parsing your <code>Library.h</code> file the compiler must have seen a declaration for the identifier <code>Book</code> at the point at which it is used in the defintion of the class <code>Library</code>.</p>
<p>As you are only declaring a member variable of type ""pointer to <code>Book</code>"", you only need a declaration and not a full definition to be available so if <code>Book</code> is a class then the simplest 'fix' is to add a forward declaration for it before the definition of <code>Library</code>.</p>
<p>e.g.</p>
<pre><code>class Book;
class Library
{
// definition as before
};
</code></pre>
<p><strong>Include Guards</strong></p>
<p>It looks like you may have some include guard errors. Because you can only define classes once per translation units the definitions inside header files are usually protected with include guards. These ensure that if the same header is included multiple times via different include files that the definitions it provides aren't seen more than once. Include guards should be arranged something like this. Looking at your <code>Library.h</code>, it may be that your include guards are not terminated correctly.</p>
<p>myclass.h:</p>
<pre><code>#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
};
// The #ifndef is terminated after all defintions in this header file
#endif //MYCLASS_H
</code></pre>
","2088","9","2","6","2010-02-19 08:10:03","11","TRUE","252485","0"
"http://stackoverflow.com/users/242762","http://stackoverflow.com/questions/3642143","http://stackoverflow.com/questions/3642143/#3642451","2010-09-04 13:21:31","4","5401","0","3","Get a single file from a remote git repository","<p>Is there a way to programmatically download a single file from a remote git repository, in Java?</p>
<ol>
<li>I prefer a solution which uses as little bandwidth as possible, preferably only downloading that single file. I do not need to browse the repository, I already have the file's path.</li>
<li>I prefer a solution which does not depend on other applications (e.g. an installation of another git client on the machine). A Java library which contains a git client implementation itself would be optimal.</li>
</ol>
<p>I was able to do something similar with Subversion using <a href=""http://www.svnkit.com/"" rel=""nofollow"">SVNKit</a> and I've seen there is a pure java implementation of git (<a href=""http://eclipse.org/jgit/"" rel=""nofollow"">eclipse's JGit</a>) which might be able to do something similar, so I hope there is a positive answer; though from what I understand about how git works - allowing updates only from local repositories - this could prove to be problematic.</p>
","46","995","<java><git><download><jgit>","2010-09-04 11:59:41","FALSE","FALSE","3642451","2010-09-04 13:21:31","6","<p>git isn't really designed for single file access from a remote repository but you can abuse <code>git archive</code> for this. The downside is that you have to download a ""tree"" rather than just the blob that you need.</p>
<p>E.g.</p>
<pre><code>git archive --remote=url://to.git.repo branch path/to/dir | tar -x file
</code></pre>
<p>As an alternative, if you have gitweb set up on the remote repository you can use a simple curl or wget command to download any file in its ""raw"" format.</p>
","499","3","1","3","2010-09-04 13:21:31","82","TRUE","252485","0"
"http://stackoverflow.com/users/132396","http://stackoverflow.com/questions/2495994","http://stackoverflow.com/questions/2495994/#2496023","2010-03-24 19:19:35","15","2055","2","6","Can SHA-1 algorithm be computed on a stream? With low memory footprint?","<p>I am looking for a way to compute SHA-1 checksums of very large files without having to fully load them into memory at once. </p>
<p>I don't know the details of the SHA-1 implementation and therefore would like to know if it is even possible to do that. </p>
<p>If you know the SAX XML parser, then what I look for would be something similar: Computing the SHA-1 checksum by only always loading a small part into memory at a time.</p>
<p>All the examples I found, at least in Java, always depend on fully loading the file/byte array/string into memory. </p>
<p>If you even know implementations (any language), then please let me know!</p>
","71","646","<java><algorithm><memory><stream><sha1>","2010-03-22 21:44:22","FALSE","FALSE","2496023","2010-03-23 13:54:54","6","<p>Yes, it's entirely possible. SHA-1 is a block algorithm, so it operates on one block at a time. The exact block size varies with the size of hash you're producing, but it's always quite small (e.g., 20 - 50 bytes or so). That, of course, is assuming you mean to include SHA-1 256, 384 and/or 512 (aka SHA-256, SHA-384 and SHA-512). If you're only including the original 160-bit version, then the block size is always 20 bytes (160 bits).</p>
<p>Edit: oops -- rereading the spec, the block sizes are 512 bits for SHA-1, SHA-224, SHA-256, and 1024 bits for SHA-384 and SHA-512. Thanks Charles!</p>
<p>Edit2: I almost forgot about the part where he's looking for source code, not just advice. Here's some code. First a header:</p>
<pre><code>// Sha.h:
#ifndef SHA_1_H_INCLUDED
#define SHA_1_H_INCLUDED
// This is a relatively straightforward implementation of SHA-1. It makes no particular
// attempt at optimization, instead aiming toward easy verification against the standard.
// To that end, many of the variable names are identical to those used in FIPS 180-2 and
// FIPS 180-3.
//
// The code should be fairly portable, within a few limitations:
// 1. It requires that 'char' have 8 bits. In theory this is avoidable, but I don't think
// it's worth the bother.
// 2. It only deals with inputs in (8-bit) bytes. In theory, SHA-1 can deal with a number of
// bits that's not a multiple of 8, but I've never needed it. Since the padding always results
// in a byte-sized stream, the only parts that would need changing would be reading and padding
// the input. The main hashing portion would be unaffected.
//
// Compiles cleanly with:
// MS VC++ 9.0SP1 (x86 or x64): -W4 -Za
// gc++ 3.4: -ansi -pedantic -Wall
// comeau 4.3.3: --vc71
// Appears to work corectly in all cases.
// You can't use maximum warnings with Comeau though -- this code itself doesn't give problems
// (that I know of) but Microsoft's headers give it *major* heartburn.
//
//
// Written by Jerry Coffin, February 2008
//
// You can use this software any way you want to, with following limitations
// (shamelessly stolen from the Boost software license):
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// If you put this to real use, I'd be happy to hear about it. If you find a bug,
// I'd be interested in hearing about that too. There's even a pretty good chance
// that I'll try to fix it, though I certainly can't guarantee that.
//
#include &lt;algorithm&gt;
#include &lt;vector&gt;
#include &lt;string&gt;
#include &lt;assert.h&gt;
#include &lt;iostream&gt;
#include &lt;sstream&gt;
#include &lt;iomanip&gt;
#if defined(_MSC_VER) &amp;&amp; _MSC_VER &lt; 1600
typedef unsigned int uint32_t;
typedef unsigned __int64 uint64_t;
#else
#include &lt;stdint.h&gt;
#endif
namespace crypto {
namespace {
struct ternary_operator {
virtual uint32_t operator()(uint32_t x, uint32_t y, uint32_t z) = 0;
};
}
class sha1 {
static const size_t hash_size = 5;
static const size_t min_pad = 64;
static const size_t block_bits = 512;
static const size_t block_bytes = block_bits / 8;
static const size_t block_words = block_bytes / 4;
std::vector&lt;uint32_t&gt; K;
std::vector&lt;uint32_t&gt; H;
std::vector&lt;uint32_t&gt; W;
std::vector&lt;ternary_operator *&gt; fs;
uint32_t a, b, c, d, e, T;
static const size_t block_size = 16;
static const size_t bytes_per_word = 4;
size_t total_size;
// hash a 512-bit block of input.
//
void hash_block(std::vector&lt;uint32_t&gt; const &amp;block);
// Pad the input to a multiple of 512 bits, and add the length
// in binary to the end.
static std::string pad(std::string const &amp;input, size_t size);
// Turn 64 bytes into a block of 16 uint32_t's.
std::vector&lt;uint32_t&gt; make_block(std::string const &amp;in);
public:
// Construct a SHA-1 object. More expensive that typical
// ctor, but not expected to be copied a lot or anything
// like that, so it should be fairly harmless.
sha1();
// The two ways to provide input for hashing: as a stream or a string.
// Either way, you get the result as a vector&lt;uint32_t&gt;. It's a fairly
// small vector, so even if your compiler doesn't do return-value
// optimization, the time taken for copying it isn't like to be
// significant.
//
std::vector&lt;uint32_t&gt; operator()(std::istream &amp;in);
std::vector&lt;uint32_t&gt; operator()(std::string const &amp;input);
friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, sha1 const &amp;s);
};
}
#endif
</code></pre>
<p>And the implementation:</p>
<pre><code>// Sha1.cpp:
#include ""sha.h""
// Please see comments in sha.h for licensing information, etc.
//
// Many people don't like the names I usually use for namespaces, so I've kept this one
// short and simple.
//
namespace crypto {
namespace {
uint32_t ROTL(uint32_t const &amp;value, unsigned bits) {
uint32_t mask = (1 &lt;&lt; bits) - 1;
return value &lt;&lt; bits | (value &gt;&gt; (32-bits))&amp;mask;
}
struct f1 : ternary_operator {
uint32_t operator()(uint32_t x, uint32_t y, uint32_t z) {
return (x &amp; y) ^ (~x&amp;z);
}
};
struct f2 : ternary_operator {
uint32_t operator()(uint32_t x, uint32_t y, uint32_t z) {
return x ^ y ^ z;
}
};
struct f3 : ternary_operator {
uint32_t operator()(uint32_t x, uint32_t y, uint32_t z) {
return (x&amp;y) ^ (x&amp;z) ^ (y&amp;z);
}
};
uint32_t word(int a, int b, int c, int d) {
a &amp;= 0xff;
b &amp;= 0xff;
c &amp;= 0xff;
d &amp;= 0xff;
int val = a &lt;&lt; 24 | b &lt;&lt; 16 | c &lt;&lt; 8 | d;
return val;
}
}
// hash a 512-bit block of input.
//
void sha1::hash_block(std::vector&lt;uint32_t&gt; const &amp;block) {
assert(block.size() == block_words);
int t;
std::copy(block.begin(), block.end(), W.begin());
for (t=16; t&lt;80; t++) {
W[t] = ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
}
a = H[0]; b = H[1]; c = H[2]; d = H[3]; e = H[4];
for (t=0; t&lt;80; t++) {
T = ROTL(a, 5) + (*fs[t])(b, c, d) + e + K[t] + W[t];
e = d;
d = c;
c = ROTL(b, 30);
b = a;
a = T;
}
H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e;
}
// Pad the input to a multiple of 512 bits, and put the length
// in binary at the end.
std::string sha1::pad(std::string const &amp;input, size_t size) {
size_t length = size * 8 + 1;
size_t remainder = length % block_bits;
size_t pad_len = block_bits-remainder;
if (pad_len &lt; min_pad)
pad_len += block_bits;
++pad_len;
pad_len &amp;= ~7;
std::string padding(pad_len/8, '\0');
for (size_t i=0; i&lt;sizeof(padding.size()); i++)
padding[padding.size()-i-1] = (length-1) &gt;&gt; (i*8) &amp; 0xff;
padding[0] |= (unsigned char)0x80;
std::string ret(input+padding);
return ret;
}
// Turn 64 bytes into a block of 16 uint32_t's.
std::vector&lt;uint32_t&gt; sha1::make_block(std::string const &amp;in) {
assert(in.size() &gt;= block_bytes);
std::vector&lt;uint32_t&gt; ret(block_words);
for (size_t i=0; i&lt;block_words; i++) {
size_t s = i*4;
ret[i] = word(in[s], in[s+1], in[s+2], in[s+3]);
}
return ret;
}
// Construct a SHA-1 object. More expensive that typical
// ctor, but not expected to be copied a lot or anything
// like that, so it should be fairly harmless.
sha1::sha1() : K(80), H(5), W(80), fs(80), total_size(0) {
static const uint32_t H0[] = {
0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0
};
static const uint32_t Ks[] = {
0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6
};
std::copy(H0, H0+hash_size, H.begin());
std::fill_n(K.begin()+00, 20, Ks[0]);
std::fill_n(K.begin()+20, 20, Ks[1]);
std::fill_n(K.begin()+40, 20, Ks[2]);
std::fill_n(K.begin()+60, 20, Ks[3]);
static f1 sf1;
static f2 sf2;
static f3 sf3;
std::fill_n(fs.begin()+00, 20, &amp;sf1);
std::fill_n(fs.begin()+20, 20, &amp;sf2);
std::fill_n(fs.begin()+40, 20, &amp;sf3);
std::fill_n(fs.begin()+60, 20, &amp;sf2);
}
// The two ways to provide input for hashing: as a stream or a string.
// Either way, you get the result as a vector&lt;uint32_t&gt;. It's a fairly
// small vector, so even if your compiler doesn't do return-value
// optimization, the time taken for copying it isn't like to be
// significant.
//
std::vector&lt;uint32_t&gt; sha1::operator()(std::string const &amp;input) {
std::string temp(pad(input, total_size + input.size()));
std::vector&lt;uint32_t&gt; block(block_size);
size_t num = temp.size()/block_bytes;
for (unsigned block_num=0; block_num&lt;num; block_num++) {
size_t s;
for (size_t i=0; i&lt;block_size; i++) {
s = block_num*block_bytes+i*4;
block[i] = word(temp[s], temp[s+1], temp[s+2], temp[s+3]);
}
hash_block(block);
}
return H;
}
std::vector&lt;uint32_t&gt; sha1::operator()(std::istream &amp;in) {
char raw_block[65];
while (in.read(raw_block, block_bytes)) {
total_size += block_bytes;
std::string b(raw_block, in.gcount());
hash_block(make_block(b));
}
std::string x(raw_block, in.gcount());
return operator()(x);
}
std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, sha1 const &amp;s) {
// Display a SHA-1 result in hex.
for (size_t i=0; i&lt;(s.H).size(); i++)
os &lt;&lt; std::fixed &lt;&lt; std::setprecision(8) &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; (s.H)[i] &lt;&lt; "" "";
return os &lt;&lt; std::dec &lt;&lt; std::setfill(' ') &lt;&lt; ""\n"";
}
}
#ifdef TEST
#include &lt;iostream&gt;
#include &lt;iomanip&gt;
#include &lt;string&gt;
#include &lt;sstream&gt;
// A minimal test harness to check that it's working correctly. Strictly black-box
// testing, with no attempt at things like coverage analysis. Nonetheless, I believe
// it should cover most of the code -- the core hashing code all gets used for every
// possible value. The padding code should be tested fairly thoroughly as well -- the
// first test is a fairly simple case, and the second the more complex one (where the
// padding requires adding another block).
class tester {
bool verify(uint32_t *test_val, std::vector&lt;uint32_t&gt; const &amp;hash, std::ostream &amp;os) {
// Verify that a result matches a test value and report result.
for (size_t i=0; i&lt;hash.size(); i++)
if (hash[i] != test_val[i]) {
os &lt;&lt; ""Mismatch. Expected: "" &lt;&lt; test_val[i] &lt;&lt; "", but found: "" &lt;&lt; hash[i] &lt;&lt; ""\n"";
return false;
}
os &lt;&lt; ""Message digest Verified.\n\n"";
return true;
}
public:
bool operator()(uint32_t *test_val, std::string const &amp;input) {
std::cout &lt;&lt; ""Testing hashing from string:\n\"""" &lt;&lt; input &lt;&lt; ""\""\n"";
crypto::sha1 hasher1;
std::vector&lt;uint32_t&gt; hash = hasher1(input);
std::cout &lt;&lt; ""Message digest is:\n\t"" &lt;&lt; hasher1;
bool verified = verify(test_val, hash, std::cerr);
crypto::sha1 hasher2;
std::cout &lt;&lt; ""Testing hashing from Stream:\n"";
std::istringstream buf(input);
hash = hasher2(buf);
std::cout &lt;&lt; ""Message digest is:\n\t"" &lt;&lt; hasher2;
return verified &amp; verify(test_val, hash, std::cerr);
}
};
int main() {
// These test values and results come directly from the FIPS pub.
//
char const *input1 = ""abc"";
char const *input2 = ""abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"";
uint32_t result1[] = {0xA9993E36, 0x4706816A, 0xBA3E2571, 0x7850C26C, 0x9CD0D89D};
uint32_t result2[] = {0x84983E44, 0x1C3BD26E, 0xBAAE4AA1, 0xF95129E5, 0xE54670F1 };
bool correct = tester()(result1, input1);
correct &amp;= tester()(result2, input2);
if (correct)
std::cerr &lt;&lt; ""All Tests passed!\n"";
else
std::cerr &lt;&lt; ""Test Failed!\n"";
}
#elif defined(MAIN)
#include &lt;sstream&gt;
#include &lt;fstream&gt;
#include &lt;iostream&gt;
int main(int argc, char **argv) {
if (argc &lt; 2) {
std::cerr &lt;&lt; ""Usage: sha1 [filename]\n"";
return EXIT_FAILURE;
}
for (int i=1; i&lt;argc; i++) {
crypto::sha1 hash;
std::ifstream in(argv[i], std::ios_base::binary);
if (in.good()) {
hash(in);
std::cout &lt;&lt; ""SHA-1("" &lt;&lt; argv[i] &lt;&lt; "") = "" &lt;&lt; hash &lt;&lt; ""\n"";
}
}
return 0;
}
#endif
</code></pre>
","13253","4","2","2","2010-03-22 21:49:40","5","TRUE","243602","0"
"http://stackoverflow.com/users/1060880","http://stackoverflow.com/questions/17479944","http://stackoverflow.com/questions/17479944/#17480086","2013-07-05 07:44:13","5","588","0","2","partitioning an float array into similar segments (clustering)","<p>I have an array of floats like this:</p>
<pre><code>[1.91, 2.87, 3.61, 10.91, 11.91, 12.82, 100.73, 100.71, 101.89, 200]
</code></pre>
<p>Now, I want to partition the array like this:</p>
<pre><code>[[1.91, 2.87, 3.61] , [10.91, 11.91, 12.82] , [100.73, 100.71, 101.89] , [200]]
</code></pre>
<p>// [200] will be considered as an outlier because of less cluster support </p>
<p>I have to find this kind of segment for several arrays and I don't know what should be the partition size. I tried to do it by using <a href=""http://en.wikipedia.org/wiki/Hierarchical_clustering"" rel=""nofollow"">hierarchical clustering (Agglomerative)</a> and it gives satisfactory results for me. However, issue is, I was suggested not to use clustering algorithms for one-dimensional problem as their is no theoretical justification (as they are for multidimensional data) to do that.</p>
<p>I spent lots of time to find solution. However, suggestions seem quite different like: <a href=""http://stackoverflow.com/questions/16659242/cluster-one-dimensional-data-using-pvclust"">this</a> and <a href=""http://stackoverflow.com/questions/11513484/1d-number-array-clustering"">this</a> VS. <a href=""http://stackoverflow.com/questions/14077110/efficiently-grouping-similar-numbers-together"">this</a> and <a href=""http://stackoverflow.com/questions/6147466/what-clustering-algorithm-to-use-on-1-d-data"">this</a> and <a href=""http://stackoverflow.com/questions/7869609/cluster-one-dimensional-data-optimally"">this</a>.</p>
<p>I found another suggestion rather than clustering i.e. <a href=""http://en.wikipedia.org/wiki/Jenks_natural_breaks_optimization#cite_ref-Jenks_1-1"" rel=""nofollow"">natural breaks optimization</a>. However, this also needs to declare the partition number like K-means (right ?).</p>
<p>It is quite confusing (specially because I have to perform those kind of segmentation on several arrays and it is impossible to know the optimal partition number).</p>
<p>Are there any ways to find partitions (thus we can reduce the variance within partitions and maximize the variance between partitions) with some theoretical justification?</p>
<p>Any pointers to article/papers (if available C/C++/Java implementation) with some theoretical justification will be very helpful for me.</p>
","62","2284","<java><c++><algorithm><cluster-analysis><data-partitioning>","2013-07-05 01:33:18","TRUE","FALSE","17480086","2013-07-05 02:41:37","5","<p>I think I'd sort the data (if it's not already), then take adjacent differences. Divide the differences by the smaller of the numbers it's a difference between to get a percentage change. Set a threshold and when the change exceeds that threshold, start a new ""cluster"".</p>
<p>Edit: Quick demo code in C++:</p>
<pre><code>#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;
#include &lt;iterator&gt;
#include &lt;numeric&gt;
#include &lt;functional&gt;
int main() {
std::vector&lt;double&gt; data{
1.91, 2.87, 3.61, 10.91, 11.91, 12.82, 100.73, 100.71, 101.89, 200
};
// sort the input data
std::sort(data.begin(), data.end());
// find the difference between each number and its predecessor
std::vector&lt;double&gt; diffs;
std::adjacent_difference(data.begin(), data.end(), std::back_inserter(diffs));
// convert differences to percentage changes
std::transform(diffs.begin(), diffs.end(), data.begin(), diffs.begin(),
std::divides&lt;double&gt;());
// print out the results
for (int i = 0; i &lt; data.size(); i++) {
// if a difference exceeds 40%, start a new group:
if (diffs[i] &gt; 0.4)
std::cout &lt;&lt; ""\n"";
// print out an item:
std::cout &lt;&lt; data[i] &lt;&lt; ""\t"";
}
return 0;
}
</code></pre>
<p>Result:</p>
<pre><code>1.91 2.87 3.61
10.91 11.91 12.82
100.71 100.73 101.89
200
</code></pre>
","1475","3","2","2","2013-07-05 01:57:34","24","TRUE","243602","0"
"http://stackoverflow.com/users/479805","http://stackoverflow.com/questions/4101924","http://stackoverflow.com/questions/4101924/#4105155","2013-06-16 11:49:01","62","4221","30","9","Functional programming - is immutability expensive?","<h3>Request:</h3>
<ol>
<li>The question is in two parts. The first is conceptual, comparing functional and
imperative programming from the perspective of cost of immutability. Second, about specifics of Java/scala.</li>
<li><a href=""http://en.wikipedia.org/wiki/Quicksort"">Quicksort</a> is taught and generally implemented as an in-memory sort. No arguments there. But, how does one implement such a thing in a PURE functional way? Specifically in Scala?</li>
</ol>
<h3>Question:</h3>
<p>Coming from a heavy imperative background (C++, Java). I have been exploring functional programming, more specifically Scala. Though, being new to functional programming, I thought it might be a good idea to ask this question here now.</p>
<p>Some of the concepts of functional programming (I am sure I am missing out a lot):</p>
<ol>
<li>Functions as first class citizens.</li>
<li>Functions do not have side effects and hence <a href=""http://en.wikipedia.org/wiki/Immutable_object"">immutable objects</a>.</li>
<li>Concurrency becomes easy as a result of 2)</li>
</ol>
<p>Even though modern <a href=""http://en.wikipedia.org/wiki/Java_virtual_machine"">JVMs</a> are extremely efficient with object creation and <a href=""http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29"">garbage collection</a> is very inexpensive for short lived objects, it's probably still better to minimize object creation right? At least in a single-threaded application where concurrency and locking is not an issue. Since Scala is a hybrid, I know I can write imperative code with mutable objects if necessary. But, as someone who has spent a lot of years trying to reuse objects and minimize allocation. I would like a good understanding of the counter school of thought.</p>
<p>As a specific case, I was a little surprised by this code snippet in <a href=""http://www.ibm.com/developerworks/java/library/j-scala03268.html"">this tutorial</a> by <a href=""http://www.tedneward.com/about.aspx"">Ted Neward</a> (seems like a prominent name in the Scala community). It has a Java version of quicksort and then gives a neat looking Scala implementation of the same.</p>
<p>Here is my attempt to benchmark the implementations. I haven't done detailed profiling. But, my guess is that the Scala version is slower because the number of objects allocated is linear (one per recursion call). Is there any way chance that tail call optimizations can come into play? If I am right, Scala supports tail call optimizations for self-recursive calls. So, it should only be helping it. I am using Scala 2.8.</p>
<h3>Java version</h3>
<pre><code>public class QuickSortJ {
public static void sort(int[] xs) {
sort(xs, 0, xs.length -1 );
}
static void sort(int[] xs, int l, int r) {
int pivot = xs[(l+r)/2];
int a = l; int b = r;
while (a &lt;= b){
while (xs[a] &lt; pivot) { a = a + 1; }
while (xs[b] &gt; pivot) { b = b - 1; }
if (a &lt;= b) {
swap(xs, a, b);
a = a + 1;
b = b - 1;
}
}
if (l &lt; b) sort(xs, l, b);
if (b &lt; r) sort(xs, a, r);
}
static void swap(int[] arr, int i, int j) {
int t = arr[i]; arr[i] = arr[j]; arr[j] = t;
}
}
</code></pre>
<h3>Scan version</h3>
<pre><code>object QuickSortS {
def sort(xs: Array[Int]): Array[Int] =
if (xs.length &lt;= 1) xs
else {
val pivot = xs(xs.length / 2)
Array.concat(
sort(xs filter (pivot &gt;)),
xs filter (pivot ==),
sort(xs filter (pivot &lt;)))
}
}
</code></pre>
<h3>Scala Code to compare implementations</h3>
<pre><code>import java.util.Date
import scala.testing.Benchmark
class BenchSort(sortfn: (Array[Int]) =&gt; Unit, name:String) extends Benchmark {
val ints = new Array[Int](100000);
override def prefix = name
override def setUp = {
val ran = new java.util.Random(5);
for (i &lt;- 0 to ints.length - 1)
ints(i) = ran.nextInt();
}
override def run = sortfn(ints)
}
val benchImmut = new BenchSort( QuickSortS.sort , ""Immutable/Functional/Scala"" )
val benchMut = new BenchSort( QuickSortJ.sort , ""Mutable/Imperative/Java "" )
benchImmut.main( Array(""5""))
benchMut.main( Array(""5""))
</code></pre>
<h3>Results</h3>
<p>Time in milliseconds for five consecutive runs</p>
<pre><code>Immutable/Functional/Scala 467 178 184 187 183
Mutable/Imperative/Java 51 14 12 12 12
</code></pre>
","51","4481","<java><scala><functional-programming>","2010-11-04 22:16:48","TRUE","FALSE","4105155","2010-11-05 13:49:51","71","<p>Since there are a few <strong>misconceptions</strong> flying around here, I’d like to clarify some points.</p>
<ul>
<li><p>The “in-place” quicksort isn’t really in-place (and quicksort is <em>not</em> by definition in-place). It requires additional storage in the form of stack space for the recursive step, which is in the order of <em>O</em>(log <em>n</em>) in the best case, but <em>O</em>(<i>n</i>) in the worst case.</p></li>
<li><p>Implementing a functional variant of quicksort that operates on arrays defeats the purpose. Arrays are never immutable.</p></li>
<li><p>The “proper” functional implementation of quicksort uses immutable lists. It is of course not in-place but it’s got the same worst-case asymptotic runtime (<em>O</em>(<i>n</i>^2)) and space complexity (<em>O</em>(<i>n</i>)) as the procedural in-place version.</p>
<p>On average, its running time is <em>still</em> on par with that of the in-place variant (<em>O</em>(<i>n</i> log <em>n</em>)). Its space complexity, however, is still <em>O</em>(<i>n</i>).</p></li>
</ul>
<hr>
<p>There are <em>two obvious disadvantages</em> of a functional quicksort implementation. In the following, let’s consider this reference implementation in Haskell (I don’t know Scala …) from the <a href=""http://www.haskell.org/haskellwiki/Introduction"">Haskell introduction</a>:</p>
<pre><code>qsort [] = []
qsort (x:xs) = qsort lesser ++ [x] ++ qsort greater
where lesser = (filter (&lt; x) xs)
greater = (filter (&gt;= x) xs)
</code></pre>
<ol>
<li><p>The first disadvantage is <em>the choice of the pivot element</em>, which is very inflexible. The strength of modern quicksort implementations relies heavily on a smart choice of the pivot (compare <a href=""http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.14.8162"">“Engineering a sort function” by Bentley <em>et al.</em></a>). The above algorithm is poor in that regard, which degrades average performance considerably.</p></li>
<li><p>Secondly, this algorithm uses <em>list concatenation</em> (instead of list construction) which is an <em>O</em>(<i>n</i>) operation. This doesn’t impact on the asymptotic complexity but it’s a measurable factor.</p></li>
</ol>
<p>A third disadvantage is somewhat hidden: unlike the “in-place” variant, this implementation <em>continually requests memory from the heap</em> for the cons cells of the list and potentially scatters memory all over the place. As a result, this algorithm has a very <em>poor cache locality</em>. I don’t know whether smart allocators in modern functional programming languages can mitigate this – but on modern machines, cache misses have become a major performance killer.</p>
<hr>
<p><strong>What’s the conclusion?</strong> Unlike others, I wouldn’t say that quicksort is inherently imperative and that’s why it performs badly in an FP environment. Quite on the contrary, I would argue that quicksort is a perfect example of a functional algorithm: it translates seamlessly into an immutable environment, its asymptotic running time and space complexity are on par with the procedural implementation, and even its procedural implementation employs recursion.</p>
<p>But this algorithm <em>still</em> performs worse when constrained to an immutable domain. The reason for this is that the algorithm has the peculiar property of benefitting from a lot of (sometimes low-level) fine-tuning that can only be efficiently performed on arrays. A naive description of the quicksort misses all these intricacies (both in the functional and in the procedural variant).</p>
<p>After reading “Engineering a sort function” I can no longer consider quicksort an elegant algorithm. Implemented efficiently, it is a clunky mess, an engineer’s piece of work, not an artist’s (not to devalue engineering! this has its own aesthetic).</p>
<hr>
<p>But I would also like to point out that this point is particular to quicksort. Not every algorithm is amenable to the same sort of low-level tweaking. A lot of algorithms and data structures really <em>can</em> be expressed without performance loss in an immutable environment.</p>
<p>And immutability can even <em>decrease</em> performance costs by removing the need of costly copies or cross-thread synchronizations.</p>
<p>So, to answer the original question, “<strong>is immutability expensive?</strong>” – In the particular case of quicksort, there is a cost that is indeed a result of immutability. But in general, <strong>no</strong>.</p>
","4491","15","1","3","2010-11-05 10:45:02","749","TRUE","238334","0"
"http://stackoverflow.com/users/36744","http://stackoverflow.com/questions/282459","http://stackoverflow.com/questions/282459/#282469","2014-06-25 14:11:44","39","33379","6","4","What is the C# equivalent to Java's instanceof and isInstance()?","<p>I know of <code>is</code> and <code>as</code> for <code>instanceof</code>, but what about the reflective <a href=""http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#isInstance(java.lang.Object)"">isInstance()</a> method?</p>
","64","237","<c#><java><reflection><introspection>","2008-11-11 23:09:50","FALSE","FALSE","282469","2008-11-11 23:33:52","21","<pre><code>bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());
</code></pre>
","91","0","1","3","2008-11-11 23:13:08","4","TRUE","238334","0"
"http://stackoverflow.com/users/85","http://stackoverflow.com/questions/27532","http://stackoverflow.com/questions/27532/#27536","2014-02-14 19:50:31","12","13703","8","4","Generating gradients programmatically?","<p>Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is <a href=""http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/"" rel=""nofollow"">this blog entry</a>, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.</p>
","38","586","<java><colors><rgb><gradient>","2008-08-26 07:57:06","FALSE","FALSE","27536","2008-08-26 08:31:44","16","<p>you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage <em>p</em> of the first colour and percentage 1 - <em>p</em> of the second:</p>
<pre><code>R = firstCol.R * p + secondCol.R * (1 - p)
</code></pre>
<p>There's <a href=""http://stackoverflow.com/questions/25007/conditional-formatting-percentage-to-color-conversion"">another question</a> related to this.</p>
<p>There are other methods of interpolation that sometimes work better. For example, using a <a href=""http://en.wikipedia.org/wiki/Sigmoid_function"">bell-shaped (sigmoidal)</a> interpolation function makes the transition smoother.</p>
<p>/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.</p>
<p>In Java, you could use the <a href=""http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GradientPaint.html""><code>GradientPaint</code></a>.</p>
","1102","5","1","1","2008-08-26 08:00:29","3","TRUE","238334","0"
"http://stackoverflow.com/users/180516","http://stackoverflow.com/questions/1751275","http://stackoverflow.com/questions/1751275/#1751291","2010-02-18 21:12:04","2","798","0","4","Are there any plans for Java to add generic collection covariance?","<p>I was trying to write some code that looked like this:</p>
<pre><code>public List&lt;IObject&gt; getObject(){
ArrayList&lt;ConcreteObject&gt; objects = new ArrayList&lt;ConcreteObject&gt;();
return objects;
}
</code></pre>
<p>(Where ConcreteObject implements IObject)</p>
<p>This doesn't work at all. It gives a compiler error. Does Java have plans to support this in the future? What is the best workaround until then? What I ended up doing was:</p>
<pre><code>public List&lt;IObject&gt; getObject(){
List&lt;IObject&gt; objects = new ArrayList&lt;IObject&gt;();
return objects;
}
</code></pre>
<p>This works and maybe there aren't really any bad side effects of doing it this way. Is this the generally accepted best approach?</p>
","66","749","<java><collections><covariance>","2009-11-17 19:45:08","TRUE","FALSE","1751291","2009-11-18 12:55:52","12","<p>Java already supports this feature, you just need to use it. For a primer, read the <a href=""http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html"">Wildcards tutorial</a> from Sun.</p>
<p>What you want is the following:</p>
<pre><code>public List&lt;? extends IObject&gt; getObject(){
ArrayList&lt;ConcreteObject&gt; objects = new ArrayList&lt;ConcreteObject&gt;();
return objects;
}
</code></pre>
<p>Alternatively, may use an unsafe cast:</p>
<pre><code>public &lt;T extends IObject&gt; List&lt;T&gt; getObject(){
ArrayList&lt;T&gt; objects = (ArrayList&lt;T&gt;) new ArrayList&lt;ConcreteObject&gt;();
return objects;
}
</code></pre>
<p>… but this method is rather brittle and will throw a runtime exception (except of signalling a compile error) when you try to access its elements with an invalid type:</p>
<pre><code>@SuppressWarnings(""unchecked"")
public &lt;T extends IObject&gt; List&lt;T&gt; getObject(){
ArrayList&lt;T&gt; objects = (ArrayList&lt;T&gt;) new ArrayList&lt;ConcreteObject&gt;();
objects.add(new ConcreteObject());
return objects;
}
List&lt;OtherConcreteObject&gt; objects = getObject(); // Works.
OtherConcreteObject obj = OtherConcreteObject.get(0); // Throws CCE.
</code></pre>
<p>This will result in the followin <code>ClassCastException</code> at runtime: “<code>ConcreteObject</code> cannot be cast to <code>OtherConcreteObject</code>” – which is rather bad because as the code stands above, it <em>should</em> succeed.</p>
<p>For that reason you should try to avoid this method.</p>
","1556","6","3","7","2009-11-17 19:47:54","2","TRUE","238334","0"
"http://stackoverflow.com/users/301829","http://stackoverflow.com/questions/2546078","http://stackoverflow.com/questions/2546078/#2546186","2014-04-12 04:13:32","34","33885","6","7","Java: random long number in 0 <= x < n range","<p>Random class has a method to generate random int in a given range. For example:</p>
<pre><code>Random r = new Random();
int x = r.nextInt(100);
</code></pre>
<p>This would generate an int number more or equal to 0 and less than 100. I'd like to do exactly the same with long number.</p>
<pre><code>long y = magicRandomLongGenerator(100);
</code></pre>
<p>Random class has only nextLong(), but it doesn't allow to set range.</p>
","44","436","<java><random><range><long-integer>","2010-03-30 14:41:21","TRUE","FALSE","2546186","2010-03-30 15:01:45","33","<p>According to <a href=""http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html"">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html</a> nextInt is implemented as</p>
<pre><code> public int nextInt(int n) {
if (n&lt;=0)
throw new IllegalArgumentException(""n must be positive"");
if ((n &amp; -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) &gt;&gt; 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) &lt; 0);
return val;
}
</code></pre>
<p>So we may modify this to perform nextLong:</p>
<pre><code>long nextLong(Random rng, long n) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() &lt;&lt; 1) &gt;&gt;&gt; 1;
val = bits % n;
} while (bits-val+(n-1) &lt; 0L);
return val;
}
</code></pre>
","923","2","2","6","2010-03-30 14:55:20","14","TRUE","237899","0"
"http://stackoverflow.com/users/964145","http://stackoverflow.com/questions/13792110","http://stackoverflow.com/questions/13792110/#13792132","2014-03-12 15:05:19","9","31427","1","5","Java Enum return Int","<p>I'm having trouble declaring an enum. I've read up on the documentation but can't figure it out.</p>
<p>What I'm trying to create is an enum for a 'DownloadType', where there are 3 download types (AUDIO, VIDEO, AUDIO_AND_VIDEO).</p>
<p>I have implemented the code as follows:</p>
<pre><code>private enum DownloadType {
AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
private final int value;
private DownloadType(int value) {
this.value = value;
}
}
</code></pre>
<p>This works fine if I then use it like this:</p>
<pre><code>DownloadType.AUDIO_AND_VIDEO.value;
</code></pre>
<p>However, I would like it so that I don't have to ask for the 'value'. I may be mistaken, but this is the way several classes work in Java such as Font, for example to set a font style, you use:</p>
<pre><code>Font.PLAIN
</code></pre>
<p>Which returns an int value, we don't use:</p>
<pre><code>Font.PLAIN.value
</code></pre>
<p>I must have misunderstood something because I can't figure this out.</p>
<p>Thanks in advance everyone</p>
","20","1045","<java><enums>","2012-12-09 21:35:08","TRUE","FALSE","13792132","2013-09-12 20:52:33","27","<p><a href=""http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#PLAIN"">Font.PLAIN</a> is <em>not</em> an enum. It is just an <code>int</code>. If you need to take the value out of an enum, you can't avoid calling a method or using a <code>.value</code>, because enums are actually objects of its own type, not primitives.</p>
<p>If you truly only need an <code>int</code>, <em>and</em> you are already to accept that type-safety is lost the user may pass invalid values to your API, you <em>may</em> define those constants as <code>int</code> also:</p>
<pre><code>static class DownloadType {
public static final int AUDIO = 0;
public static final int VIDEO = 1;
public static final int AUDIO_AND_VIDEO = 2;
}
</code></pre>
<p>By the way, the <code>value</code> field is actually redundant because there is also an <code>.ordinal()</code> method, so you could define the <code>enum</code> as:</p>
<pre><code>enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }
</code></pre>
<p>and get the ""value"" using </p>
<pre><code>DownloadType.AUDIO_AND_VIDEO.ordinal()
</code></pre>
","1097","4","3","5","2012-12-09 21:39:52","4","TRUE","237899","0"
"http://stackoverflow.com/users/354027","http://stackoverflow.com/questions/2939023","http://stackoverflow.com/questions/2939023/#2939031","2012-05-12 07:38:38","8","763","1","7","What is the difference between += and =+?","<p>What is the difference between += and =+?
Specifically, in java, but in general also.</p>
","41","93","<java><syntax><operators><increment><unary-operator>","2010-05-30 14:33:50","FALSE","FALSE","2939031","2012-05-12 07:38:38","27","<pre><code>i += 4;
</code></pre>
<p>means</p>
<pre><code>i = i + 4; // increase i by 4.
</code></pre>
<p>While</p>
<pre><code>i =+ 4;
</code></pre>
<p>is equivalent to</p>
<pre><code>i = +4; // assign 4 to i. the unary plus is effectively no-op.
</code></pre>
<p>(See <a href=""http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.3"" rel=""nofollow"">http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.3</a> for what a unary + does.)</p>
","483","4","4","10","2010-05-30 14:35:56","2","TRUE","237899","0"
"http://stackoverflow.com/users/1357341","http://stackoverflow.com/questions/12438786","http://stackoverflow.com/questions/12438786/#12439093","2012-10-14 01:45:07","260","7506","61","5","try-finally block prevents StackOverflowError","<p>Take a look at the following two methods:</p>
<pre><code>public static void foo() {
try {
foo();
} finally {
foo();
}
}
public static void bar() {
bar();
}
</code></pre>
<hr>
<p>Running <code>bar()</code> clearly results in a <code>StackOverflowError</code>, but running <code>foo()</code> does not (the program just seems to run indefinitely). <em>Why is that?</em></p>
","45","410","<java><recursion><stackoverflow><stackoverflowerror><try-finally>","2012-09-15 15:49:19","TRUE","FALSE","12439093","2012-09-15 17:17:52","279","<p>It doesn't run forever. Each stack overflow causes the code to move to the finally block. The problem is that it will take a really, really long time. The order of time is O(2^N) where N is the maximum stack depth.</p>
<p>Imagine the maximum depth is 5</p>
<pre><code>foo() calls
foo() calls
foo() calls
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
finally
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
finally calls
foo() calls
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
finally
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
finally calls
foo() calls
foo() calls
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
finally
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
finally calls
foo() calls
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
finally
foo() calls
foo() which fails to call foo()
finally calls
foo() which fails to call foo()
</code></pre>
<p>To work each level into the finally block take twice as long an the stack depth could be
10,000 or more. If you can make 10,000,000 calls per second, this will take 10^3003 seconds or longer than the age of the universe. </p>
","1870","3","1","9","2012-09-15 16:25:23","36","TRUE","236279","0"
"http://stackoverflow.com/users/454049","http://stackoverflow.com/questions/11774099","http://stackoverflow.com/questions/11774099/#11774161","2014-05-10 11:24:26","166","25377","54","5","Legal identifiers in Java","<p>I am reading for SCJP and I have a question regarding this line:</p>
<blockquote>
<p>Identifiers must start with a letter, a currency character ($), or a
connecting character such as the underscore ( _ ). Identifiers cannot
start with a number!</p>
</blockquote>
<p>It states that a valid identifier name can start with a connecting character <strong>such as</strong> underscore. I thought underscores were the only valid option? What other <em>connecting characters</em> are there?</p>
","25","498","<java><identifier><scjp>","2012-08-02 08:54:26","FALSE","FALSE","11774161","2012-08-02 09:53:05","210","<p>Here is a list of connecting characters. These are characters used to connect words.</p>
<p><a href=""http://www.fileformat.info/info/unicode/category/Pc/list.htm"">http://www.fileformat.info/info/unicode/category/Pc/list.htm</a></p>
<pre><code>U+005F LOW LINE _
U+203F UNDERTIE ‿
U+2040 CHARACTER TIE ⁀
U+2054 INVERTED UNDERTIE ⁔
U+FE33 PRESENTATION FORM FOR VERTICAL LOW LINE ︳
U+FE34 PRESENTATION FORM FOR VERTICAL WAVY LOW LINE ︴
U+FE4D DASHED LOW LINE ﹍
U+FE4E CENTRELINE LOW LINE ﹎
U+FE4F WAVY LOW LINE ﹏
U+FF3F FULLWIDTH LOW LINE _
</code></pre>
<p>This compiles on Java 7.</p>
<pre><code>int _, ‿, ⁀, ⁔, ︳, ︴, ﹍, ﹎, ﹏, _;
</code></pre>
<hr>
<p>An example. In this case <code>tp</code> is the name of a column and the value for a given row.</p>
<pre><code>Column&lt;Double&gt; ︴tp︴ = table.getColumn(""tp"", double.class);
double tp = row.getDouble(︴tp︴);
</code></pre>
<hr>
<p>The following</p>
<pre><code>for (int i = Character.MIN_CODE_POINT; i &lt;= Character.MAX_CODE_POINT; i++)
if (Character.isJavaIdentifierStart(i) &amp;&amp; !Character.isAlphabetic(i))
System.out.print((char) i + "" "");
}
</code></pre>
<p>prints</p>
<p>$ _ ¢ £ ¤ ¥ ؋ ৲ ৳ ৻ ૱ ௹ ฿ ៛ ‿ ⁀ ⁔ ₠ ₡ ₢ ₣ ₤ ₥ ₦ ₧ ₨ ₩ ₪ ₫ € ₭ ₮ ₯ ₰ ₱ ₲ ₳ ₴ ₵ ₶ ₷ ₸ ₹ ꠸ ﷼ ︳ ︴ ﹍ ﹎ ﹏ ﹩ $ _ ¢ £ ¥ ₩</p>
","1344","7","4","18","2012-08-02 08:59:03","5","TRUE","236279","18"
"http://stackoverflow.com/users/60915","http://stackoverflow.com/questions/4937402","http://stackoverflow.com/questions/4937402/#4937591","2013-04-02 13:52:08","69","62283","16","9","Moving decimal places over in a double","<p>So I have a double set to equal 1234, I want to move a decimal place over to make it 12.34</p>
<p>So to do this I multiply .1 to 1234 two times, kinda like this</p>
<pre><code>double x = 1234;
for(int i=1;i&lt;=2;i++)
{
x = x*.1;
}
System.out.println(x);
</code></pre>
<p>This will print the result, ""12.340000000000002""</p>
<p>Is there a way, without simply formatting it to two decimal places, to have the double store 12.34 correctly?</p>
","38","451","<java><double><decimal>","2011-02-08 19:29:25","TRUE","FALSE","4937591","2012-01-14 01:25:02","162","<p>If you use <code>double</code> or <code>float</code>, you should use rounding or expect to see some rounding errors. If you can't do this, use <code>BigDecimal</code>.</p>
<p>The problem you have is that 0.1 is not an exact representation, and by performing the calculation twice, you are compounding that error.</p>
<p>However, 100 can be represented accurately, so try:</p>
<pre><code>double x = 1234;
x /= 100;
System.out.println(x);
</code></pre>
<p>which prints:</p>
<pre><code>12.34
</code></pre>
<p>This works because <code>Double.toString(d)</code> performs a small amount of rounding on your behalf, but it is not much. If you are wondering what it might look like without rounding:</p>
<pre><code>System.out.println(new BigDecimal(0.1));
System.out.println(new BigDecimal(x));
</code></pre>
<p>prints:</p>
<pre><code>0.100000000000000005551115123125782702118158340454101562
12.339999999999999857891452847979962825775146484375
</code></pre>
<p>In short, rounding is unavoidable for sensible answers in floating point whether you are doing this explicitly or not.</p>
<hr>
<p>Note: <code>x / 100</code> and <code>x * 0.01</code> are not exactly the same when it comes to rounding error. This is because the round error for the first expression depends on the values of x, whereas the <code>0.01</code> in the second has a fixed round error.</p>
<pre><code>for(int i=0;i&lt;200;i++) {
double d1 = (double) i / 100;
double d2 = i * 0.01;
if (d1 != d2)
System.out.println(d1 + "" != ""+d2);
}
</code></pre>
<p>prints</p>
<pre><code>0.35 != 0.35000000000000003
0.41 != 0.41000000000000003
0.47 != 0.47000000000000003
0.57 != 0.5700000000000001
0.69 != 0.6900000000000001
0.7 != 0.7000000000000001
0.82 != 0.8200000000000001
0.83 != 0.8300000000000001
0.94 != 0.9400000000000001
0.95 != 0.9500000000000001
1.13 != 1.1300000000000001
1.14 != 1.1400000000000001
1.15 != 1.1500000000000001
1.38 != 1.3800000000000001
1.39 != 1.3900000000000001
1.4 != 1.4000000000000001
1.63 != 1.6300000000000001
1.64 != 1.6400000000000001
1.65 != 1.6500000000000001
1.66 != 1.6600000000000001
1.88 != 1.8800000000000001
1.89 != 1.8900000000000001
1.9 != 1.9000000000000001
1.91 != 1.9100000000000001
</code></pre>
","2236","9","6","10","2011-02-08 19:48:30","19","TRUE","236279","10"
"http://stackoverflow.com/users/98975","http://stackoverflow.com/questions/2710651","http://stackoverflow.com/questions/2710651/#2710704","2010-04-26 12:52:37","5","1988","1","4","Java's TreeSet equivalent in Python?","<p>I recently came across some Java code that simply put some strings into a Java TreeSet, implemented a distance based comparator for it, and then made its merry way into the sunset to compute a given score to solve the given problem.</p>
<p>My questions,</p>
<ul>
<li><p>Is there an equivalent data structure available for Python?</p>
<ul>
<li>The Java treeset looks basically to be an ordered dictionary that can use a comparator of some sort to achieve this ordering.</li>
</ul></li>
<li><p>I see there's a <a href=""http://www.python.org/dev/peps/pep-0372/"" rel=""nofollow"">PEP for Py3K</a> for an OrderedDict, but I'm using 2.6.x. There are a bunch of ordered dict implementations out there - anyone in particular that can be recommended?</p></li>
</ul>
<p>PS, Just to add - I <em>could</em> probably import DictMixin or UserDict and implement my own sorted/ordered dictionary, AND make it happen through a comparator function - but that seems to be overkill.</p>
<p>Thanks.</p>
<hr>
<p>Update. Thanks for the answers. To elaborate a bit, lets say I've got a compare function thats defined like, (given a particular value ln),</p>
<pre><code>def mycmp(x1, y1, ln):
a = abs(x1-ln)
b = abs(y1-ln)
if a&lt;b:
return -1
elif a&gt;b:
return 1
else:
return 0
</code></pre>
<p>I'm a bit unsure about how I'd integrate this into the ordering given in the ordered dict <a href=""http://docs.python.org/dev/library/collections.html#collections.OrderedDict"" rel=""nofollow"">link given here..</a>. </p>
<p>Something like,</p>
<pre><code>OrderedDict(sorted(d.items(), cmp=mycmp(len)))
</code></pre>
<p>Ideas would be welcome. </p>
","36","1654","<java><python><data-structures><treeset>","2010-04-26 01:26:51","TRUE","FALSE","2710704","2010-04-26 12:52:37","2","<p>The Python 2.7 <a href=""http://docs.python.org/dev/library/collections.html#collections.OrderedDict"" rel=""nofollow"">docs for <code>collections.OrderedDict</code></a> has a link to a <a href=""http://code.activestate.com/recipes/576693/"" rel=""nofollow"">OrderedDict recipe</a> that runs on Python 2.4 or better.</p>
<p><strong>Edit:</strong> In regard to sorting: Use <code>key=</code> rather than <code>cmp=</code>. It tends to lead to <a href=""http://stackoverflow.com/questions/1972672/what-arguments-does-python-sort-function-have/1973688#1973688"">faster code</a> and moreover, the <code>cmp=</code> keyword has been eliminated in Python3.</p>
<pre><code>d={5:6,7:8,100:101,1:2,3:4}
print(d.items())
# [(1, 2), (3, 4), (100, 101), (5, 6), (7, 8)]
</code></pre>
<p>The code you posted for <code>mycmp</code> doesn't make it clear what you want passed as <code>x1</code>. Below, I assume x1 is supposed to be the <strong>value</strong> in each key-value pair. If so, you could do something like this:</p>
<pre><code>length=4
print(sorted(d.items(),key=lambda item: abs(item[1]-length) ))
# [(3, 4), (1, 2), (5, 6), (7, 8), (100, 101)]
</code></pre>
<p><code>key=...</code> is passed a function, <code>lambda item: abs(item[1]-length)</code>.
For each <code>item</code> in <code>d.items()</code>, the lambda function returns the number <code>abs(item[1]-length)</code>. This number acts as proxy for the item as far as sorting is concerned. See <a href=""http://wiki.python.org/moin/HowTo/Sorting"" rel=""nofollow"">this essay</a> for more information on sorting idioms in Python.</p>
<p>PS. <code>len</code> is a Python builtin function. So, so as to not clobber that <code>len</code>, I've changed the variable name to <code>length</code>.</p>
","1749","5","2","2","2010-04-26 01:47:41","21","TRUE","233718","0"
"http://stackoverflow.com/users/1329402","http://stackoverflow.com/questions/12370042","http://stackoverflow.com/questions/12370042/#12370212","2012-09-11 12:54:36","1","216","0","2","How do I get a value randomly from a list in Jython script?","<pre><code>lists = portTest.lists(arg1, arg2)
// this returns the lists from webservice in java
// public String[] list1;
// public String[] list2;public String[] list3;
// i want to get the random element in the list,
// not the first, second or any selected item.
elementinthelist = lists.list1[0]
</code></pre>
<p>How do i generate the random element from the list</p>
<p>I am writing a testscript in Jython. I am calling the service using Grinder tool </p>
","59","473","<java><python><jython><grinder>","2012-09-11 12:44:50","TRUE","FALSE","12370212","2012-09-11 12:54:36","3","<p>In Python, use <a href=""http://docs.python.org/library/random.html#random.choice"" rel=""nofollow"">random.choice</a>:</p>
<pre><code>import random
elementinthelist = random.choice(lists.list1)
</code></pre>
","209","1","1","1","2012-09-11 12:54:36","10","TRUE","233718","0"
"http://stackoverflow.com/users/12730","http://stackoverflow.com/questions/5157658","http://stackoverflow.com/questions/5157658/#5157805","2011-03-01 17:09:16","1","2161","0","1","Consume a Java Web Service through a C# Service Reference","<p>There are many questions about how to do this using a Web Reference in C#, but I know how to do that. What I'm trying to accomplish is to have a portable dll that consumes the Java Web Services that I can reference in my projects instead of duplicating the functionality. One of the things is that with Web References the <code>KeepAlive</code> of the request is set to <code>true</code>. That doesn't work for the environment I'm developing in and it has to be <code>false</code>. What I did with Web References is create an abstract class that inherits <code>SoapHttpClientProtocol</code> and change the Reference.cs to inherit from the abstract class. The abstract class looked like this:</p>
<pre><code>[System.Web.Services.WebServiceBinding(Name = ""JavaWebReferenceProxy"")]
public abstract class JavaWebReferenceProxy : SoapHttpClientProtocol
{
public JavaWebReferenceProxy()
{
base.Timeout = Settings.Instance.SoapTimeout;
}
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest rq = base.GetWebRequest(uri);
((HttpWebRequest)rq).KeepAlive = Settings.Instance.SoapKeepAlive;
return rq;
}
}
</code></pre>
<p>This allowed me to override the <code>GetWebRequest</code> and the constructor to set values that were in the web.config. I'm wondering how I can do this with a Service Reference to the Java Web Service. I've found some examples for the simplified <code>serviceModel</code> section in 4.0 (which is the framework I'm using), but I need to specify the url and the timeout as well. I'm not sure if I can use the simplified <code>serviceModel</code> or if I need to use the full implementation. I also am unsure if I can use the Service Reference at all. I'm just looking for a little guidance if anyone has implemented something like this. </p>
<p>What should the <code>serviceModel</code> section look like in my config file? The 3 things I need to be able to specify is the URL, the Timeout and the keep-alive. Thanks in advance.</p>
","57","2036","<c#><java><web-services><web-config><wcf-binding>","2011-03-01 16:56:46","TRUE","FALSE","5157805","2011-03-01 17:09:16","2","<p>You need custom binding for that. Try this:</p>
<pre><code>&lt;system.serviceModel&gt;
&lt;bindings&gt;
&lt;customBinding&gt;
&lt;binding name=""myBinding"" sendTimout=""00:05:00""&gt;
&lt;textMessageEncoding messageVersion=""Soap11"" /&gt;
&lt;httpTransport keepAliveEnabled=""false"" /&gt;
&lt;/binding&gt;
&lt;/customBinding&gt;
&lt;/bindings&gt;
&lt;client&gt;
&lt;endpoint name=""myEndpointName"" address=""http://..."" binding=""customBinding""
bindingConfiguration=""myBinding"" contract=""MyReference.IMyService"" /&gt;
&lt;/client&gt;
&lt;/system.serviceModel&gt;
</code></pre>
<p>SendTimeout should set timeout for operation completion (including receiving response), keepAliveEnebled controls persistent HTTP connection and address in edpoint is address of the service.</p>
","835","2","1","1","2011-03-01 17:09:16","13","TRUE","223483","0"
"http://stackoverflow.com/users/812303","http://stackoverflow.com/questions/8552029","http://stackoverflow.com/questions/8552029/#8595915","2011-12-21 20:26:13","1","682","1","1","How to turn off SecureConversationToken in WCF web service","<p>I have a WCF web service with WS-* security and I need to write a Java client for it using WSS4J API.
But, as it turns out WSS4J does not support the <code>&lt;SecurityContextToken&gt;</code> and <code>&lt;DerivedKeyToken&gt;</code> tags, which are specific to WS-SecureConversation.</p>
<p>is there a way to turn it off via code or better, via web.config?</p>
<p><strong>UPDATE:</strong></p>
<p>Service definition:</p>
<pre><code> &lt;service name=""my.service""
behaviorConfiguration=""SecureTransport""&gt;
&lt;endpoint
address=""mex""
binding=""mexHttpBinding""
contract=""IMetadataExchange"" /&gt;
&lt;endpoint
contract=""my.interface""
binding=""wsHttpBinding""
bindingConfiguration=""UsernameAndPassword""/&gt;
&lt;/service&gt;
</code></pre>
<p>Behaviour and Bindings:</p>
<pre><code>&lt;behaviors&gt;
&lt;serviceBehaviors&gt;
&lt;behavior name=""SecureTransport""&gt;
&lt;serviceMetadata httpGetEnabled=""true"" /&gt;
&lt;serviceDebug includeExceptionDetailInFaults=""true""/&gt;
&lt;serviceCredentials&gt;
&lt;userNameAuthentication userNamePasswordValidationMode=""Custom""
customUserNamePasswordValidatorType=""example.API.Security.CustomUserNameValidator, APISecurity"" /&gt;
&lt;serviceCertificate findValue=""CN=Example"" storeLocation=""LocalMachine"" storeName=""TrustedPeople"" x509FindType=""FindBySubjectDistinguishedName"" /&gt;
&lt;/serviceCredentials&gt;
&lt;/behavior&gt;
&lt;/serviceBehaviors&gt;
&lt;/behaviors&gt;
&lt;bindings&gt;
&lt;wsHttpBinding&gt;
&lt;binding name=""UsernameAndPassword""&gt;
&lt;security mode=""Message""&gt;
&lt;message clientCredentialType=""UserName"" /&gt;
&lt;/security&gt;
&lt;/binding&gt;
&lt;/wsHttpBinding&gt;
&lt;/bindings&gt;
</code></pre>
","58","1871","<java><wcf><web-services><wss4j>","2011-12-18 13:30:14","TRUE","FALSE","8595915","2011-12-21 20:26:13","0","<p>Just turn security context and probably also negotiation in your binding configuration:</p>
<pre><code>&lt;bindings&gt;
&lt;wsHttpBinding&gt;
&lt;binding name=""UsernameAndPassword""&gt;
&lt;security mode=""Message""&gt;
&lt;message clientCredentialType=""UserName"" establishSecurityContext=""false""
negotiateServiceCredential=""false"" /&gt;
&lt;/security&gt;
&lt;/binding&gt;
&lt;/wsHttpBinding&gt;
&lt;/bindings&gt;
</code></pre>
","490","1","1","2","2011-12-21 20:26:13","4736","TRUE","223483","0"
"http://stackoverflow.com/users/2118527","http://stackoverflow.com/questions/15216345","http://stackoverflow.com/questions/15216345/#15216380","2013-03-05 06:07:23","4","158","0","4","I need to assign a random but unique ID to each row of mysql table.The ID should be same if the row contains same values","<p>I need to assign a random but unique ID to each row in Mysql table.The ID should be same if the row contains same values.</p>
<p>ie., If the 1st row contains [hi,hello,bye] 2nd row contains[gg,hello,bye] and 3rd row contains[hi,hello,bye] then 1st and 3rd row should generate same ID and 2nd row should genetare different ID.</p>
<p>Thanks in advance.</p>
","120","361","<java><mysql>","2013-03-05 05:15:40","FALSE","FALSE","15216380","2013-03-05 06:07:23","1","<pre><code>SELECT CRC32(CONCAT(column1, column2, column3)) FROM MyTable.
</code></pre>
<p>Technically CRC32 is not <em>random</em> (but what is?) -- and it has a small chance of generating collisions (different values mapping to the same integer). But it's a start.</p>
","272","1","1","1","2013-03-05 05:19:06","4","TRUE","214562","0"
"http://stackoverflow.com/users/808681","http://stackoverflow.com/questions/6427349","http://stackoverflow.com/questions/6427349/#6428055","2011-07-04 12:24:53","3","1183","0","3","How to change a value in mysql database using conditions from java code?","<p>I'm trying to change a value <code>Dr_status</code> that only contain one int even 0 or 1. So if <code>Dr_status</code> equal to 1 change it to 0 and vice versa.
Here is the code :</p>
<pre><code>String query = ""Select Bluetooth_Address FROM dr"";
String str = ""40D32DBBE665"";//in the database I have only two fields in `Bluetooth_Address` column 40D32DBBE665 and another value
String check = """";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
PreparedStatement preparedStmt= con.prepareStatement(""update `dr` set `Dr_status` = '1'"");
PreparedStatement preparedStmt1= con.prepareStatement(""update `dr` set `Dr_status` = '0'"");
dbtime = rs.getString(1);
if (dbtime.equals(str)){
check = ""Select `Dr_status` From `dr` Where `Bluetooth_Address` = "" + "" "" + str ;
if(check.equals(0)){
preparedStmt.executeUpdate();
}
if(check.equals(1)){
preparedStmt1.executeUpdate();
}
</code></pre>
<p>I don't know where is the problem !!! please help.
Thanks in advance.</p>
","72","1130","<java><mysql>","2011-06-21 14:54:45","TRUE","FALSE","6428055","2011-06-21 18:06:53","3","<p>I give +1 to the answer from @Marcelo Hernández Rishmawy. Instead of testing the condition in Java code, do the test and the update in an SQL expression that converts 0 to 1 and 1 to 0 automatically, for the rows that match your Bluetooth address condition.</p>
<p>I'll also give you a tip that in MySQL, 1 and 0 are integers, but they are also used for true and false. So you can use either of the following tricks to make the statement more compact:</p>
<pre><code>""update `dr` set `Dr_status` = ! `Dr_status` where `Bluetooth_Address = "" + str
</code></pre>
<p>This trick works too:</p>
<pre><code>""update `dr` set `Dr_status` = 1 - `Dr_status` where `Bluetooth_Address = "" + str
</code></pre>
<p>It's a nice way to simplify, but FWIW it's specific to MySQL, not standard SQL. Other databases brands use proper boolean values, not 1 and 0.</p>
<hr>
<p>Re your comment: the error is not related to the solutions above, it's because you're interpolating a string of hex digits. You need to either quote the string, or better yet use a query parameter. </p>
<p>You should learn how to use query parameters in any case, because they're good for writing secure code to defend against SQL injection issues, and it's generally easier and more robust than trying to interpolate variables into SQL query strings.</p>
<p>See <a href=""http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html"" rel=""nofollow"">Using Prepared Statements</a> at The Java Tutorials.</p>
","1486","7","2","4","2011-06-21 15:38:54","44","TRUE","214562","0"
"http://stackoverflow.com/users/13491","http://stackoverflow.com/questions/490378","http://stackoverflow.com/questions/490378/#490425","2009-01-29 03:51:40","3","112","0","1","How do I place an IN parameter with a LIKE with a RowSet?","<p>I have fighting to get a IN parameter to work inside of a LIKE statement now for hours!
I am using a CachedRowSet, which I understand should follow the same rules as a PreparedStatement.<br />
Here is the basic query:</p>
<pre><code>CachedRowSet cache;
String sql = ""SELECT x "" +
""FROM Y "" +
""WHERE z LIKE '?__'""
cache.setCommand(sql);
cache.setString(1, ""someString"");
</code></pre>
<p>someString is a known id but the database( by the way is PostgreSQL) entry has a unknown 2 char suffix. </p>
","57","534","<java><regex><postgresql><prepared-statement><rowset>","2009-01-29 03:18:39","TRUE","FALSE","490425","2009-01-29 03:51:40","5","<p>Parameter placeholders inside quotes are ignored. They're interpreted as a literal ""?"". If you use a parameter, you must put the placeholder outside quotes in the SQL expression.</p>
<p>But <code>LIKE</code> can be compared to any string or any <em>expression</em> that produces a string. For example:</p>
<pre><code>SELECT x FROM y WHERE z LIKE (? || '__')
</code></pre>
<p>Now you could supply ""someString"" for the parameter, and then it will be concatenated with the constant string <code>'__'</code>.</p>
","518","3","1","1","2009-01-29 03:51:40","33","TRUE","214562","0"
"http://stackoverflow.com/users/947474","http://stackoverflow.com/questions/10605936","http://stackoverflow.com/questions/10605936/#10606259","2012-05-15 18:32:09","6","165","0","3","SQL to Determine Tee Order in Golf Application","<p>I am working on a golf application that includes a scorecard system. I am storing each score for each player in the database and I need to come up with a query to determine tee order. So for example if the players have played 3 holes and the scores look like this...</p>
<pre><code>Player 1 2 3
--------- - - -
Player 1: 3, 4, 3
Player 2: 2, 3, 3
Player 3: 2, 4, 3
</code></pre>
<p>... Then the order needs to look like this...</p>
<pre><code>1.) Player 2
2.) Player 3
3.) Player 1
</code></pre>
<p>... So the players will be ordered by their scores compared to their opponents scores. Does that make sense? Is this even possible with a query, or should I write a function to parse a 2d array in code? I am using Java in that case.</p>
<p>My table structure looks like this:</p>
<ul>
<li>Players (player id, and player name)</li>
<li>Rounds (round id, course id)</li>
<li>Scores (round id, player id, hole number, and score)</li>
</ul>
","46","952","<java><sql><database><sqlite>","2012-05-15 17:34:50","TRUE","FALSE","10606259","2012-05-15 18:08:53","3","<p>I can see a solution that uses windows functions row_number() and an additional column in the database for the ordering at each level (or a recursive CTE in SQL Server). However, SQLite does not support this.</p>
<p>Here is my recommendation on implementing the solution without doing a lot of querying backwards:</p>
<p>(1) Assign the tee order for the first tee.</p>
<p>(2) For each next tee, look at the previous score and the previous tee order:</p>
<p>(3) Assign the new tee order by looping through the previous scores by ordering by highest score DESC and previous tee order ASC.</p>
<p>Because you only have a few players per round, it is reasonable to do this in the app layer. However, if you had a database that supported window function, then you could more easily do a database only solution.</p>
<p>I can't resist. Here some code that will do this with a table to store the orders. You need to loop through, once per hole:</p>
<pre><code>create table ThisOrder (
ThisOrderId int primary key autoincrement,
RoundId int,
Hole int,
PlayerId int
)
</code></pre>
<p>Initialize it with each player in some order.</p>
<p>Then, insert new rows into the table for each hole:</p>
<pre><code>insert into ThisOrder(RoundId, HoleId, PlayerId)
select s.RoundId, s.Hole+1, s.PlayerId
from Scores s join
ThisOrder to
on s.PlayerId = to.PlayerId and
s.RoundId = to.RoundId and
s.Hole = to.Hole
order by s.Score DESC, to.Order ASC
</code></pre>
<p>You'll need to call this once for each hole, minus one.</p>
<p>Then get your ordering as:</p>
<pre><code> select *
from ThisOrder
where roundid = &lt;roundid&gt; and hole = &lt;thehole&gt;
order by ThisOrderId
</code></pre>
","1762","11","3","2","2012-05-15 17:58:11","24","TRUE","213350","0"
"http://stackoverflow.com/users/1324100","http://stackoverflow.com/questions/11506617","http://stackoverflow.com/questions/11506617/#11507586","2012-07-17 13:22:14","1","181","0","1","maxdrawdown calculation in SQL","<p>ok lets say i have a simple table from trading account with all the typical transactions info:</p>
<pre><code>Account ID Type OrderID Points NetPL Balance
13543564678 16 BUY 389745683 4.55 100.00 1,000,000.00
13543564678 16 BUY 389745684 4.55 100.00 1,000,100.00
13543564678 16 BUY 389745685 4.55 100.00 1,000,200.00
13543564678 16 SELL 389745686 4.55 100.00 1,000,300.00
13543564678 16 BUY 389745687 4.55 100.00 1,000,400.00
13543564678 16 SELL 389745688 4.55 100.00 1,000,500.00
13543564678 16 SELL 389745689 4.55 100.00 1,000,600.00
13543564678 16 SELL 389745690 4.55 -100.00 1,000,700.00
13543564678 16 SELL 389745691 4.55 -100.00 1,000,600.00
13543564678 16 SELL 389745692 4.55 -100.00 1,000,500.00
13543564678 16 SELL 389745693 4.55 -100.00 1,000,400.00
13543564678 16 SELL 389745694 4.55 100.00 1,000,300.00
13543564678 16 SELL 389745695 4.55 100.00 1,000,400.00
13543564678 16 BUY 389745696 4.55 100.00 1,000,500.00
13543564678 16 BUY 389745697 4.55 100.00 1,000,600.00
13543564678 16 BUY 389745698 4.55 100.00 1,000,700.00
13543564678 16 BUY 389745699 4.55 100.00 1,000,800.00
13543564678 16 BUY 389745700 4.55 100.00 1,000,900.00
13543564678 16 BUY 389745701 4.55 100.00 1,001,000.00
13543564678 16 BUY 389745702 4.55 100.00 1,001,100.00
13543564678 16 BUY 389745703 4.55 100.00 1,001,200.00
13543564678 16 BUY 389745704 4.55 -100.00 1,001,300.00
13543564678 16 BUY 389745705 4.55 -100.00 1,001,200.00
13543564678 16 BUY 389745706 4.55 -100.00 1,001,100.00
13543564678 21 BUY 389745707 4.55 -100.00 1,001,000.00
13543564678 21 SELL 389745708 4.55 -100.00 1,000,900.00
13543564678 21 SELL 389745709 4.55 -100.00 1,000,800.00
13543564678 21 SELL 389745710 4.55 -100.00 1,000,700.00
13543564678 21 BUY 389745711 4.55 -100.00 1,000,600.00
13543564678 21 SELL 389745712 4.55 -100.00 1,000,500.00
13543564678 21 BUY 389745713 4.55 -100.00 1,000,400.00
13543564678 21 SELL 389745714 4.55 -100.00 1,000,300.00
13543564678 21 SELL 389745715 4.55 100.00 1,000,200.00
13543564678 21 BUY 389745716 4.55 100.00 1,000,300.00
</code></pre>
<p>what i need here is to calculate a max drawdown using sql ONLY. I can easily do it on java (run a loop), but this thing shouold be a part of a big query, calculating different acc parameters.</p>
<p>so let me explain the formula : max drawdown is a value showing biggest balance drop toward negative, for all the acc records available in the db. looking into ex above, first drawdown is $400 (first negative $100 section), second one is bigger, its $1200 (second one). As you understand, these drawdowns happend regularly so acc history should have it a lot, not just 2 as shown here. usually it it calculates this kind of data on a huge dataset, starting from 100,000 records and up.</p>
<p>env is oracle 11gr2, read access only.
any smart ideas would be very appreciated!</p>
<p>ok, looks like system overwrites edits so i have to put it into 1 consolidated one.
I tried to add an artif column where map negative trades as 'Y' and tried to find a way how to do sum() on them after it. the problem here is that any single record can be more then any sum() of consequential records. </p>
","30","3354","<java><sql><oracle11gr2>","2012-07-16 14:37:50","TRUE","FALSE","11507586","2012-07-17 13:22:14","1","<p>You want to first enumerate the draw downs. I do this by using the lag function with a cumulative sum. The lag finds the start of a draw down, by looking at the previous PL being positive and the current negative. The cumulative sum assigns a value.</p>
<p>The rest follows from identifying these periods.</p>
<pre><code>select Account, MAX(DrawDownAmount)
from (select Account, DrawDownNum, SUM(-NetPl) as DrawDownAmount
from (select t.*,
sum(BeginDrawDown) over (partition by Account order by orderid) as DrawDownNum
from (select t.*,
(case when NetPL &lt; 0 then 1 else 0 end) as isdrawdown,
(case when coalesce(lag(NetPl, 1) over (partition by Account order by orderid), 1) &gt;= 0 and
NetPl &lt; 0
then 1
else 0
end) as BeginDrawDown
from t
) t
) t
where isdrawdown = 1
group by Account, DrawDownNum
) t
group by Account
</code></pre>
","1117","2","1","3","2012-07-16 15:34:38","57","TRUE","213350","0"
"http://stackoverflow.com/users/1584507","http://stackoverflow.com/questions/22513903","http://stackoverflow.com/questions/22513903/#22513941","2014-03-19 17:42:20","1","107","0","1","Copy only selected values from one table to another table with condition","<p>I am trying to copy selected values from rows of one table to another table, the problem is that SQLite gives an error for a nested <code>SELECT</code> command as </p>
<p><code>java.sql.SQLException: only a single result allowed for a SELECT that is part of an expression</code></p>
<p>Here is what I am trying:</p>
<pre><code>INSERT INTO table2(ID, ProjectName )
SELECT ID, ProjectName FROM table1
Where table1.ID NOT IN table2
</code></pre>
<p>I can't use <code>*</code> here, since <code>table1</code> has four columns and <code>table2</code> has only 3.
All has to be done is to check if any <code>ID</code> value from <code>table1</code> is not present in <code>table2</code>, then copy only that <code>ID</code>, respective <code>ProjectName</code> values from <code>table1</code> and insert it into table2 as <code>ID, ProjectName , null</code></p>
<p>null is for the thrid column value in table2.</p>
<p>Any suggestions or help would be great</p>
","72","966","<java><sql><sqlite>","2014-03-19 17:40:08","TRUE","FALSE","22513941","2014-03-19 17:42:20","2","<p>Your query is almost there:</p>
<pre><code>INSERT INTO table2(ID, ProjectName )
SELECT ID, ProjectName
FROM table1
Where table1.ID NOT IN (select table2.id from table2);
</code></pre>
<p>This is standard SQL, so it should work in any database.</p>
","266","2","1","1","2014-03-19 17:42:20","2","TRUE","213350","0"
"http://stackoverflow.com/users/1233359","http://stackoverflow.com/questions/25232462","http://stackoverflow.com/questions/25232462/#25232506","2014-08-10 22:31:46","1","56","0","2","Repeating selects or use IN clause, which is faster?","<p>I find this becomes a common situation when design JDBC/JPA queries when using a collection as where condition for selection.</p>
<p>Let's say if there is a table of 50 thousand records with field <code>order_id</code> which is properly indexed. Now the java application have a list of 500 order ids to find order details and need to assign values to each order object. So there can be two plan</p>
<pre><code>1. run 500 SELECT queries
for(String id:order_ids){
Order order = QueryAgent.execute(""SELECT * FROM ORDES o WHERE o.order_id =""+id);
modifyOrder(order);
}
2. run one query whith 500 parameters in
String orders_in_string = getOrdersInString(order_ids);
List&lt;Order&gt; orders = QueryAgent.execute(""SELECT * FROM ORDES o WHERE o.order_id IN =""+orders_in_string);
for(Order order:orders){
modifyOrder(order);
}
</code></pre>
<p>I cannot tell which one get better performance.</p>
","52","911","<java><sql><oracle><java-ee><jpa>","2014-08-10 19:56:34","TRUE","FALSE","25232506","2014-08-10 20:05:00","6","<p>The two queries are going to return the same volume of results. So, your real question is which is faster: running 500 small queries or one large query to get the same results.</p>
<p>The proper answer to a performance question is to encourage you to try it on your system and see which is faster on your data in your environment.</p>
<p>In this case, there is every reason to expect that a single query would be faster. SQL incurs overhead in parsing queries (or finding already parsed equivalent queries), in starting a query, and in preparing results. All of these happen <em>once</em> per query. So, I would expect one query to be faster.</p>
<p>If the list of <code>order_id</code>s is already coming from the database, I would recommend building a more complex query, so they don't have to go back to the application. Something like:</p>
<pre><code>select o.*
from orders o
where o.order_id in (select . . . );
</code></pre>
<p>Also, if you don't need all the columns, you should just explicitly choose the ones you want. Actually, it is a good idea to be always explicit in the columns being chosen.</p>
","1126","5","1","1","2014-08-10 20:01:28","5","TRUE","213350","0"
"http://stackoverflow.com/users/2109694","http://stackoverflow.com/questions/21479751","http://stackoverflow.com/questions/21479751/#21479786","2014-07-14 06:08:50","1","157","0","1","How to execute a group of 'select count(*)' queries as a batch in Java?","<p><strong>EDIT : besides the answer by Gordon, <a href=""http://stackoverflow.com/questions/606234/select-count-from-multiple-tables"">I found this question answered beautifully on this thread</a></strong></p>
<p>While we can execute a group of insert/update statements as a batch, there is no such provision for select statements. I understand that it's impossible to do so because they return results that may have many columns.</p>
<p>However, <code>SELECT COUNT(*) FROM table_name</code> returns just one value and that is an integer. Is there a way to run a group of such queries as a batch and retrieve the results as an int array?</p>
<p>My particular requirement is to run these queries for a bunch of tables on the same database and then repeat this for more databases. Consider this example:</p>
<pre><code> String[] queries = {""SELECT COUNT(*) FROM table1"",
""SELECT COUNT(*) FROM table2"",
""SELECT COUNT(*) FROM table3"" };
Statement st = connection.createStatement();
for(String q: queries){
st.addBatch(q);
}
st.executeBatch();
</code></pre>
<p>In this case, the executeBatch() command will only return the number of rows affected, which will be zero (I suppose) in this case for each statement.</p>
<p>Is there a way to make a batch of such statements considering that they return only one value each? Any workaround?</p>
<p><strong>Specific requirements follow..</strong></p>
<p>SQL Procedures are out of question as I have to do this on many different databases and I don't have any access except to read them. I mean, I <em>can</em> store procedures there, but I've been told not to modify the database in any way and just to read from it. Additionally, the number of databases may increase later and I wouldn't be there to install these procedures on them, so I don't want that dependency in order for this solution to be truly flexible.</p>
<p>I am using Java with SQL Server 2008 for building a webpage that gets count values from a bunch of tables on various databases and displays them.</p>
","71","2116","<java><sql><sql-server><sql-server-2008>","2014-01-31 12:07:15","TRUE","FALSE","21479786","2014-01-31 12:16:06","2","<p>Why not just run one query? You an do:</p>
<pre><code>select (SELECT COUNT(*) FROM table1) as table1cnt,
(SELECT COUNT(*) FROM table2) as table2cnt,
(SELECT COUNT(*) FROM table3) as table3cnt;
</code></pre>
<p>You can also return one value per row, but you'll want an additional column to identify the table:</p>
<pre><code>select which, cnt
from ((SELECT 'table1' as which, COUNT(*) as cnt FROM table1) union all
(SELECT 'table2' as which, COUNT(*) as cnt FROM table2) union all
(SELECT 'table3' as which, COUNT(*) as cnt FROM table3)
) t
</code></pre>
","592","2","2","2","2014-01-31 12:09:39","2","TRUE","213350","0"
"http://stackoverflow.com/users/3702643","http://stackoverflow.com/questions/24221721","http://stackoverflow.com/questions/24221721/#24221735","2014-06-15 06:22:30","1","58","0","2","Select DISTINCT from MYSQL database","<p>I need to extract some data from my database, but the problem is that Im getting repeated values from the database, which I do not want.</p>
<p>The username is stored into the database multiple times.</p>
<p>I tried using DISTINCT but it did not work.</p>
<p>Can anyone tell me how to extract the username from the database only once?</p>
<p>Code:</p>
<pre><code>PreparedStatement preparedStatement = connect
.prepareStatement(""SELECT DISTINCT username, score, name from score order by score desc limit 10"");
</code></pre>
","35","543","<java><mysql><distinct>","2014-06-14 15:58:55","TRUE","FALSE","24221735","2014-06-15 06:22:30","3","<p>Use <code>group by</code> instead of <code>distinct</code>. <code>Select distinct</code> applies to all columns being selected:</p>
<pre><code>SELECT username, max(score) as score, max(name) as name
from score
group by username
order by score desc
limit 10;
</code></pre>
","277","1","1","2","2014-06-14 16:01:09","3","TRUE","213350","0"
"http://stackoverflow.com/users/1186898","http://stackoverflow.com/questions/22213889","http://stackoverflow.com/questions/22213889/#22214098","2014-03-06 03:12:26","0","177","0","1","Duplicate row when multiple threads insert the same content in the mysql database","<p>I have one mysql table which looks like</p>
<h2>id | property_code | property_value</h2>
<p>The id is auto increment, is the primary key in this table.</p>
<p>when I have multiple threads in the distributed machines, insert the same content to this table, so that a duplicate will happen.</p>
<h2> 1 | code_1 | value1</h2>
<h2> 2 | code_1 | value1</h2>
<p>I know if I set the property_code as the primary key, it will solve this problem.
is there any other solution to solve this problem if I don't want to change the primary key?</p>
","81","544","<java><mysql><multithreading><concurrency>","2014-03-06 02:49:37","FALSE","FALSE","22214098","2014-03-06 03:12:26","0","<p>Creating a unique index doesn't change the schema of the table <em>directly</em>. You can create such an index by doing:</p>
<pre><code>create unique index table_property_code on table(property_code);
</code></pre>
<p>This will enforce uniqueness of the value in the table, regardless of the number of simultaneous inserts and updates.</p>
<p>Adding a unique constraint or unique key does exactly the same thing. If you wanted, you could do this through an <code>alter table</code> command, but you don't need to.</p>
<p>Just a note, your question is a little ambiguous, so you might want one unique index on both <code>property_code</code> and <code>property_value</code>.</p>
","687","4","1","1","2014-03-06 03:12:26","23","TRUE","213350","0"
"http://stackoverflow.com/users/2928868","http://stackoverflow.com/questions/21140037","http://stackoverflow.com/questions/21140037/#21140120","2014-01-15 14:34:37","0","50","0","1","Number of characters in sql query result","<p>I am using Spring 3.1.1 with Hibernate 4 and a MSSQL database. Finally, I have been able to query my database with joins in my table that returns the correct answers. Although, it seems that it does not return the entire strings of my messages, but cuts at 29/30 digits. Here is my query:</p>
<pre><code>SQLQuery sql = this.getCurrentSession().createSQLQuery(
""SELECT event.id as eventid, CAST(event_type.type_name AS varchar) as eventtype, event.check_date, event.event_date, event.status, CAST(event_message.message AS varchar) as eventmessage "" +
""FROM event_log event "" +
""LEFT JOIN event_type "" +
""ON (event.event_type_id = event_type.id) "" +
""LEFT JOIN event_message "" +
""ON (event.event_message_id = event_message.id) "" +
""WHERE event.event_type_id = "" + jobId +
""ORDER BY eventid"");
</code></pre>
<p>The result can be:</p>
<pre><code>4506 Database 2014-01-15 14:14:15.02 2014-01-15 14:14:15.02 false Database-connection cannot be
</code></pre>
<p>Where the columns are id, task_name, check_date, event_date, status and the message-string at the end. . </p>
<p>The result goes to a <code>ArrayList&lt;Object[]&gt;</code> where I read <code>row[0]</code> etc. to get the entities in the row. The string message gets cut after 29 digits, which is disturbing. Why does it cut the string and how can I fix this? In my database the string exists in it's full and is entitled 400 characters max. </p>
<p><em>I know this is probably not the best way to query my database, but it will do for my application since it works.</em> </p>
","40","1643","<java><sql><spring>","2014-01-15 14:28:15","TRUE","FALSE","21140120","2014-01-15 14:34:37","1","<p>You are using <code>varchar</code> without a length. <em>Never</em> do this!</p>
<p>Replace:</p>
<pre><code>CAST(event_type.type_name AS varchar)
</code></pre>
<p>With something like:</p>
<pre><code>CAST(event_type.type_name AS varchar(255))
</code></pre>
<p>In some contexts, the default length is 32. In some it is 1. In general, though, <em>always</em> specify the length.</p>
<p>EDIT:</p>
<p>Actually, you probably don't even need the <code>cast</code>. Why not just have <code>event_type.type_name</code> in the <code>select</code> list?</p>
","561","6","2","1","2014-01-15 14:31:24","3","TRUE","213350","0"
"http://stackoverflow.com/users/2035600","http://stackoverflow.com/questions/18453170","http://stackoverflow.com/questions/18453170/#18454112","2013-08-26 22:30:54","0","135","0","1","MYSQL SUBSTRING_INDEX / CONVERT / IF clause","<p>I have a table with something like this.</p>
<pre><code>abc-cde-0001222
abc-cde-0001223
abc-ced-0001224
cde-efg-0003001
ced-efg-0003002
ced-efg-0003008
</code></pre>
<p>I wish to select <code>abc-cde-0001222, abc-ced-0001224</code></p>
<pre><code> also cde-efg-0003001 , cde-efg-0003002
ced-efg-0003008 , """"
</code></pre>
<p>See, I need to obtain 1st and last values of a range. If the particular value is only one item (not in a range) I want it to select as the 1st value and a null value.</p>
<p>So far I have only a Idea of using <code>IF</code> and <code>increment operator</code> (If this is possible). I can do the formatting and obtain the Int value using </p>
<pre><code>SELECT field, CONVERT(SUBSTRING_INDEX(field,'-',-1), UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;
</code></pre>
<p>Please could you give me a hand...
Lot appreciated</p>
","43","888","<java><mysql><sql>","2013-08-26 21:17:30","TRUE","FALSE","18454112","2013-08-26 22:30:54","0","<p>This is a pain in MySQL. But, it is possible. The logic is to find where a sequence starts. You can do this with a correlated subquery and some arithmetic. Then you want a cumulative sum of the starts. This is harder, because it requires doing a correlated subquery on the correlated subquery.</p>
<p>First, to set the <code>NullIfStart</code> variable:</p>
<pre><code>select t.*,
(select 0
from t t2
where left(t2.field, 8) = left(t.field, 8) and
t2.field &lt; t.field and
right(t2.field, 7) + 0 = right(t.field, 7) + 0 - 1
) as NullIfStart
from t;
</code></pre>
<p>This gets the cumulative sum, which can be used as a grouping field:</p>
<pre><code>select t.*
(select sum(NullIfStart is null)
from (select t1.*,
(select 0
from t t2
where left(t2.field, 8) = left(t1.field, 8) and
t2.field &lt; t1.field and
right(t2.field, 7) + 0 = right(t1.field, 7) + 0 - 1
) as NullIfStart
from t t1
) tnis
where right(tnis.field, 7) = right(t.field, 7) and
tnis.field &lt;= t.field
) grp
from t;
</code></pre>
<p>The final solution is to do the aggregation:</p>
<pre><code>select min(field),
(case when max(field &lt;&gt; min(field) then max(field) end)
from (select t.*
(select sum(NullIfStart is null)
from (select t1.*,
(select 0
from t t2
where left(t2.field, 8) = left(t1.field, 8) and
t2.field &lt; t1.field and
right(t2.field, 7) + 0 = right(t1.field, 7) + 0 - 1
) as NullIfStart
from t t1
) tnis
where left(tnis.field, 8) = left(t.field, 8) and
tnis.field &lt;= t.field
) grp
from t
) s
group by left(s.field, 8), grp;
</code></pre>
","2134","4","3","7","2013-08-26 22:30:54","73","TRUE","213350","0"
"http://stackoverflow.com/users/2554121","http://stackoverflow.com/questions/17529335","http://stackoverflow.com/questions/17529335/#17529561","2013-07-08 14:45:16","0","79","0","1","Count Duplicate Results in Oracle Database","<p>I am working on a database project using both Java and SQL with an Oracle Database. I am new at working with databases and new at SQL. My question is: how would I be able to get the customer count and record each of their purchase history on a pivot table? For example, on the following table, I have Lee a total of 3 times, and purchased Item A, Item B, and Item C. Ann is there 3 times as well and purchased Item D, Item E, and Item F. I want to put their name, the number of occurrences and what they purchased on separate pivot table. </p>
<pre><code>Row Customer Purchase_History
1 Lee Item A
2 Lee Item B
3 Lee Item C
4 Ann Item D
5 Ann Item E
6 Ann Item F
</code></pre>
<p>I've written some code attempting to do this, but when I compile and run, it will not give me the desired results. Here is my code:</p>
<pre><code> String TableCount = ""SELECT J.Row, J.Customer, J.Purchase_History, C.cnt"" +
"" FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt"" +
""FROM Table GROUP BY Customer"") C ON J.Customer = C.Customer;
ResultSet rs = st.executeQuery(TableCount);
while(rs.next()){
st.executeUpdate(""CREATE TABLE IF NOT EXISTS CUSTOMER_COUNT"" +
""(TableCount , Purchase_History )"");
String InsertIntoTable = String.format(""INSERT INTO CUSTOMER_COUNT"" +
""(""TableCount"",""Purchase_History"")"" +
"" VALUES ('%s','%s)"");
}
</code></pre>
<p>What am I doing wrong here? Any help would be greatly appreciated!</p>
","42","1744","<java><sql><database>","2013-07-08 14:33:44","TRUE","FALSE","17529561","2013-07-08 14:45:16","0","<p>Your query logic is fine. You should print out the query before running it. The problem would be these two lines (at least):</p>
<pre><code> "" FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt"" +
""FROM Table GROUP BY Customer"") C ON J.Customer = C.Customer;
</code></pre>
<p>I assume you really mean:</p>
<pre><code> "" FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt"" +
""FROM Table GROUP BY Customer) C ON J.Customer = C.Customer"";
</code></pre>
<p>In any case, when you print this out, you'll have the expression <code>cntFROM table</code>. You need a space:</p>
<pre><code> "" FROM Table J INNER JOIN(SELECT Customer, count(Customer) as cnt"" +
"" FROM Table GROUP BY Customer) C ON J.Customer = C.Customer"";
</code></pre>
<p>But, an easier way to write your query is to use analytic functions:</p>
<pre><code>select J.Row, J.Customer, J.Purchase_History,
count(*) over (partition by customer) as cnt
from table j
</code></pre>
","1046","4","4","1","2013-07-08 14:45:16","12","TRUE","213350","0"
"http://stackoverflow.com/users/3589625","http://stackoverflow.com/questions/24909106","http://stackoverflow.com/questions/24909106/#24909195","2014-07-23 11:36:07","0","40","0","3","SQL statement takes huge amount of time, is it possible optimize it?","<p>This is my SQL query with which I get all the duplicates, but one(the newest one):</p>
<pre><code>SELECT d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID, d.C_DateCreated
FROM duplicates as d
WHERE d.C_DateCreated !=(select max(d2.C_DateCreated)
FROM duplicates d2
WHERE d2.C_DataSourceId = d.C_DataSourceId)
</code></pre>
<p>Is it possible to optimize it somehow? Unfortunately in 300 000 records it takes +- 40minutes. </p>
<p>Method where the query is:</p>
<pre><code>public ArrayList&lt;Record&gt; get() throws SQLException,
ClassNotFoundException {
Statement st = DBConnect.DBC.con.createStatement();
String sql = (""select d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID,
d.C_DateCreated ""
+ ""from duplicates as d ""
+ ""where d.C_DateCreated !=(select max(d2.C_DateCreated) ""
+ ""from duplicates d2 where d2.C_DataSourceId = d.C_DataSourceId)"");
ResultSet rs = st.executeQuery(sql);
DBConnect.DBC.con.commit();
while (rs.next()) {
int contactID = rs.getInt(""C_ContactID"");
String email = rs.getString(""C_EmailAddress"");
String dataSourceID = rs.getString(""C_DataSourceID"");
String dateCreated = rs.getString(""C_DateCreated"");
duplicate = new Record(contactID, email, dataSourceID, dateCreated);
duplicates.add(duplicate);
}
rs.close();
st.close();
return duplicates;
}
</code></pre>
","68","1431","<java><sql><sqlite>","2014-07-23 11:20:11","TRUE","FALSE","24909195","2014-07-23 11:30:28","2","<p>You would start by creating an index on <code>duplicates(C_DataSourceId, C_DateCreated)</code>:</p>
<pre><code>create index duplicates_DataSourceId_DateCreated on duplicates(C_DataSourceId, C_DateCreated);
</code></pre>
<p>If you are using a database that supports window functions, then I would rephrase this as:</p>
<pre><code>SELECT d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID, d.C_DateCreated
FROM (select d.*, max(C_DateCreated) over (partition by C_DataSourceId) as maxdc
from duplicates d
) d
WHERE d.C_DateCreated &lt;&gt; maxdc;
</code></pre>
<p>It is worth doing the comparison, because sometimes window functions have efficient implementations.</p>
<p>And, if you have the index, a slightly more efficient version of your query is:</p>
<pre><code>SELECT d.C_ContactID, d.C_EmailAddress, d.C_DataSourceID, d.C_DateCreated
FROM duplicates d
WHERE EXISTS (select 1
from duplicates 2
where d2.C_DataSourceId = d.C_DataSourceId and
d2.C_DateCreated &gt; d.C_DateCreated
);
</code></pre>
<p>This says to get all rows from duplicates where there is another row (with the same source) that has a bigger date created. The slight advantage is that this doesn't have to look at <em>all</em> the values to get the <code>max()</code>. It only has to find the first one. The major performance improvement will be the composite index.</p>
","1429","5","3","8","2014-07-23 11:24:38","4","TRUE","213350","0"
"http://stackoverflow.com/users/1621981","http://stackoverflow.com/questions/20554973","http://stackoverflow.com/questions/20554973/#20555042","2013-12-12 22:00:27","0","35","0","1","Creating a mysql Table from another Table","<p>Here is my problem: I have a table with relations between people and objects.</p>
<pre><code>Table logs
| id | user_id | object_id |
----------------------------
| 1 | 25488 | 54879 |
----------------------------
| 2 | 25488 | 54880 |
----------------------------
| 3 | 35487 | 54880 |
----------------------------
</code></pre>
<p>And I want to make a new table where each row is a user and each column is a object. If the user has a relation to the object I will input 1, if not 0.</p>
<pre><code>Table User
| id | user_id | o54879 | o54880 | o87984 | ...
--------------------------------------------------------
| 1 | 25488 | 0 | 1 | 0 | ...
--------------------------------------------------------
| 2 | 35487 | 0 | 1 | 1 | ...
--------------------------------------------------------
</code></pre>
<p>I did the work with java but it is very slow. Creating the table is fine, but then I loop over every user and create the correct sql query (as a String). So each time, I make a query to extract the data and another to input the data in the new table. I have 100 000 user in the database so It will take a while. </p>
<p>Is there a faster way to acheve this, with less transactions to the database?</p>
","41","1296","<java><mysql><sql><performance>","2013-12-12 21:48:27","TRUE","FALSE","20555042","2013-12-12 22:00:27","2","<p>It you have the destination table, then you know the list of objects you need.</p>
<p>This process is called pivoting a table. In MySQL you need to do this explicitly. Here is an example using aggregation:</p>
<pre><code>insert into table2(user_id, o54879, o54880, . . .)
select user_id,
max(object_id = 54879),
max(object_id = 54880),
. . .
from logs
group by user_id;
</code></pre>
<p>EDIT:</p>
<p>This uses a MySQL convention that <code>0</code> is false and <code>1</code> is true. The above logic is equivalent to:</p>
<pre><code>max(case when object_id = 54879 then 1 else 0 end),
max(case when object_id = 54880 then 1 else 0 end),
</code></pre>
<p>Sometimes, I prefer the explicit <code>case</code> statement, because that is standard SQL. Sometimes, I prefer the MySQL convention because it does simplify the code (at the expense of making it slightly less readable for non-programmers).</p>
","960","5","2","1","2013-12-12 21:52:43","4","TRUE","213350","0"
"http://stackoverflow.com/users/2322920","http://stackoverflow.com/questions/25446300","http://stackoverflow.com/questions/25446300/#25446413","2014-08-22 12:32:47","0","41","0","2","Make one query out of two others?","<p>I have never been very good at SQL queries (I've always preferred NoSQL databases, but I need to use a SQL database this time).</p>
<p>I need to research how many seats are sold compared to the amount of total seats in cinema halls. At the moment I can accomplish this using 2 different queries in Hibernate, one for the total amount of seats and the other for the amount of sold seats, and then divising these results.</p>
<p>This is my code :</p>
<pre><code> Double amountOfSoldTickets = ((Long) session.createQuery(""select count(*) from Ticket t where t.vertoning.zaal.cinemacomplex.id = :id"").
setInteger(""id"", complex.getId()).list().get(0)).doubleValue();
Double capacity= ((Long) session.createQuery(""select sum(z.capaciteit) from Zaal z"").list().get(0)).doubleValue();
return amountOfSoldTickets / capacity;
</code></pre>
<p>I thought about using a subquery though I have no idea how to do this in hibernate.
If anyone has any idea how to solve this in one query it'd be greatly appreciated.</p>
<p>Some additional info: I let hibernate implicitly join my tables in the first query.</p>
<p><code>Ticket</code> has a many to one to <code>Vertoning</code>, <code>Vertoning</code> has a many to one to <code>Zaal</code>, <code>Zaal</code> has a many to one to <code>cinemacomplex</code> </p>
","33","1333","<java><mysql><hibernate><subquery>","2014-08-22 11:48:05","TRUE","FALSE","25446413","2014-08-22 12:32:47","1","<p>I encourage you to learn SQL -- and to learn it on a real database instead of through the HQL interface. HQL is useful for what it does, but it misses on some very important SQL functionality.</p>
<p>I believe the following will work in HQL:</p>
<pre><code>select count(*) as SoldSeats,
(select sum(z.capaciteit) from Zaal z) as Capacity
from Ticket t
where t.vertoning.zaal.cinemacomplex.id = :id;
</code></pre>
<p>In just MySQL, you could put these as subqueries in the <code>from</code> clause:</p>
<pre><code>select t.SoldSeats, z.Capacity
from (select count(*) as SoldSeats,
from Ticket t
where t.vertoning.zaal.cinemacomplex.id = :id
) t
(select sum(z.capaciteit) as Capacity
from Zaal z
) z;
</code></pre>
<p>Note that if this is inside a loop where you are assigning different values to <code>id</code>, then the whole loop can possibly replaced with SQL.</p>
","918","4","2","3","2014-08-22 11:54:34","6","TRUE","213350","0"
"http://stackoverflow.com/users/2847689","http://stackoverflow.com/questions/24910042","http://stackoverflow.com/questions/24910042/#24910138","2014-07-23 12:09:25","0","25","0","1","Get distinct values via hibernate","<p>I want to get distinct values by a parameter:</p>
<pre><code>@Transactional
public List&lt;data&gt; getAllFromColumn(String identifier) {
List&lt;data&gt; resultList = em.createQuery(""SELECT DISTINCT p.market FROM data p"", Data.class).getResultList();
return resultList;
}
</code></pre>
<p>My problem is that this only returns me a <code>NullPointerException</code>. Any recommendations what is wrong, or what I can do differently?</p>
<p>I appreciate your answer!</p>
","33","485","<java><sql><hibernate><orm>","2014-07-23 12:04:40","TRUE","FALSE","24910138","2014-07-23 12:09:25","1","<p>If HQL doesn't support <code>select distinct</code> (which it doesn't seem to according to the syntax), you can do this using <code>group by</code>:</p>
<pre><code>SELECT p.market
FROM data p
GROUP BY p.market;
</code></pre>
","229","1","1","2","2014-07-23 12:09:25","5","TRUE","213350","0"
"http://stackoverflow.com/users/3540851","http://stackoverflow.com/questions/23107807","http://stackoverflow.com/questions/23107807/#23108085","2014-04-16 23:10:45","0","40","0","2","SQL statement (Oracle) that selects rows from tbl NOT IN pattern (selected from joined tables)","<p>I have two tables: <code>tblAPARTMENT</code> and <code>tblRESERVATION</code>. I want a list of all apartmentID's which are not in the reservation-table with those dates.</p>
<p>I have tried: </p>
<pre><code>SELECT apartmentID, apartmentNAME
FROM tblAPARTMENT
NOT IN
(SELECT apartmentID FROM tblRESERVATION
WHERE tblRESERVATION.startDate &gt; _a-date_
AND tblRESERVATION.endDate &lt; _a-date_
</code></pre>
<p>I know there is a better way to write this, I just cant figure it out.</p>
","94","504","<java><sql><oracle>","2014-04-16 11:15:27","TRUE","FALSE","23108085","2014-04-16 23:10:45","0","<p>The syntactically correct way to write your query is:</p>
<pre><code>SELECT a.apartmentID, a.apartmentNAME
FROM tblAPARTMENT a
WHERE a.apartmentID NOT IN (SELECT a.apartmentID
FROM tblRESERVATION r
WHERE r.startDate &lt;= _a-date_ AND r.endDate &gt;= _a-date_
);
</code></pre>
<p>This is a reasonable way, but it is generally safer to use <code>not exists</code> rather than <code>not in</code> (due to <code>NULL</code> handling):</p>
<pre><code>SELECT a.apartmentID, a.apartmentNAME
FROM tblAPARTMENT a
WHERE NOT EXISTS (SELECT a.apartmentID
FROM tblRESERVATION r
WHERE r.startDate &lt;= _a-date_ AND r.endDate &gt;= _a-date_ and
r.apartmentid = a.apartmentid
);
</code></pre>
","855","2","2","4","2014-04-16 11:26:05","11","TRUE","213350","0"
"http://stackoverflow.com/users/1813682","http://stackoverflow.com/questions/20713578","http://stackoverflow.com/questions/20713578/#20713846","2013-12-21 00:03:41","-1","66","0","1","Java Mysql Ordering varchar as int","<p>I'm trying to solve the following problem in java and msql.</p>
<p>if I run the following query directly in mysql records sorted correctly.
But when the same query is done through java or connector, NOT the records are sorted.
It is as if the query is performed by comparing string and not integer.</p>
<blockquote>
<p>select * from table1 order by cast(col2 as signed) limit 0,10</p>
</blockquote>
<p>Code example:</p>
<pre><code>public ArrayList&lt;Customers_voip_terminations_details&gt; select_Customers_voip_terminations_details_all(int voipID, int fromrow, int torow, String orderby) throws SQLException {
String query = """";
if (fromrow == 0 &amp;&amp; torow == 0) {
query = ""select * from customers_voip_terminations_details where voipid=? order by cast(? as signed)"";
this.preparedStatement = conn.prepareStatement(query);
this.preparedStatement.setInt(1, voipID);
this.preparedStatement.setString(2, orderby);
} else {
//Tools tool = new Tools();
query = ""select * from customers_voip_terminations_details where voipid=? order by cast(? as signed) LIMIT ?, ?"";
this.preparedStatement = conn.prepareStatement(query);
this.preparedStatement.setInt(1, voipID);
this.preparedStatement.setString(2, orderby);
this.preparedStatement.setInt(3, fromrow);
this.preparedStatement.setInt(4, torow);
}
this.resultSet = this.preparedStatement.executeQuery();
ArrayList&lt;Customers_voip_terminations_details&gt; result = new ArrayList&lt;Customers_voip_terminations_details&gt;();
while (this.resultSet.next()) {
Customers_voip_terminations_details item = new Customers_voip_terminations_details();
item.registerid = this.resultSet.getInt(""registerid"");
item.date1 = this.resultSet.getInt(""date1"");
item.date2 = this.resultSet.getInt(""date2"");
item.voipid = this.resultSet.getInt(""voipid"");
item.customerid = this.resultSet.getInt(""customerid"");
item.countryid = this.resultSet.getInt(""countryid"");
item.uniquesearch = this.resultSet.getString(""uniquesearch"").trim();
item.networktypeid = this.resultSet.getInt(""networktypeid"");
item.zone = this.resultSet.getString(""zone"").trim();
item.whitecli = this.resultSet.getInt(""whitecli"");
item.whiteroute = this.resultSet.getInt(""whiteroute"");
item.acd = this.resultSet.getFloat(""acd"");
item.asr = this.resultSet.getFloat(""asr"");
item.pdd = this.resultSet.getInt(""pdd"");
item.billingtime = this.resultSet.getInt(""billingtime"");
item.rate = this.resultSet.getDouble(""rate"");
item.status = this.resultSet.getInt(""status"");
result.add(item);
}
this.resultSet.close();
this.preparedStatement.close();
return result;
}
</code></pre>
","34","3043","<java><mysql><ordering>","2013-12-20 23:31:38","TRUE","FALSE","20713846","2013-12-21 00:03:41","1","<p>When you have an expression like this in your query string:</p>
<pre><code>order by cast(? as signed)
</code></pre>
<p>The <em>value</em> being put in is a constant value -- not a set of characters into the string. So, if you put in <code>col2</code>, you are really saying:</p>
<pre><code>order by cast('col2' as signed)
</code></pre>
<p>In MySQL, the cast succeeds (it would fail in other databases) and returns <code>0</code>, because there are no digits at the beginning of the value. Ordering by a constant is, well, like either ordering randomly or ordering by nothing at all.</p>
<p>Happily, this is easily fixed by putting in the proper column directly and dispensing with the substitution:</p>
<pre><code> query = ""select * from customers_voip_terminations_details where voipid=? order by cast(voipid as signed)"";
</code></pre>
","849","4","3","1","2013-12-21 00:03:41","32","TRUE","213350","0"
"http://stackoverflow.com/users/361275","http://stackoverflow.com/questions/21273430","http://stackoverflow.com/questions/21273430/#21273680","2014-01-22 05:34:07","-2","125","2","4","how to write this sql query - replacing each word of a string with matching value from another table","<p>I have two tables:</p>
<p>Table 1:</p>
<pre><code>column1 column2
1 TARA JENK ERIK MURP
2 MATH SIER SHCK ELCP SBAR
3 CELN KRAB
</code></pre>
<p>Table 2:</p>
<pre><code>ID NAME
345 TARA
084 JENK
875 ERIK
345 MURP
</code></pre>
<p>Now, I want to query the data to be called within Java, so as I get the table 1 with column2's each word replaced by the ID matching in Table 2.</p>
<p>Is the SQL for this doable.</p>
<p>Thanks in advance,</p>
<p>Cheers</p>
<p>EDITED:
Expected output:</p>
<pre><code>column1 column2
1 345 084 875 435
2 980 245 352 355 425
3 523 233
</code></pre>
","100","641","<java><sql><oracle>","2014-01-22 03:09:04","TRUE","FALSE","21273680","2014-01-22 05:34:07","1","<p>Here is code that does what you want:</p>
<pre><code>with words(id, word, rest, lev) as (
select column1 as id,
substr(column2, 1, instr(column2, ' ') - 1) as word,
substr(column2, instr(column2, ' ') + 1) as rest,
1 as lev
from table1
union all
select id,
(case when rest like '% %'
then substr(rest, 1, instr(rest, ' ') - 1)
else rest
end) as word,
(case when rest like '% %'
then substr(rest, instr(rest, ' ') + 1)
end) as rest,
lev + 1
from words
where rest is not null
)
select w.id,
listagg(coalesce(cast(t2.id as varchar2(255)), w.word), ' ') within group (order by w.lev)
from words w left outer join
table2 t2
on w.word = t2.name
group by w.id;
</code></pre>
<p><a href=""http://www.sqlfiddle.com/#!4/d41d8/23807"" rel=""nofollow"">Here</a> is a SQL Fiddle demonstrating it working.</p>
","1019","2","1","6","2014-01-22 03:34:44","25","TRUE","213350","0"
"http://stackoverflow.com/users/15055","http://stackoverflow.com/questions/311775","http://stackoverflow.com/questions/311775/#311833","2014-07-30 02:22:33","69","52054","24","7","Python - Create a list with initial capacity","<p>Code like this often happens:</p>
<pre><code>l = []
while foo:
#baz
l.append(bar)
#qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to constantly be re-initialized to grow. (I understand that lists aren't just wrappers around some array-type-thing, but something more complicated. I think this still applies, though; let me know if not).</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us python programmers?</p>
","44","805","<java><python><list><initialization><dictionary>","2008-11-22 20:56:41","TRUE","FALSE","311833","2014-07-30 02:22:33","71","<pre><code>def doAppend( size=10000 ):
result = []
for i in range(size):
message= ""some unique object %d"" % ( i, )
result.append(message)
return result
def doAllocate( size=10000 ):
result=size*[None]
for i in range(size):
message= ""some unique object %d"" % ( i, )
result[i]= message
return result
</code></pre>
<p><strong>Results</strong>. (evaluate each function 144 times and average the duration)</p>
<pre><code>simple append 0.0102
pre-allocate 0.0098
</code></pre>
<p><strong>Conclusion</strong>. It barely matters. </p>
<p>Premature optimization is the root of all evil.</p>
","646","3","2","14","2008-11-22 22:02:34","66","TRUE","210804","0"
"http://stackoverflow.com/users/204","http://stackoverflow.com/questions/1977925","http://stackoverflow.com/questions/1977925/#1977935","2009-12-30 14:50:03","1","3373","0","4","Server-Side Redirect in PHP","<p>I have a Java application that I need to integrate our existing PHP website with. The vendor wants us to do a server-side redirect to allow for secure authentication and single-sign-on, but I'm not sure how to do that in PHP. The vendor explained the workflow as follows:</p>
<ol>
<li>User clicks on a 'Open Application' link on our PHP site</li>
<li>The PHP application hits a page on the Java application, sending the authentication parameters</li>
<li>If successful, the PHP application sends the headers back to the user's browser, which forces a 'redirect', otherwise the PHP app displays an error</li>
</ol>
<p>What this will allow would be for our PHP app to securely talk to the Java app, and the client never has to send any sort of authentication.</p>
<p>From what I understand, .NET and Java have this capability built in, but I can't find a way in PHP to do this. Any ideas? </p>
<p><b>UPDATE</b></p>
<p>I'm not talking about using the header(""Location: ...""); function to do a redirect. The kicker with this server-side redirect is that the app does the authentication and sends all that information back to the client so that the client is then logged in. Using header(""Location: ..."") just forces the browser to go elsewhere.</p>
<p><b>UPDATE 2</b></p>
<p>autologin.php (Simulates the user logging into an external app via curl)</p>
<pre><code>// The login 'form' is at login.php
$ch = curl_init('http://domain.local/login.php');
// We are posting 2 variables, and returning the transfer just so it doesn't dump out
// Headers are processed by the callback function processHeaders()
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'processHeaders');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=user&amp;password=pass');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute curl, close the connection, and redirect the user to a 'restricted' page
$response = curl_exec($ch);
curl_close($ch);
header(""Location: http://domain.local/restricted.php"");
function processHeaders($ch, $header) {
// Dump the response headers to the client
header($header);
strlen($header);
}
</code></pre>
<p>login.php (Contains the 'login' form)</p>
<pre><code>session_start();
if($_POST) {
if($_POST['username'] == 'user' &amp;&amp; $_POST['password'] == 'pass') {
$_SESSION['auth'] = 1;
$_SESSION['token'] = md5(time());
} else {
echo 'Auth failed';
}
} else {
echo 'Invalid access type';
}
</code></pre>
<p>restricted.php (Restricted page)</p>
<pre><code>session_start();
if($_SESSION['auth']) {
echo 'Secret Token: '.$_SESSION['token'];
} else {
echo 'Please log in';
}
</code></pre>
<p>The idea is that the user wants to ultimately get to 'restricted.php'. 'login.php' contains the code necessary to log in. What I want to simulate is the user filling out the form on 'login.php' and logging the user into 'restricted.php'. </p>
<p>The above snippets of code work together on my local tests (hitting autologin.php redirects to restricted.php and the secret token is printed out), but I can't seem to get it to work cross-application. The apps will be on the same domain (https://domain.com/myapp, <a href=""https://domain.com:1234/vendorapp"" rel=""nofollow"">https://domain.com:1234/vendorapp</a>).</p>
<p>I've never done this before in any language, I'm just going off of what my vendor has told me they've done. Apparently they've never dealt with PHP before and have no idea what to do. </p>
","27","3549","<java><.net><php><server-side>","2009-12-30 01:16:57","TRUE","FALSE","1977935","2009-12-30 04:45:26","4","<p>You just output a normal HTTP redirect <a href=""http://php.net/manual/en/function.header.php"" rel=""nofollow""><code>header()</code></a> like this:</p>
<pre><code>&lt;?php header('Location: http://www.example.com/'); ?&gt;
</code></pre>
<hr>
<p>Re Update</p>
<p>If I understand correctly you'd need to do this:</p>
<ol>
<li>Browser POSTs login request to PHP server</li>
<li>PHP script packages the login information in some specific form for JSP app</li>
<li>PHP script POSTs (via <a href=""http://php.net/curl"" rel=""nofollow"">cURL</a>) or <a href=""http://php.net/soap"" rel=""nofollow"">SOAPs</a> or whatever is necessary to JSP app</li>
<li>PHP receives the response and parses out the necessary information</li>
<li>PHP sends header and/or body data back to browser</li>
</ol>
<p>Step 4, parsing the information, depends on how you send and receive the information. If you receive them in the header via cURL, you'll need to <a href=""http://php.net/manual/en/function.curl-setopt.php"" rel=""nofollow"">set</a> <code>CURLOPT_HEADER</code> to <code>true</code> and parse the necessary data out of the response. This may be as simple as splitting the string on the first blank line or more complicated, that depends on your specific situation.</p>
<p>How this logs in the user in <em>your</em> app is something you need to handle as well. The JSP app probably handles the actual password and username and hands you back a token of some sort which you'll need to keep track of.</p>
","1484","5","1","3","2009-12-30 01:21:24","5","TRUE","209820","0"
"http://stackoverflow.com/users/130964","http://stackoverflow.com/questions/1181753","http://stackoverflow.com/questions/1181753/#1181759","2014-05-13 15:41:52","18","10410","0","2","what is the c# equivalent of public final static in java","<p>In Java I can write: </p>
<pre><code>public final static MyClass foo = new MyClass(""foo"");
</code></pre>
<p>is there an equivalent in C#?</p>
","56","147","<c#><java><static><final><public>","2009-07-25 09:41:01","TRUE","FALSE","1181759","2014-05-13 15:41:52","31","<p>The closest thing (not exactly the same, <a href=""http://renaud.waldura.com/doc/java/final-keyword.shtml"" rel=""nofollow""><code>final</code> has other meanings</a> too) for Java <code>final</code> fields I can think of is <a href=""http://msdn.microsoft.com/en-us/library/acdd6hb7%28VS.71%29.aspx"" rel=""nofollow""><code>readonly</code></a>: </p>
<pre><code>public static readonly MyClass field = new MyClass(""foo"");
</code></pre>
<p>If you have a primitive type (string, int, boolean), you may want to use <code>const</code> instead.</p>
<pre><code>public const string MAGIC_STRING = ""Foo"";
</code></pre>
","608","2","2","4","2009-07-25 09:43:56","2","TRUE","209573","0"
"http://stackoverflow.com/users/169603","http://stackoverflow.com/questions/1484445","http://stackoverflow.com/questions/1484445/#1484459","2014-07-25 16:20:52","12","2565","1","7","Why are variables declared with their interface name in Java?","<p>This is a real beginner question (I'm still learning the Java basics).</p>
<p>I can (sort of) understand why methods would return a List&lt;String&gt; rather than an ArrayList&lt;String&gt;, or why they would accept a List parameter rather than an ArrayList. If it makes no difference to the method (i.e., if no special methods from ArrayList are required), this would make the method more flexible, and easier to use for callers. The same thing goes for other collection types, like Set or Map.</p>
<p>What I don't understand: it appears to be common practice to create local variables like this:</p>
<pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;();
</code></pre>
<p>While this form is less frequent:</p>
<pre><code>ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
</code></pre>
<p>What's the advantage here?</p>
<p>All I can see is a minor disadvantage: a separate ""import"" line for java.util.List has to be added. Technically, ""import java.util.*"" could be used, but I don't see that very often either, probably because the ""import"" lines are added automatically by some IDE.</p>
","61","1125","<java><interface><variables><declaration>","2009-09-27 20:50:17","TRUE","FALSE","1484459","2014-07-25 16:20:52","16","<p>When you read </p>
<pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;();
</code></pre>
<p>you get the idea that all you care about is being a <code>List&lt;String&gt;</code> and you put less emphasis on the actual implementation. Also, you restrict yourself to members declared by <code>List&lt;String&gt;</code> and not the particular implementation. You don't care if your data is stored in a linear array or some fancy data structure, as long as it looks like a <code>List&lt;String&gt;</code>.</p>
<p>On the other hand, reading the second line gives you the idea that the code <em>cares</em> about the variable being <code>ArrayList&lt;String&gt;</code>. By writing this, you are implicitly saying (to future readers) that you shouldn't blindly change actual object type because the rest of the code <strong>relies</strong> on the fact that it is really an <code>ArrayList&lt;String&gt;</code>.</p>
","923","3","1","4","2009-09-27 20:57:07","7","TRUE","209573","0"
"http://stackoverflow.com/users/252579","http://stackoverflow.com/questions/2080886","http://stackoverflow.com/questions/2080886/#2080889","2010-01-17 12:12:42","8","1010","0","1","What do the numbers in stack trace mean?","<p>How can I use the numbers in the stacktrace? What do these mean?
In eclipse I get often exceptions, for example a NullPointerException:</p>
<pre><code>java.lang.NullPointerException
at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(+68)
at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(+47)
at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.handleVmEvent(+186)
</code></pre>
","40","410","<java><eclipse><exception><console><stack-trace>","2010-01-17 12:04:38","TRUE","FALSE","2080889","2010-01-17 12:12:42","12","<p>Those are the offsets of the instruction that caused the exception from the beginning of the method.</p>
<pre><code>java.lang.NullPointerException
at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(+68)
</code></pre>
<p>The instruction at offset 68 in the method <code>com.sun.midp.lcdui.DefaultEventHandler.commandEvent</code> is causing the actual exception by accessing a null reference.</p>
<pre><code> at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(+47)
</code></pre>
<p>The instruction at offset 47 in the method <code>com.sun.midp.lcdui.AutomatedEventHandler.commandEvent</code> is a call instruction that runs the <code>com.sun.midp.lcdui.DefaultEventHandler.commandEvent</code> method.</p>
<pre><code> at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.handleVmEvent(+186)
</code></pre>
<p>The instruction at offset 186 in the method <code>com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.handleVmEvent</code> is a call instruction that runs the <code>com.sun.midp.lcdui.AutomatedEventHandler.commandEvent</code> method.</p>
","1080","4","3","6","2010-01-17 12:05:58","1","TRUE","209573","0"
"http://stackoverflow.com/users/732583","http://stackoverflow.com/questions/6432700","http://stackoverflow.com/questions/6432700/#6432997","2012-02-17 14:25:56","1","1140","0","2","PreparedStatement is not reading all my parameters for PostGIS Geography","<p>I have the following JDBC code. Note that I am attempting to use PostGIS geography:</p>
<pre><code>PreparedStatement stmt = db.prepareStatement(""INSERT INTO "" +
""source_imagery (image_path, boundary, image_time)"" +
"" VALUES (?, ST_GeographyFromText('POLYGON(("" +
""? ?, ? ?, ? ?, ? ?))'), ?)"");
stmt.setString(1, file.getAbsolutePath());
stmt.setDouble(2, bounds.getY());
stmt.setDouble(3, bounds.getX());
...
</code></pre>
<p>I am getting the following exception on the last line of code:</p>
<pre><code>org.postgresql.util.PSQLException: The column index is out of range: 3, number of columns: 2.
</code></pre>
<p>I understand that it thinks I only have 2 parameters there, but you can see that I intended there to be 10. I'm not sure why it is not reading any of the parameters within the <code>POLYGON</code>. I know that this SQL statement works if I use it directly in the database, but I'm not sure what I have to change to make it work in my Java code. Any ideas?</p>
","72","1095","<java><database><postgresql><jdbc><postgis>","2011-06-21 22:18:10","TRUE","FALSE","6432997","2011-06-21 23:05:20","2","<p>Your problem is that this:</p>
<pre><code>'POLYGON((? ?, ? ?, ? ?, ? ?))'
</code></pre>
<p>is an SQL string literal that just happens to contain eight question marks. Since that is an SQL string literal, none of the question marks inside it are considered to be placeholders. That leaves you with two placeholders: the one at the very beginning of the <code>VALUES</code> list and the one at the very end.</p>
<p>You'll have to build your polygon some other way. There might be a better way than <code>ST_GeographyFromText</code> but, alas, I don't know what it is and I don't have PostGIS set up anywhere. If necessary, you can build the POLYGON string by hand with standard string wrangling and then use a placeholder for it:</p>
<pre><code>VALUES (?, ST_GeographyFromText(?), ?)
</code></pre>
<p>The placeholder inside <code>ST_GeographyFromText</code> will be seen as a placeholder as it isn't inside a string literal and you could user <code>stmt.setString</code> to give it a value.</p>
","1001","4","2","1","2011-06-21 23:00:10","42","TRUE","208885","0"
"http://stackoverflow.com/users/592025","http://stackoverflow.com/questions/5892828","http://stackoverflow.com/questions/5892828/#5892859","2011-05-05 05:12:37","1","482","0","1","SQLException when using a PreparedStatement for Derby DB","<p>I have an SQL query that i am going to run using a PreparedStatement, and it is </p>
<pre><code>UPDATE tbl_HitsCounter SET count = ? WHERE keyid = (SELECT id FROM tbl_HitsMaster WHERE sitename = '?')
</code></pre>
<p>Now when i set the 2nd paramater, which is a string value, i am getting a strange SQLException.</p>
<pre><code>preparedStatement.setInt(1, 99);
preparedStatement.setString(2, masterKey);
</code></pre>
<p>As the setString() method is executed, i am getting an SQLException</p>
<pre><code>The column position '2' is out of range. The number of columns for this ResultSet is '1'.
</code></pre>
<p>I have no idea what this is about, i havent even executed the executeUpdate() method.</p>
","56","711","<java><sql><derby>","2011-05-05 04:56:23","TRUE","FALSE","5892859","2011-05-05 05:12:37","5","<p>There is only one placeholder in your SQL but you are trying to assign a value for the second. Your problem is that you have quoted the second placeholder, your SQL should look more like this:</p>
<pre><code>UPDATE tbl_HitsCounter
SET count = ?
WHERE keyid = (
SELECT id
FROM tbl_HitsMaster
WHERE sitename = ?
)
</code></pre>
<p>Note the lack of quotes in <code>sitename = ?</code>. This is a placeholder: <code>?</code>. This is an SQL question mark string literal: <code>'?'</code>.</p>
","506","2","1","1","2011-05-05 05:00:55","4","TRUE","208885","0"
"http://stackoverflow.com/users/1194901","http://stackoverflow.com/questions/9245970","http://stackoverflow.com/questions/9245970/#9245996","2012-02-12 02:48:22","0","210","0","1","SQL statement syntax error","<p>Having trouble with an sql statement to retrieve a record between two timestamps. This is just giving me a NullPointerException and I think it's just a syntax error, II've been searching around and I couldn't find anything. This is the statement:</p>
<pre><code>private static final String strGetRecordByDate =
""SELECT * FROM APP.MYTABLE "" +
""WHERE MYDATE &gt;= ?, AND MYDATE &lt;= ? "" +
""VALUES (?, ?)"";
</code></pre>
<p>creating the statement:</p>
<pre><code>stmtGetRecordByDate = dbConnection.prepareStatement(strGetRecordByDate);
</code></pre>
<p>The nullpointer exception shows on stmtGetRecordByDate.clearParameters():</p>
<pre><code>public Vector getRecordByDate(Date datefrom, Date dateto){
Vector&lt;String&gt; records = new Vector&lt;String&gt;();
ResultSet results = null;
java.sql.Date sqlDatefrom = new java.sql.Date(datefrom.getTime());
java.sql.Date sqlDateto = new java.sql.Date(dateto.getTime());
try {
stmtGetRecordByDate.clearParameters();
stmtGetRecordByDate.setDate(1, sqlDatefrom);
stmtGetRecordByDate.setDate(2, sqlDateto);
results = stmtGetRecordByDate.executeQuery();
while (results.next()) {
int id = results.getInt(1);
String entry = results.getString(2);
records.add(entry);
}
} catch(SQLException sqle) {
sqle.printStackTrace();
}
return records;
}
</code></pre>
<p>The Rest of the queries and statements work fine so I know that the database itself is fine there is just something wrong with this one.</p>
<p>Any suggestions would be great.
Thanks!</p>
","26","1640","<java><sql><syntax>","2012-02-12 02:37:25","TRUE","FALSE","9245996","2012-02-12 02:48:22","2","<p>You can't use a <code>VALUES</code> in that context and you have a stray comma in your WHERE clause; you want this:</p>
<pre><code>private static final String strGetRecordByDate =
""SELECT * FROM APP.MYTABLE "" +
""WHERE MYDATE &gt;= ? AND MYDATE &lt;= ?"";
</code></pre>
<p>You could also use <code>BETWEEN</code>:</p>
<pre><code>private static final String strGetRecordByDate =
""SELECT * FROM APP.MYTABLE "" +
""WHERE MYDATE BETWEEN ? AND ?"";
</code></pre>
<p>but that's just a matter of style.</p>
<p>I'm not certain about the Java side of things but you're probably getting a <code>null</code> in <code>stmtGetRecordByDate</code> because of your invalid SQL.</p>
","701","4","2","6","2012-02-12 02:43:42","6","TRUE","208885","0"
"http://stackoverflow.com/users/3497425","http://stackoverflow.com/questions/25077195","http://stackoverflow.com/questions/25077195/#25077795","2014-08-01 10:38:56","1","44","0","2","Reading json from java application with python","<p>I've been working on one project with my colleague. We have a python api, jquery web interface + java android interface.
Basically, web&amp;android should send data in json format and my api should read and process it.
Python has no troubles with reading variables from post request from jquery via cgi.
Here's snippet (without headers and stuff) that works just OK:</p>
<pre><code>import cgi
storage = cgi.FieldStorage()
print(storage)
</code></pre>
<p>Return value is (as expected) something like:</p>
<pre><code>FieldStorage(None, None, [MiniFieldStorage('command', 'xy'), MiniFieldStorage('extra', '168')])
</code></pre>
<p>With this, I can easily get value of command by calling</p>
<pre><code>storage[""command""].value
</code></pre>
<p>Unfortunately, when sending the same request from java, I don't get expected result.
Here is a snippet we use at the moment.</p>
<pre><code>HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(LOGIN_URL);
JSONObject json = null;
try {
json = new JSONObject(""{\""command\"":\""xy\"",\""extra\"":\""168\""}"");
se = new StringEntity(json.toString(), ""UTF-8"");
se.setContentType(""application/json; charset=UTF-8"");
httppost.setEntity(se);
httppost.setHeader(""Content-type"", ""application/json"");
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(
new InputStreamReader( response.getEntity().getContent(), ""UTF-8"")
);
String jsonString = null;
while((jsonString=reader.readLine())!=null){ Log.i(""response"",jsonString); }
return null;
}
catch (ClientProtocolException e) { e.printStackTrace();}
catch (IOException e) { e.printStackTrace();}
catch (JSONException e) { e.printStackTrace();}
</code></pre>
<p>When reading this request (print(storage)) in python, I get</p>
<pre><code>FieldStorage(None, None, '{""command"":""xy"",""extra"":""168""}')
</code></pre>
<p>You can notice that altough I received the string, it's not an MiniFieldStorage instance and I can not read it. </p>
<pre><code>storage.list
</code></pre>
<p>returns None. Also, I can not iterate over storage (TypeError, ""not indexable"")</p>
<p>We have been trying to solve this for hours and we are still not sure, where is the problem - whether its python/cgi or java (but I have a strong feeling that we have wrong java code since neither of us is a real java coder)</p>
<p><strong>Note for non-python coders:</strong>
I believe problem is that java sends <em>a string</em> instead of json object, but I may be also wrong - I dont have much experience with python.cgi</p>
","46","2617","<java><android><python><json><cgi>","2014-08-01 09:36:28","TRUE","FALSE","25077795","2014-08-01 10:38:56","0","<p>You don't show how you're posting your data from the ""web"" version, but it doesn't look as if you are posting JSON there: you're just sending normal form data, with the fields ""command"" and ""extra"".</p>
<p>But the Java version <em>is</em> sending JSON (your point about ""sending a string"" is irrelevant: strings are the way JSON data is transferred). </p>
<p>So, since you're not sending form-encoded data, <code>cgi.FieldStorage</code> is irrelevant and you should just read the raw data from <code>sys.stdin</code>, then decode it:</p>
<pre><code>import sys
data = sys.stdin.read()
params = json.loads(data)
</code></pre>
","630","3","1","1","2014-08-01 10:08:10","32","TRUE","204560","0"
"http://stackoverflow.com/users/178751","http://stackoverflow.com/questions/6919228","http://stackoverflow.com/questions/6919228/#6919288","2011-08-02 22:06:54","1","36","0","1","Representing dates which are a certain number of days before or after another date in a RDBMS","<p>Is there a standard way to represent dates which are a certain number of days before or after another date in an RDBMS?</p>
<p>For example, let's say Date 1 is 30th October, 2005, which can obviously be stored in a datetime column or similar in the RDB.</p>
<p>But let's say Date 2 is ""3 days After Date 1"", how would you represent it in the RDB, assuming that Date 1 can be changed anytime in the future, which means Date 2 would have to be updated automatically somehow?</p>
<p>Thanks!!</p>
","93","499","<java><sql><sql-server><database-design><date>","2011-08-02 22:00:38","FALSE","FALSE","6919288","2011-08-02 22:06:54","2","<p>Give 2 items of information, you can always work out the third</p>
<ul>
<li>Start Date + Offset = Another Date</li>
<li>Another Date - Start Date = Offset</li>
</ul>
<p>In this case, you appear to have 2 known facts</p>
<ul>
<li>Start date</li>
<li>Offset</li>
</ul>
<p>Store these and make ""Another Date"" a computed column with DATEADD</p>
<pre><code>CREATE TABLE whatever (
...
StartDate date NOT NULL,
DayOffset smallint NOT NULL,
AnotherDate AS DATEADD (day, DayOffset, StartDate),
...
</code></pre>
<p>This way, AnotherDate will be maintained by the database engine as the 2 input values changes</p>
<p>If <em>any</em> of the 3 can change then you usually have to use a trigger...</p>
","700","5","1","1","2011-08-02 22:06:54","6","TRUE","203089","0"
"http://stackoverflow.com/users/187241","http://stackoverflow.com/questions/2396695","http://stackoverflow.com/questions/2396695/#2396855","2010-03-07 16:01:21","1","777","0","3","How to combine two result sets from one table sorted independently using one SQL query?","<p>This is a simplified task which I have to solve in real project. In this project data is stored in HSQLDB. Data is accessed using JDBC.</p>
<p>I have one table:</p>
<pre><code>name | flag
-----------
aa | 1
bb | 0
cc | 1
dd | 0
ee | 1
ff | 0
</code></pre>
<p>I need to compose query to get the following table:</p>
<pre><code>name | flag
-----------
aa | 1
cc | 1
ee | 1
ff | 0
dd | 0
bb | 0
</code></pre>
<p>The final table is like rows with flag = 1 were taken and sorted <strong>ascending</strong>, rows with flag = 0 were taken and sorted <strong>descending</strong> and results were combined one after another.</p>
<p>Please, pay attention, that rows with flag = 1 and rows with flag = 0 have <strong>opposite</strong> sort order.</p>
<p>Is it possible to do in SQL? I wouldn`t like to make two queries and merge ResultSets in Java code manually.</p>
","87","890","<java><sql><union><hsqldb>","2010-03-07 15:06:23","TRUE","FALSE","2396855","2010-03-07 16:01:21","3","<p>In any SQL, only the outermost order by applies so it has to be done there.</p>
<p>I don't know if this works in your SQL dialect (and can't check sorry), but you could do this</p>
<pre><code>SELECT name, flag
FROM 'table'
ORDER BY
flag desc,
CASE WHEN flag = 1 THEN name ELSE '' END,
CASE WHEN flag = 0 THEN name ELSE '' END DESC
</code></pre>
","363","2","1","2","2010-03-07 15:56:14","50","TRUE","203089","0"
"http://stackoverflow.com/users/398713","http://stackoverflow.com/questions/7605504","http://stackoverflow.com/questions/7605504/#7605591","2011-09-30 03:11:47","1","1236","0","1","Suppressing ""X rows affected"" in SQL Server using sqlcmd and Java","<p>In my Java program, I am trying to execute a bunch of SQL scripts using <code>sqlcmd</code> via <code>getRuntime.exec()</code>.</p>
<p>Earlier, I had been using <code>osql</code> this way -</p>
<pre><code>osql -n -S SERVER -U sa -P PASSWORD -q ""SET NOCOUNT ON"" -i ""INPUTSCRIPT.sql""
</code></pre>
<p>However, in the case of <code>sqlcmd</code>, the <code>-i</code> and <code>-q</code> switches are mutually exclusive. How do I do this in <code>sqlcmd</code>?</p>
<p><strong>Note:</strong></p>
<ol>
<li><p>I'd rather not modify the SQL scripts to include <code>SET NOCOUNT ON</code> in
each file.</p></li>
<li><p>There's already been a very similar question <a href=""http://stackoverflow.com/questions/2014129/is-there-a-way-to-suppress-x-rows-affected-in-sqlcmd-from-the-command-line"">here</a>. That solution discusses setting environment variables. Is that possible using Java?</p></li>
</ol>
","65","901","<java><sql-server><sqlcmd>","2011-09-30 02:56:04","TRUE","FALSE","7605591","2011-09-30 03:11:47","4","<p>You can specify multiple scripts for the <code>i</code> switch so you can do this:</p>
<pre><code>sqlcmd ... -i SetNoCountOn.sql,MyScript1.sql,MyScript2.sql
</code></pre>
<p>That is, create a an extra script that just has <code>SET NOCOUNT ON</code></p>
","259","2","1","1","2011-09-30 03:11:47","15","TRUE","203089","0"
"http://stackoverflow.com/users/592704","http://stackoverflow.com/questions/8494106","http://stackoverflow.com/questions/8494106/#8494190","2011-12-13 18:22:23","0","133","0","1","MSSQL 2005 - JDBC4 and subqueries","<p>I tried a query which </p>
<ul>
<li>A) fills var table</li>
<li>B) gets the var table data as helpful to select next data</li>
</ul>
<blockquote>
<pre><code>CREATE PROCEDURE Test
AS
BEGIN
DECLARE @A TABLE
(
id INT NOT NULL,
name VARCHAR(50)
);
INSERT @A SELECT id,name FROM table1 WHERE id&gt;10
DECLARE @B TABLE
(
address VARCHAR(255),
city VARCHAR(128)
);
INSERT @b SELECT address,city FROM table2
WHERE id IN(SELECT id FROM @A)
END;
</code></pre>
</blockquote>
<p>... so, as a result, I have two select statements in my procedure :S The thing is... All procedures which contain just one select statement behave fine with JDBC4 but here something is wrong because when procedure contains two select statement it returns nothing :( So my question can two select statement cause the problem with jdbc4? A if it does how to fix it?</p>
","33","853","<java><sql-server-2005><tsql><jdbc><database-connection>","2011-12-13 18:15:57","TRUE","FALSE","8494190","2011-12-13 18:22:23","3","<p>Try adding <code>SET NOCOUNT ON</code> (edit: once at the top of the procedure body) to the stored procedure. The result of this is sent back and may be confusing JDBC 4: this is quite common...</p>
<p>See <a href=""http://stackoverflow.com/q/1483732/27535"">SET NOCOUNT ON usage</a> for more</p>
<pre><code>CREATE PROCEDURE Test
AS
BEGIN
SET NOCOUNT ON; -- here
DECLARE @A TABLE
...
</code></pre>
","403","2","1","4","2011-12-13 18:22:23","7","TRUE","203089","0"
"http://stackoverflow.com/users/573215","http://stackoverflow.com/questions/4978519","http://stackoverflow.com/questions/4978519/#4978550","2011-02-12 14:22:10","0","69","0","1","Is it possible to name database tables like Java types?","<p>I want to tables of RDBMS like the names of Java types. Example:</p>
<pre><code>mytld.mycompany.myproject.mypackage.mysubpackage.MyClass
</code></pre>
<p>Currently I am trying to do this with PostgreSQL. It gives me this error:</p>
<pre><code>FEHLER: falscher qualifizierter Name (zu viele Namensteile): mytld.mycompany.myproject.mypackage.mysubpackage.MyClass
</code></pre>
<p>In English this means something like:</p>
<pre><code>ERROR: wrong qualified name (to much name parts): mytld.mycompany.myproject.mypackage.mysubpackage.MyClass
</code></pre>
<ul>
<li>Wasn't there something like database objects which could be referenced with punctuation names? </li>
<li>I also may be able to substitute the ""."" by another character. Is there any robust algorithm to do this?</li>
<li>Is there a way to use the exact java class names as database tables?</li>
</ul>
<p>Thanks in advance.</p>
","55","896","<java><sql><database><postgresql><table>","2011-02-12 14:16:12","TRUE","FALSE","4978550","2011-02-12 14:22:10","7","<p>You'd have to have it in <a href=""http://www.postgresql.org/docs/9.0/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS"" rel=""nofollow"">quotes</a> with a limit of 63 characters</p>
<pre><code>""mytld.mycompany.myproject.mypackage.mysubpackage.MyClass""
</code></pre>
<p>Personally, I wouldn't do this. Your database is <em>not</em> the java code.</p>
","357","2","1","3","2011-02-12 14:22:10","6","TRUE","203089","0"
"http://stackoverflow.com/users/819911","http://stackoverflow.com/questions/8070031","http://stackoverflow.com/questions/8070031/#8070115","2011-11-10 18:59:45","0","2562","0","2","Cannot connect jdbc to sql server","<p>Below is my code for a simple select query for the Sql Server using jdbc. </p>
<pre><code>import java.sql.*;
import java.util.*;
public class DateServer{
public void dbconnect(String conn, String user, String pass){
try{
Class.forName(""com.microsoft.sqlserver.jdbc.SQLServerDriver"");
Connection con = DriverManager.getConnection(conn, user, pass);
System.out.println(""connected"");
Statement stat = con.createStatement();
String query = ""select * from headcount_new"";
ResultSet rs = stat.executeQuery(query);
}
catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
DateServer conserver = new DateServer();
conserver.dbconnect(""jdbc:sqlserver://&amp;lt;&lt;hostname&gt;&amp;gt"", ""&amp;lt;&lt;username&gt;&amp;gt"", ""&amp;lt;&lt;password&gt;&amp;gt"");
}
}
</code></pre>
<p>I am getting the following error:</p>
<pre><code>com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.Util.parseUrl(Util.java:420)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.parseAndMergeProperties(SQLServerDriver.java:856)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:838)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at DateServer.dbconnect(DateServer.java:9)
at DateServer.main(DateServer.java:22)""
</code></pre>
<p>Can someone please help me what the error is about? I am new to Java.</p>
<p>thanks.</p>
","33","1794","<java><sql-server><jdbc>","2011-11-09 18:53:48","TRUE","FALSE","8070115","2011-11-10 18:59:45","3","<p>Not sure why you have <code>&amp;lt;&lt;hostname&gt;&amp;gt</code> etc</p>
<p>A JDBC URL looks like this</p>
<pre><code> jdbc:sqlserver://SomeServer;user=SomeUser;password=XXX;
</code></pre>
","198","2","1","2","2011-11-09 19:00:20","7","TRUE","203089","0"
"http://stackoverflow.com/users/1666","http://stackoverflow.com/questions/156503","http://stackoverflow.com/questions/156503/#156528","2014-07-07 22:35:19","344","187351","77","12","How do you assert that a certain exception is thrown in JUnit 4 tests?","<p>How can I use JUnit4 idiomatically to test that some code throws an exception?</p>
<p>While I can certainly do something like this:</p>
<pre><code>@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
</code></pre>
<p>I recall that there is an annotation or an Assert.xyz or <em>something</em> that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.</p>
","70","546","<java><exception><junit><junit4><assert>","2008-10-01 06:56:08","TRUE","FALSE","156528","2014-07-07 22:35:19","408","<p>JUnit 4 has support for this:</p>
<pre><code>@Test(expected=IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
</code></pre>
","235","1","1","7","2008-10-01 07:12:13","16","TRUE","203031","14"
"http://stackoverflow.com/users/135589","http://stackoverflow.com/questions/1321745","http://stackoverflow.com/questions/1321745/#1321754","2014-09-18 23:20:48","203","41324","62","7","Scala doesn't have enums - what to use instead of an enum","<p>Scala doesn't have type-safe <code>enum</code>s like Java has. If I have a set of related constants then what is the best way in Scala to represent those constants?</p>
","57","172","<java><scala><enums>","2009-08-24 11:06:01","FALSE","FALSE","1321754","2014-03-14 16:18:18","123","<p><a href=""http://www.scala-lang.org/docu/files/api/scala/Enumeration.html"">http://www.scala-lang.org/docu/files/api/scala/Enumeration.html</a></p>
<p>Example use</p>
<pre><code> object Main extends App {
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
import WeekDay._
def isWorkingDay(d: WeekDay) = ! (d == Sat || d == Sun)
WeekDay.values filter isWorkingDay foreach println
}
</code></pre>
","492","2","1","8","2009-08-24 11:07:18","1","TRUE","203031","16"
"http://stackoverflow.com/users/287282","http://stackoverflow.com/questions/5042587","http://stackoverflow.com/questions/5042587/#5042604","2014-07-20 18:23:18","87","51020","7","2","Convert from java.util.date to JodaTime","<p>I want to convert a <code>java.util.Date</code> to <code>JodaTime</code> so as to carry out subtractions between dates. Is there a good concise way to convert from <code>Date</code> to <code>JodaTime</code>?</p>
","39","215","<java><datetime><jodatime>","2011-02-18 14:38:36","FALSE","FALSE","5042604","2011-02-18 14:45:05","165","<pre><code>java.util.Date date = ...
DateTime dateTime = new DateTime(date);
</code></pre>
<p>Make sure <code>date</code> isn't <code>null</code>, though, otherwise it acts like <code>new DateTime()</code> - I <em>really</em> don't like that.</p>
","248","1","1","7","2011-02-18 14:39:53","1","TRUE","203031","0"
"http://stackoverflow.com/users/169277","http://stackoverflow.com/questions/2489106","http://stackoverflow.com/questions/2489106/#2489145","2014-05-20 18:34:04","62","53539","29","1","Error starting jboss server","<p>I've just finished re-installing my OS, and as always install and test standard tools which I use, and now I get this error like never before when I tried to start Jboss 5 from eclipse, its quite big exeption :</p>
<pre><code>3:53:10,693 ERROR [AbstractKernelController] Error installing to Instantiated: name=AttachmentStore state=Described
java.lang.IllegalArgumentException: Wrong arguments. new for target java.lang.reflect.Constructor expected=[java.net.URI] actual=[java.io.File]
at org.jboss.reflect.plugins.introspection.ReflectionUtils.handleErrors(ReflectionUtils.java:395)
at org.jboss.reflect.plugins.introspection.ReflectionUtils.newInstance(ReflectionUtils.java:153)
at org.jboss.reflect.plugins.introspection.ReflectConstructorInfoImpl.newInstance(ReflectConstructorInfoImpl.java:106)
at org.jboss.joinpoint.plugins.BasicConstructorJoinPoint.dispatch(BasicConstructorJoinPoint.java:80)
at org.jboss.aop.microcontainer.integration.AOPConstructorJoinpoint.createTarget(AOPConstructorJoinpoint.java:282)
at org.jboss.aop.microcontainer.integration.AOPConstructorJoinpoint.dispatch(AOPConstructorJoinpoint.java:103)
at org.jboss.kernel.plugins.dependency.KernelControllerContextAction$JoinpointDispatchWrapper.execute(KernelControllerContextAction.java:241)
at org.jboss.kernel.plugins.dependency.ExecutionWrapper.execute(ExecutionWrapper.java:47)
at org.jboss.kernel.plugins.dependency.KernelControllerContextAction.dispatchExecutionWrapper(KernelControllerContextAction.java:109)
at org.jboss.kernel.plugins.dependency.KernelControllerContextAction.dispatchJoinPoint(KernelControllerContextAction.java:70)
at org.jboss.kernel.plugins.dependency.InstantiateAction.installActionInternal(InstantiateAction.java:66)
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54)
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42)
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:774)
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:540)
at org.jboss.kernel.plugins.deployment.AbstractKernelDeployer.deployBean(AbstractKernelDeployer.java:319)
at org.jboss.kernel.plugins.deployment.AbstractKernelDeployer.deployBeans(AbstractKernelDeployer.java:297)
at org.jboss.kernel.plugins.deployment.AbstractKernelDeployer.deploy(AbstractKernelDeployer.java:130)
at org.jboss.kernel.plugins.deployment.BasicKernelDeployer.deploy(BasicKernelDeployer.java:76)
at org.jboss.bootstrap.microcontainer.TempBasicXMLDeployer.deploy(TempBasicXMLDeployer.java:91)
at org.jboss.bootstrap.microcontainer.TempBasicXMLDeployer.deploy(TempBasicXMLDeployer.java:161)
at org.jboss.bootstrap.microcontainer.ServerImpl.doStart(ServerImpl.java:138)
at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:450)
at org.jboss.Main.boot(Main.java:221)
at org.jboss.Main$1.run(Main.java:556)
at java.lang.Thread.run(Thread.java:619)
Failed to boot JBoss:
java.lang.IllegalStateException: Incompletely deployed:
DEPLOYMENTS IN ERROR:
Deployment ""AttachmentStore"" is in error due to: java.lang.IllegalArgumentException: Wrong arguments. new for target java.lang.reflect.Constructor expected=[java.net.URI] actual=[java.io.File]
DEPLOYMENTS MISSING DEPENDENCIES:
Deployment ""ProfileServiceBootstrap"" is missing the following dependencies:
Dependency ""ProfileService"" (should be in state ""Installed"", but is actually in state ""Instantiated"")
Dependency ""jboss.kernel:service=Kernel"" (should be in state ""Installed"", but is actually in state ""**ERROR**"")
Deployment ""ProfileServiceDeployer"" is missing the following dependencies:
Dependency ""AttachmentStore"" (should be in state ""Installed"", but is actually in state ""**ERROR**"")
Deployment ""ProfileService"" is missing the following dependencies:
Dependency ""ProfileServiceDeployer"" (should be in state ""Installed"", but is actually in state ""Instantiated"")
Dependency ""jboss.kernel:service=KernelController"" (should be in state ""Installed"", but is actually in state ""**ERROR**"")
Deployment ""ProfileServicePersistenceDeployer"" is missing the following dependencies:
Dependency ""AttachmentStore"" (should be in state ""Installed"", but is actually in state ""**ERROR**"")
at org.jboss.kernel.plugins.deployment.AbstractKernelDeployer.internalValidate(AbstractKernelDeployer.java:278)
at org.jboss.kernel.plugins.deployment.AbstractKernelDeployer.validate(AbstractKernelDeployer.java:174)
at org.jboss.bootstrap.microcontainer.ServerImpl.doStart(ServerImpl.java:142)
at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:450)
at org.jboss.Main.boot(Main.java:221)
at org.jboss.Main$1.run(Main.java:556)
at java.lang.Thread.run(Thread.java:619)
23:53:11,600 INFO [ServerImpl] Runtime shutdown hook called, forceHalt: true
23:53:11,615 INFO [ServerImpl] Shutdown complete
</code></pre>
<p>Did anyone had the similar problem before?I've never encountered it so far</p>
","27","6016","<java><eclipse><jboss><jboss5.x>","2010-03-21 22:56:40","TRUE","FALSE","2489145","2014-05-20 18:34:04","141","<p>Looks like a bug that occurs with certain specific combinations of JRE and OS versions (see <a href=""https://jira.jboss.org/jira/browse/JBAS-6981"">https://jira.jboss.org/jira/browse/JBAS-6981</a>). Basically, the JBoss config is relying on reflection to return constructors in a certain order, and in some cases this order is different, causing the exception. Did you change your JRE version when you reinstalled, say from 1.6.0_17 to _18?</p>
<p>Anyway, the workaround is described in the JIRA issue, and also <a href=""http://community.jboss.org/thread/2390?tstart=0"">here</a>. You need to change the content of <code>conf/bootstrap/profile.xml</code>. Look for the definition of the <code>AttachmentStore</code>, and change the constructor line so that it starts:</p>
<pre><code>&lt;constructor&gt;&lt;parameter class=""java.io.File""&gt;
</code></pre>
<p>The original version doesn't have the <code>class=""java.io.File""</code> attribute.</p>
<p>Pretty sloppy of the JBoss folks, but there you go.</p>
","1010","4","1","11","2010-03-21 23:05:22","9","TRUE","203031","11"
"http://stackoverflow.com/users/806390","http://stackoverflow.com/questions/6889431","http://stackoverflow.com/questions/6889431/#6889445","2011-10-28 18:52:18","0","117","0","2","Getting screen height returns a larger screen than the physical screen can display","<p>When I get the screen size for my Android app, it returns a variable which in every case is too large for the screen to display. I use the following code to get screen size.</p>
<pre><code>final int windowHeight = getResources().getDisplayMetrics().heightPixels;
final int windowWidth = getResources().getDisplayMetrics().widthPixels;
</code></pre>
<p>Is there any way to compensate for it? Or to even fix my problem?</p>
<p>Also, is there a way to turn the battery/time bar off in the app? I think that might be the reason I'm having trouble, but I don't actually know. That's why I am asking.</p>
","82","605","<java><android><screen><titlebar>","2011-07-31 12:20:31","TRUE","FALSE","6889445","2011-10-28 18:52:18","1","<p>To disable the battery/time bar, I use this in my <code>AndroidManifest.xml</code> file, for the <code>&lt;application&gt;</code> tag :</p>
<pre><code>&lt;application
android:icon=""@drawable/icon""
android:label=""@string/app_name""
android:theme=""@android:style/Theme.NoTitleBar""
...
&gt;
</code></pre>
<p><br>
And, to get the screen's size, here's what I have in my <code>Activity</code> :</p>
<pre><code> Display display = getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
</code></pre>
","597","2","2","4","2011-07-31 12:22:54","2","TRUE","200321","0"
"http://stackoverflow.com/users/11545","http://stackoverflow.com/questions/14289518","http://stackoverflow.com/questions/14289518/#14293763","2013-01-12 18:07:30","6","227","4","2",".NET equivalent for Java bounded wildcard (IInterf<?>)?","<p>I'm stuck trying to translate some Java code that uses (bounded) wildcard generics to C#. My problem is, Java seems to allow a generic type to be both covariant and contravariant when used with a wildcard.</p>
<p>[This is a spin-off from a previous <a href=""http://stackoverflow.com/q/14277441/11545"">question</a> dealing with a simpler case of bounded-wildcards]</p>
<p><strong>Java</strong> - works:</p>
<pre><code>class Impl { }
interface IGeneric1&lt;T extends Impl&gt; {
void method1(IGeneric2&lt;?&gt; val);
T method1WithParam(T val);
}
interface IGeneric2&lt;T extends Impl&gt; {
void method2(IGeneric1&lt;?&gt; val);
}
abstract class Generic2&lt;T extends Impl&gt; implements IGeneric2&lt;T&gt; {
// !! field using wildcard
protected IGeneric1&lt;?&gt; elem;
public void method2(IGeneric1&lt;?&gt; val1) {
val1.method1(this);
//assignment from wildcard to wildcard
elem = val1;
}
}
abstract class Generic&lt;T extends Impl&gt; implements IGeneric1&lt;T&gt;, IGeneric2&lt;T&gt; {
public void method1(IGeneric2&lt;?&gt; val2) {
val2.method2(this);
}
}
</code></pre>
<p><strong>C#</strong> - doesn't compile...</p>
<pre><code>class Impl { }
interface IGeneric1&lt;T&gt; where T:Impl {
//in Java:
//void method1(IGeneric2&lt;?&gt; val);
void method1&lt;U&gt;(IGeneric2&lt;U&gt; val) where U : Impl; //see this Q for 'why'
// http://stackoverflow.com/a/14277742/11545
T method1WithParam(T to);
}
interface IGeneric2&lt;T&gt;where T:Impl {
void method2&lt;U&gt;(IGeneric1&lt;U&gt; val) where U : Impl;
}
abstract class Generic2&lt;T, TU&gt;: IGeneric2&lt;T&gt; //added new type TU
where T : Impl
where TU : Impl
{
//in Java:
//protected IGeneric1&lt;?&gt; elem;
protected IGeneric1&lt;TU&gt; elem;
//in Java:
//public void method2(IGeneric1&lt;?&gt; val1)
public void method2&lt;U&gt;(IGeneric1&lt;U&gt; val)
where U : TU //using TU as constraint
{
elem = val; //Cannot convert source type 'IGeneric1&lt;U&gt;'
//to target type 'IGeneric1&lt;TU&gt;'
}
public abstract void method1WithParam(T to);
}
abstract class Generic&lt;T&gt; : IGeneric1&lt;T&gt;, IGeneric2&lt;T&gt; where T : Impl
{
//in Java:
//public void method1(IGeneric2&lt;?&gt; val2)
public void method1&lt;U&gt;(IGeneric2&lt;U&gt; val2) where U : Impl
{
val2.method2(this);
}
public abstract T method1WithParam(T to);
public abstract void method2&lt;U&gt;(IGeneric1&lt;U&gt; val) where U : Impl;
public abstract void nonGenericMethod();
}
</code></pre>
<p>If I change <code>interface IGeneric1&lt;T&gt;</code> to <code>interface IGeneric1&lt;out T&gt;</code> the above error goes away, but <code>method1WithParam(T)</code> complains about variance: </p>
<pre><code>Parameter must be input-safe. Invalid variance: The type parameter 'T' must be
contravariantly valid on 'IGeneric1&lt;out T&gt;'.
</code></pre>
","55","3034","<java><.net><generics><covariance><bounded-wildcard>","2013-01-12 02:16:40","TRUE","FALSE","14293763","2013-01-12 13:34:45","3","<p>Let me start by saying that is definitely starting to look like a design review is in order. The original Java class aggregates an <code>IGeneric1&lt;?&gt;</code> member, but without knowing its type argument there's no possibility to call <code>method1WithParam</code> on it in a type-safe manner.</p>
<p>This means that <code>elem</code> can be used only to call its <code>method1</code> member, whose signature does not depend on the type parameter of <code>IGeneric1</code>. It follows that <code>method1</code> can be broken out into a non-generic interface:</p>
<pre><code>// C# code:
interface INotGeneric1 {
void method1&lt;T&gt;(IGeneric2&lt;T&gt; val) where T : Impl;
}
interface IGeneric1&lt;T&gt; : INotGeneric1 where T : Impl {
T method1WithParam(T to);
}
</code></pre>
<p>After this, <code>class Generic2</code> can aggregate an <code>INotGeneric1</code> member instead:</p>
<pre><code>abstract class Generic2&lt;T&gt;: IGeneric2&lt;T&gt; where T : Impl
{
protected INotGeneric1 elem;
// It's highly likely that you would want to change the type of val
// to INotGeneric1 as well, there's no obvious reason to require an
// IGeneric1&lt;U&gt;
public void method2&lt;U&gt;(IGeneric1&lt;U&gt; val) where U : Impl
{
elem = val; // this is now OK
}
}
</code></pre>
<p>Of course now you cannot call <code>elem.method1WithParam</code> unless you resort to casts or reflection, even though it is known that such a method exists and it is generic with some unknown type <code>X</code> as a type argument. However, that is the same restriction as the Java code has; it's just that the C# compiler will not accept this code while Java will only complain if you do try to call <code>method1WithParam1</code>.</p>
","1770","4","2","1","2013-01-12 13:28:41","672","TRUE","200152","0"
"http://stackoverflow.com/users/11545","http://stackoverflow.com/questions/14277441","http://stackoverflow.com/questions/14277441/#14277742","2013-01-12 03:25:53","3","456","1","1",".NET equivalent for Java wildcard generics <?> with co- and contra- variance?","<p>I'm stuck trying to translate some Java code that uses (bounded) wildcard generics to C#.
My problem is, Java seems to allow a generic type to be both covariant and contravariant when used with a wildcard. For instance: </p>
<p><strong>Java:</strong></p>
<pre><code>interface IInterf { }
class Impl implements IInterf { }
interface IGeneric1&lt;T extends Impl&gt; {
void method1(IGeneric2&lt;?&gt; val);
void method1WithParam(T val);
}
interface IGeneric2&lt;T extends Impl&gt; {
void method2(IGeneric1&lt;?&gt; val);
}
abstract class Generic&lt;T extends Impl&gt; implements IGeneric1&lt;T&gt;, IGeneric2&lt;T&gt; {
public void method1(IGeneric2&lt;?&gt; val2) {
val2.method2(this);
}
}
</code></pre>
<p>...works.</p>
<p><em>C# equivalent (?)</em></p>
<pre><code>interface IInterf { }
class Impl : IInterf { }
interface IGeneric1&lt;T&gt; where T:Impl {
//Java was:
//void method1(IGeneric2&lt;?&gt; val2);
void method1(IGeneric2&lt;Impl&gt; val);
void method1WithParam(T to);
}
interface IGeneric2&lt;T&gt;where T:Impl {
void method2(IGeneric1&lt;Impl&gt; val);
}
abstract class Generic&lt;T&gt; : IGeneric1&lt;T&gt;, IGeneric2&lt;T&gt; where T : Impl
{
//Java was:
//public void method1(IGeneric2&lt;?&gt; val2) {
public void method1(IGeneric2&lt;Impl&gt; val2)
{
val2.method2(this); //'this': Argument type 'Generic&lt;T&gt;' is not
//assignable to parameter type 'IGeneric1&lt;Impl&gt;'
}
public abstract void method1WithParam(T to);
public abstract void method2(IGeneric1&lt;Impl&gt; val);
}
</code></pre>
<p>...fails to compile - see the error in the comment. Which is to be expected, since IGeneric's generic parameter is not marked 'out' for covariance. </p>
<p>If I change this:</p>
<pre><code>interface IGeneric1&lt;T&gt; where T:Impl {
</code></pre>
<p>to this </p>
<pre><code>interface IGeneric1&lt;out T&gt; where T:Impl
</code></pre>
<p>the error goes away, but another one appears, for the declaration of the method that takes a generic parameter inside the same interface:</p>
<pre><code>interface IGeneric1&lt;T&gt; where T:Impl {
void method1WithParam(T val); //Parameter must be input-safe.
//Invalid variance: The type parameter 'T' must be
//contravariantly valid on 'IGeneric1&lt;out T&gt;'.
</code></pre>
<p>Suggestions?</p>
<p>[Also see the <a href=""http://stackoverflow.com/q/14289518/11545"">follow-up question</a> for a somewhat harder scenario]</p>
","77","2565","<java><.net><generics><covariance><bounded-wildcard>","2013-01-11 11:40:24","TRUE","FALSE","14277742","2013-01-11 12:12:11","4","<p>You need to translate the Java wildcard generic methods to C# methods that are generic in their own right. For example, this:</p>
<pre><code>interface IGeneric2&lt;T extends Impl&gt; {
void method2(IGeneric1&lt;?&gt; val);
}
</code></pre>
<p>should be translated to </p>
<pre><code>interface IGeneric2&lt;T&gt;where T:Impl {
void method2&lt;U&gt;(IGeneric1&lt;U&gt; val) where U:Impl;
}
</code></pre>
<p>It is necessary to repeat the type constraint for <code>T</code> specified by <code>IGeneric1&lt;T&gt;</code> as the type constraint for <code>U</code>.</p>
<p>The reason for this is that in the Java version there are <em>implicit</em> constraints for the type arguments of the parameters of <code>method1</code> and <code>method2</code>: if the parameter must be some kind of <code>IGeneric1&lt;X&gt;</code> then <code>X</code> must obviously be an <code>Impl</code> because otherwise it could not possibly implement <code>IGeneric1</code> for that type.</p>
<p>In C# the constraints must be explicit, so you repeat what <code>IGeneric1&lt;T&gt;</code> and <code>IGeneric2&lt;T&gt;</code> require of <code>T</code>.</p>
<p>So the equivalent code would be:</p>
<pre><code>interface IInterf { }
class Impl : IInterf { }
interface IGeneric1&lt;T&gt; where T:Impl {
void method1&lt;U&gt;(IGeneric2&lt;U&gt; val) where U:Impl;
void method1WithParam(T to);
}
interface IGeneric2&lt;T&gt;where T:Impl {
void method2&lt;U&gt;(IGeneric1&lt;U&gt; val) where U:Impl;
}
abstract class Generic&lt;T&gt; : IGeneric1&lt;T&gt;, IGeneric2&lt;T&gt; where T : Impl
{
public void method1&lt;U&gt;(IGeneric2&lt;U&gt; val2) where U:Impl
{
val2.method2(this);
}
public abstract void method1WithParam(T to);
public abstract void method2&lt;U&gt;(IGeneric1&lt;U&gt; val) where U:Impl;
}
</code></pre>
","1845","6","3","10","2013-01-11 11:57:38","17","TRUE","200152","0"
"http://stackoverflow.com/users/1088875","http://stackoverflow.com/questions/8440110","http://stackoverflow.com/questions/8440110/#8440132","2011-12-09 03:23:45","3","115","0","5","Is there a way to hide/show certain methods when instantiating an object?","<p>This question came to mind while I was writing a class that iterates over a list, with methods next() and previous() that will continuously loop (e.g. if at the last object, return it, and then reset index to 0)</p>
<p>In the constructor I was pondering adding a boolean variable, which if true would just act like a regular iterator with only next() methods and no looping. In this case, having the method previous() would make no sense. So I'm curious, is it possible to hide the previous() method in this case. Is it possible to achieve this somehow in Java or C#?. </p>
<p>What about other languages?</p>
","73","614","<c#><java><oop><design>","2011-12-09 01:42:34","FALSE","FALSE","8440132","2011-12-09 01:54:00","6","<h2>C#</h2>
<p>It is possible by making the two methods part of two different interfaces, and casting the object to one of the two interfaces. For example:</p>
<pre><code>interface ILoopingIterator
{
void Next();
void Previous();
}
interface INonLoopingIterator
{
void Next();
}
class PlaysItBothWays : ILoopingIterator, INonLoopingIterator
{
void ILoopingIterator.Next()
{
this.NextCore();
}
void ILoopingIterator.Previous()
{
// since this code will never be shared anyway, put it here
}
void INonLoopingIterator.Next()
{
this.NextCore();
}
private void NextCore()
{
// do stuff here; this method only exists so that code can be shared
}
}
</code></pre>
<p>Note that I have made the class implement <em>both</em> interfaces explicitly; this way, users of instances are <em>forced</em> to select which ""mode"" they want to use the class in. You could implement only one interface explicitly instead (providing a ""default"" mode that can be changed).</p>
<p>and now:</p>
<pre><code>var looping = (ILoopingIterator) new PlaysItBothWays(); // selects mode A
var nonLooping = (INonLoopingIterator) new PlaysItBothWays(); // selects mode B
</code></pre>
<p>Of course this does not stop anyone from casting the instance to the ""other"" interface if they want to, but if the programmer wants to subvert their own code they can also use reflection which allows much more than that.</p>
<h2>Java</h2>
<p>In Java, the above is not possible. You can come close by having the class expose methods that return instances of one of the two interfaces, and using the returned value. Of course then the object is really a factory and not a service provider, so that's feels like cheating on the problem.</p>
<pre><code>class PlaysItBothWays
{
public ILoopingIterator asLooping() { return /* something */ }
public INonLoopingIterator asNonLooping() { return /* something else */ }
}
</code></pre>
","1994","5","3","1","2011-12-09 01:47:14","5","TRUE","200152","0"
"http://stackoverflow.com/users/716092","http://stackoverflow.com/questions/6143777","http://stackoverflow.com/questions/6143777/#6143828","2011-05-27 07:20:39","1","241","1","1","is there any way to uniquely identify an user that acceses my network of websites?","<p>Is there any way, preferable in java, to uniquely identify a user? </p>
<p>I have the following scenario : I own 10 websites and i want to know when the same user accesses any of my websites. So if a user accesses site A, and after that he accesses site B i want to get a response to the question : Did this particular user accessed site A before? </p>
<p>Keeping track of the IP is a poor approach as mostly IPs are dynamic or more people share the same ip through a router. </p>
<p>I'm guessing that getting the MAC Address is a security branch :).</p>
<p>Cookies are available only for a specific url !? </p>
<p>Is there any way i can get this working ?</p>
<p>Thanks a lot!</p>
<p>EDIT:</p>
<p>I read that's not possbile to access the same cookie across multiple domains. Is it possbile after all ? Here's the reference : at: <a href=""http://stackoverflow.com/questions/6121141/cookie-problems-with-ie-and-chrome-working-with-java"">Cookie problems with IE and Chrome (working with java)</a> ""Cookies are domain based. Many browsers reject cookies on embedded resources (CSS/JS/images) which are served from other domain than the page is been served from""</p>
<p>So if i add a <code>response.addCookie(UniqueCookieForCurrentUser);</code> will it be available on other domains ? </p>
<p>I'm calling, as you suggested, from javascript :</p>
<pre><code> var query = '?requestURI=' + encodeURIComponent(requestURI)
+ '&amp;resolution=' + encodeURIComponent(resolution)
+ '&amp;websiteid=' + encodeURIComponent(id)
+ '&amp;DisplayedBanners=' + encodeURIComponent(DisplayedBanners);
document.getElementById(""body"").innerHTML = ""&lt;img src ='http://dan-vaio:8080/licenta/bannerimg.gif"" + query + ""' width = 728 height = 90 /&gt;"";
</code></pre>
<p>And in servlet i return this: (after adding the cookie to the response)</p>
<pre><code> File f = new File(filePath);
byte[] b = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(b);
ServletOutputStream out = response.getOutputStream();
out.write(b);
out.close();
</code></pre>
","82","2109","<java><cookies><ip><user-experience>","2011-05-26 19:09:32","TRUE","FALSE","6143828","2011-05-26 20:02:46","4","<p>Do as all ad networks do: You place a small web bug on each site that loads a cookie from ONE of your servers, so that regardless of which site the user goes to, they always get a cookie from the same bug server. Put a unique identifier into each site's bug so that you're not dependent on referers to identify the source site for each hit on the bug server.</p>
<hr>
<p>following:</p>
<p>Ok. on each site you'll have this on each landing page:</p>
<pre><code>&lt;img src=""http://bugs.example.com?src=siteName"" width=1 height=1 alt=""Track me, please!"" /&gt;
</code></pre>
<p>and replace <code>siteName</code> with something appropriate for each site. e.g. <code>src=siteA</code>, <code>src=siteB</code>, etc...</p>
<p>When a user comes in to site A, their browser will load this image from your webbug server, and a cookie will be issued to identify the user. A PHP session cookie, or something like the one generated by Apache's mod_usertrack). The important thing is that the cookie's value is UNIQUE for each user.</p>
<p>So now this user has a cookie in their browser, <code>example.com.track=2536t4234235423423</code>. When the user then visits site B, the browser will send this cookie along with the image request to the web bug server, and now your logs will show that cookie 2536t4234235423423 has visited both site A and site B.</p>
<p>The cookie by itself is useless, it just identifies a user. But in combination with the URL requested from the web bug server, which contains the name of the originating server, you can then see which site any particular cookie (e.g. user) visited.</p>
","1610","7","1","6","2011-05-26 19:13:48","4","TRUE","199344","0"
"http://stackoverflow.com/users/1248720","http://stackoverflow.com/questions/12606074","http://stackoverflow.com/questions/12606074/#12606093","2012-09-26 16:24:42","1","1284","0","3","SQL Statement fails, even if there are entities in the db","<p>I have a table called Produkt and in this table there are several products called test.</p>
<p>When I want to do that code:</p>
<pre><code>public Produkt findByName(String name) throws SQLException{
log.error(""Enter findByName with parameters: "" + name);
PreparedStatement ps;
ResultSet rs = null;
String query = ""SELECT * FROM Produkt WHERE name="" + name;
ps=hsqlmanager.getConnection().prepareStatement(query);
rs = ps.executeQuery();
ps.close();
if(rs.next()) return(new Produkt(rs));
else return(null);
}
</code></pre>
<p>it always gives me an sql error:</p>
<pre><code>Exception in thread ""main"" java.sql.SQLSyntaxErrorException: user
lacks privilege or object not found: TEST at
org.hsqldb.jdbc.Util.sqlException(Unknown Source) at
org.hsqldb.jdbc.Util.sqlException(Unknown Source) at
org.hsqldb.jdbc.JDBCPreparedStatement.&lt;init&gt;(Unknown Source) at
org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source) at
dao.DAOProdukt.findByName(DAOProdukt.java:157) at
dao.test_produkt_dao.main(test_produkt_dao.java:23)
</code></pre>
<p>why? i appreaciate your answer!!!</p>
<p><strong>UPDATE:</strong></p>
<p>Why are the PS incorrectly used? Pls tell me so that I can learn from that?</p>
","57","1260","<java><sql><eclipse><hsqldb>","2012-09-26 16:15:16","TRUE","FALSE","12606093","2012-09-26 16:24:42","5","<p>You're generating an invalid SQL statement, with no quotes around your <code>name</code> parameter</p>
<pre><code>String query = ""SELECT * FROM Produkt WHERE name='"" + name + ""'"";
^-- ^^^^^^
</code></pre>
","263","1","1","7","2012-09-26 16:16:32","1","TRUE","199344","0"
"http://stackoverflow.com/users/2801243","http://stackoverflow.com/questions/21341629","http://stackoverflow.com/questions/21341629/#21341665","2014-01-24 20:27:48","0","50","0","2","Can't get my Array to cancel at 0","<p>I'm trying to get my Array to cancel when a user inputs 0, but it seems to want to cancel at any inputted number. </p>
<pre><code>import java.util.Scanner;
public class Assignment2
{
public static void main (String[] args)
{
Scanner scan= new Scanner(System.in);
int count=0;
double[] nums= new double[100];
for(int i=0;i&lt;nums.length;++i)
{
nums[i]= scan.nextDouble();
nums[i]=i;
if (i == 0){
break;}
count++;
}
}
}
</code></pre>
","33","522","<java><arrays>","2014-01-24 20:11:56","TRUE","FALSE","21341665","2014-01-24 20:27:48","5","<p>You're testing <code>i</code> (your loop counter), not whatever the user actually input. You probably want:</p>
<pre><code>nums[i] = scan.nextDouble();
if (nums[i] == 0) {
break;
}
</code></pre>
<p>instead. Plus, your <code>nums[i] = i</code> line totally trashes whatever DID get input, and replaces it with the loop counter value, you're basically storing your loop values. That makes the user input totally pointless.</p>
","433","2","1","2","2014-01-24 20:14:13","3","TRUE","199344","0"
"http://stackoverflow.com/users/1187594","http://stackoverflow.com/questions/13421813","http://stackoverflow.com/questions/13421813/#13421892","2012-11-16 18:05:31","0","960","1","1","send arraylist values and fetch that array value in php","<p>I am trying to get the values from a php file.</p>
<p>I have a java file like this </p>
<pre><code>ArrayList&lt;NameValuePair&gt; al = new ArrayList&lt;NameValuePair&gt;();
for (int i = 0; i &lt; name.size(); i++)
{
al.add(new BasicNameValuePair(""names[""+i+""]"",String.valueOf(name.get(i))));
System.out.println(""arr is "" +String.valueOf(name.get(i)+ ""arrrr""+name.get(i)));
}
</code></pre>
<p>Here, <code>name</code> is an ArrayList.</p>
<p>Now I want that name ArrayList to be sent to php and loop that array and insert into database</p>
<p>this is my php file</p>
<pre><code>$con = mysql_connect(""localhost"",""aaa"",""aa"");
mysql_select_db(""aa"", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$arr[] = $_POST['names[]'];
foreach ($arr as $key)
{
$query=""insert into Orders1(names) values('$key')"";
mysql_query($query);
}
</code></pre>
<p>it's inserting <code>""""</code> (empty) value in database please help me.</p>
","55","970","<java><php><android><mysql>","2012-11-16 17:49:21","TRUE","FALSE","13421892","2012-11-16 18:05:31","2","<p>edit: and now you've deleted your php code, so the following won't make much sense...</p>
<hr>
<p>If you're using array-based field names in your html form, e.g.</p>
<p></p>
<p>then the <code>[]</code> do <strong>NOT</strong> appear in the $_POST array when the form's submitted. Instead, <code>$_POST['foo']</code> becomes a sub-array of the various values entered into those form fields.</p>
<p>That means </p>
<pre><code>$arr[] = $_POST['names[]'];
</code></pre>
<p>is almost certainly an undefined array key, returning a <code>NULL</code>, which you then append to the <code>$arr</code> array. You loop over $arr and insert the values, but insert only that null.</p>
<p>Try, simply:</p>
<pre><code>foreach($_POST['names'] as $val) {
$v = mysql_real_escape_string($val);
$sql = ""ISNERT INTO .... VALUES ('$v');
}
</code></pre>
<p>note the use of the escape function. Your code is highly vulnerable to <a href=""http://bobby-tables.com"" rel=""nofollow"">SQL injection attacks</a> and would leave your server open to a total remote compromise.</p>
","1063","8","2","6","2012-11-16 17:54:16","5","TRUE","199344","0"
"http://stackoverflow.com/users/1625316","http://stackoverflow.com/questions/12127229","http://stackoverflow.com/questions/12127229/#12127237","2012-08-26 03:10:36","0","74","0","1","order by mysql request in java","<p>please I have a problem in this query</p>
<p><code>ResultSet rs = stmt.executeQuery(""select * from user order by""+var);</code></p>
<p>I can get the valor of var, but it can't be be executed.
var variable i get it through</p>
<p><code>&lt;th&gt;&lt;a href=""ManageUser?action=order&amp;var=nom""&gt;Nom&lt;/a&gt;&lt;/a&gt; &lt;/th&gt;</code></p>
<p>in DAO I have.</p>
<pre><code>public static ArrayList Order(String var) throws SQLException,ClassNotFoundException
{
ArrayList&lt;User&gt; list=new ArrayList&lt;User&gt;();
Connection con = createDBConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(""select * from user order by nom"");
int i=0;
while(rs.next())
{
User cb= new User();
cb.setID(rs.getInt(1));
cb.setNom(rs.getString(2));
cb.setPrenom(rs.getString(3));
cb.setEmail(rs.getString(4));
cb.setStatut(rs.getString(5));
cb.setPassword(rs.getString(6));
cb.setDate(rs.getDate(7));
list.add(cb);
i++;
}
stmt.close();
con.close();
return list;
}
</code></pre>
<p>please HELP.</p>
","30","1287","<java><mysql><java-ee>","2012-08-26 02:39:33","TRUE","FALSE","12127237","2012-08-26 03:10:36","2","<pre><code>ResultSet rs = stmt.executeQuery(""select * from user order by""+var);
^---missing space
</code></pre>
<p>without that space, you get</p>
<pre><code>... order bysomefield
^---
</code></pre>
<p>which is a syntax error.</p>
","306","2","2","2","2012-08-26 02:40:58","1","TRUE","199344","0"
"http://stackoverflow.com/users/832411","http://stackoverflow.com/questions/10459035","http://stackoverflow.com/questions/10459035/#10459042","2012-05-05 05:09:54","0","187","0","1","How to run a Java program on every file in a directory in UNIX?","<p>I have a java class file which I need to run on every file in a directory. Its in the form of</p>
<p>java StripEnronHeaders &lt; FILE NAME > </p>
<p>I'm very new to UNIX so I'm wondering if there is a UNIX command or set of commands that will allow me to run that java program recursively for every file in a directory?</p>
","63","329","<java><shell><unix>","2012-05-05 05:08:17","FALSE","FALSE","10459042","2012-05-05 05:09:54","4","<pre><code>find . -type f -exec java StripEnronHeaders {} \;
</code></pre>
<p>though this will execute java for EVERY file you find. If that app can accept multiple files on the command line, then this'll be more efficient:</p>
<pre><code>find . -type f|xargs java StripEnronHeaders
</code></pre>
","299","1","2","1","2012-05-05 05:09:54","1","TRUE","199344","0"
"http://stackoverflow.com/users/1456004","http://stackoverflow.com/questions/13431589","http://stackoverflow.com/questions/13431589/#13431626","2013-11-23 09:20:46","0","183","0","5","What is the difference between capturing and non-capturing Pattern?","<p>In the <code>Pattern</code> class it says there are two types of regex: <em>capturing</em> and <em>non-capturing</em>, but I don't understand the difference. </p>
<p><a href=""http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#special"" rel=""nofollow"">http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#special</a></p>
<p>How are they different? When do I have to use each one? Any examples?</p>
","67","437","<java><regex><pattern-matching>","2012-11-17 14:39:49","FALSE","FALSE","13431626","2012-11-17 15:32:47","3","<p>Consider a pattern where you need to check for a variety of things in a single position, e.g a bunch of different two character patterns. Normally you use the <code>|</code> alternation operator:</p>
<pre><code>/(ab|cd|ef)/
</code></pre>
<p>which requires use of <code>()</code> brackets as well. But those brackets also act as a capturing group. Maybe you really don't want to capture those char sequences, just check for their presence, which is where the non-capturing groups come into play:</p>
<pre><code>/(?:ab|cd|ef)/
</code></pre>
","545","2","2","1","2012-11-17 14:44:09","5","TRUE","199344","0"
"http://stackoverflow.com/users/1154656","http://stackoverflow.com/questions/10806839","http://stackoverflow.com/questions/10806839/#10806929","2012-05-29 21:25:23","-1","1156","0","1","How to get multiple rows of JSON data and put it into some sort of Array?","<p>I tried to retrieve multiple rows of JSON data and display it but im not able to retrieve all the rows,im only getting the top(first) row of the database table.And im confused about how can i put the retrieved JSON data into some sort of array and access the individual rows?</p>
<p>I have provided the code relevant to the problem.
Yes i have done enough research before posting this question.I actually found one question which was some what similar to mine but nobody has answered it so i'm making this post.</p>
<p>Thank You</p>
<p>Below is the code from my Freebies.java class where i'm trying to retrieve JSONdata by calling getAllFreebies function from UserFunctions.java class</p>
<pre><code>UserFunctions uf = new UserFunctions();
JSONObject json = uf.getAllFreebies();
System.out.println(json);
</code></pre>
<p>Below is the code of the function getAllFreebies() in the class UserFunctions.java</p>
<pre><code>public JSONObject getAllFreebies(){
List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
params.add(new BasicNameValuePair(""tag"", getAllFreebies_tag));
JSONObject json = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
return json;
}
</code></pre>
<p>Below is the code from index.php where im calling getFreebies() function from DB_Function.php file</p>
<pre><code>else if($tag = 'getAllFreebies'){
$getAllFreebies = $db-&gt;getFreebies($username,$catagory,$subcatagory,$title,$condition,$description,$address,$city,$state,$country,$zipcode,$posted_on);
if($getAllFreebies)
{
$response[""success""] = 1;
$response[""getAllFreebies""][""username""] = $getAllFreebies[""username""];
$response[""getAllFreebies""][""catagory""] = $getAllFreebies[""catagory""];
$response[""getAllFreebies""][""subcatagory""] = $getAllFreebies[""subcatagory""];
$response[""getAllFreebies""][""title""] = $getAllFreebies[""title""];
$response[""getAllFreebies""][""item_condition""] = $getAllFreebies[""item_condition""];
$response[""getAllFreebies""][""description""] = $getAllFreebies[""description""];
$response[""getAllFreebies""][""address""] = $getAllFreebies[""address""];
$response[""getAllFreebies""][""city""] = $getAllFreebies[""city""];
$response[""getAllFreebies""][""state""] = $getAllFreebies[""state""];
$response[""getAllFreebies""][""country""] = $getAllFreebies[""country""];
$response[""getAllFreebies""][""zipcode""] = $getAllFreebies[""zipcode""];
$response[""getAllFreebies""][""posted_on""] = $getAllFreebies[""posted_on""];
echo json_encode($response);
}else {
$response[""error""] =1;
$response[""error_msg""] = ""Error in getAllFreebies"";
echo json_encode($response);
}
}// end of getAllFreebies tag
</code></pre>
<p>Below is the code of my getFreebies() function of DB_function.php which is responsible for performing queries on MySQL database.</p>
<pre><code>public function getFreebies(){
$result = mysql_query(""SELECT * FROM freebie"") or die(mysql_error());
return mysql_fetch_array($result);
}
</code></pre>
<p>Below is the logcat:</p>
<pre><code>05-30 00:13:23.960: E/JSON(318): {""tag"":""getAllFreebies"",""success"":1,""error"":0,""getAllFreebies"":{""username"":""viking"",""catagory"":""Art"",""subcatagory"":""Potrait"",""title"":""Potrait"",""item_condition"":""Good"",""description"":""potarit"",""address"":""Blah St"",""city"":""lalaland"",""state"":""NA"",""country"":""NA"",""zipcode"":""blah"",""posted_on"":""2012-05-27""}}
</code></pre>
","73","3655","<java><php><android><mysql><json>","2012-05-29 21:17:18","TRUE","FALSE","10806929","2012-05-29 21:25:23","3","<p>mysql_fetch_array() only returns a single row of the query result set as an array. It does not fetch ALL of the rows. Since you're returning the results of the fetch from your getFreebies method, instead of the result handle itself, it is impossible for the calling code to get any other results from the query, other than the one row you've fetched.</p>
<p>As such, you should have:</p>
<pre><code>public function getFreebies() {
$result = ...
return($result);
}
</code></pre>
<p>and</p>
<pre><code>$getAllFreebies = $db-&gt;getFreebies(...);
$data = array();
while($row = mysql_fetch_assoc($getAllFreebies)) {
$data[] = array(
.... your variable assignments here ...
);
}
echo json_encod($data);
</code></pre>
","737","3","2","3","2012-05-29 21:25:23","8","TRUE","199344","0"
"http://stackoverflow.com/users/823398","http://stackoverflow.com/questions/7971262","http://stackoverflow.com/questions/7971262/#7971352","2011-11-01 19:10:08","-7","147","0","5","I must have precision","<p>I have gotten my android code well developed and again run into problemss with precision can someone help me get past this, please</p>
<p>Here is my code</p>
<pre><code>// m1_els1_met = 310 and m1_els2_met = 320
static final double ELIP = 0.7854;
static final double mm_to_inch = 0.0393700787; //multiply
double m1_els1_met = new Double(m1_els1.getText().toString());
double m1_els1_eng = new Double(m1_els1_met) * mm_to_inch;
double m1_els2_met = new Double(m1_els2.getText().toString());
double m1_els2_eng = new Double(m1_els2_met) * mm_to_inch;
// elliptical area equals D1 x D2 x 0.7854
double eliptical_area_inches = (m1_els1_eng * m1_els2_eng) * ELIP;
String eliptical_area_inches_result = String.format(""%.4f"", eliptical_area_inches);
m1_sa_in.setText(eliptical_area_inches_result);
</code></pre>
<p>I am expecting m1_sa_in to equal 121.8784 but I get 120.7 something instead. With precision my program is worthless.</p>
","21","941","<java><numeric-precision>","2011-11-01 18:42:04","TRUE","FALSE","7971352","2011-11-01 19:10:08","5","<p>Your expectation is wrong:</p>
<pre><code>310 * 0.0393700787 = 12.204724397
320 * 0.0393700787 = 12.598425184
12.204... * 12.598... = 153.7603007207
153.7603007207 * 0.7854 = 120.76334018
</code></pre>
","208","1","1","1","2011-11-01 18:48:38","6","TRUE","199344","0"
"http://stackoverflow.com/users/1026067","http://stackoverflow.com/questions/8275813","http://stackoverflow.com/questions/8275813/#8275834","2011-11-29 19:42:28","5","299","0","7","In java, will the program ""remember"" the result if you call the same function for the second time?","<p>This question came up when I was thinking about the algorithm to fast compute the power of a number, say compute <code>x^n</code>.</p>
<p>In Java, the recursive part is something like:</p>
<pre><code>return power(x,n/2) * power(x,n/2);
</code></pre>
<p>So after the program has returned the value of <code>power(x,n/2)</code>, will it go through the whole recursive process again to compute the value for the second <code>power(x,n/2)</code>?</p>
<p>If so, should we store the value in some variable first, then return the square of that value?</p>
","98","556","<java><algorithm><recursion><memoization>","2011-11-26 02:14:47","TRUE","FALSE","8275834","2011-11-26 02:34:20","12","<p>What you have in mind is called <strong>memoization</strong>: A pure function (i.e. a function whose return value depends only on the argument values) can remember the result for arguments that it has previously encountered.</p>
<p>Memoization is performed by some high-level special-purpose languages like Maple. However, general-purpose languages don't have this (rather complex) behaviour by default.</p>
<p>However, in your case this isn't necessary. Rather than using recursion, your algorithm is better implemented as <em>iteration</em>. <a href=""http://en.wikipedia.org/wiki/Exponentiation_by_squaring"">Binary exponentiation</a> by repeated squaring is the standard algorithm.</p>
<p>Here's some C-like pseudo-code (my Java isn't 100%):</p>
<pre><code>// compute pow(base, exponent)
int result = 1;
int term = base;
while (exponent != 0)
{
if (exponent % 2 != 0) { result *= term; }
term = term * term;
exponent /= 2;
}
return result;
</code></pre>
<p>For some examples, 7 is 111 in binary, so <em>b</em><sup>7</sup>&nbsp;=&nbsp;<em>b</em><sup>1</sup>&nbsp;&times;&nbsp;<em>b</em><sup>2</sup>&nbsp;&times;&nbsp;<em>b</em><sup>4</sup>, and we only need to keep track of <em>one</em> copy of the running term. Another one: 5 = 101b, so <em>b</em><sup>5</sup>&nbsp;=&nbsp;<em>b</em><sup>1</sup>&nbsp;&times;&nbsp;1&nbsp;&times;&nbsp;<em>b</em><sup>4</sup>.</p>
<p><sub>In C++ it's quite easy to build a generic memoizing wrapper for any function <code>R f(T1, T2, ..., TN)</code> that stores the memory in a hash map <code>std::unordered_map&lt;std::tuple&lt;T1, ..., TN&gt;, R&gt;</code>; upon invocation the wrapper checks if the argument-tuple already exists, and if yes, it returns the value from the map, and if no it performs the computation and inserts the result into the map. I'm sure something similar can be rigged up in Java.</sub></p>
","1870","6","1","2","2011-11-26 02:21:52","7","TRUE","197735","0"
"http://stackoverflow.com/users/900858","http://stackoverflow.com/questions/7135379","http://stackoverflow.com/questions/7135379/#7135402","2011-08-21 10:13:05","2","142","0","4","What is the difference in true and false in this code?","<p>What is the difference between true and false in this code?</p>
<pre><code> public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
int cbcheck = 1;
} else {
int cbcheck = 0;
}
}
@Override
public void onClick(View v) {
;
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.registerbut:
onCheckedChanged(cbagree, false);
if (cbcheck == 1) {
Intent intent = new Intent(this,
RegisterScreen2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
} else if (cbcheck == 0){
}
break;
}
}
</code></pre>
<p>The part where it says <code>onCheckedChanged(cbagree, true);</code> what would happen if I passed false instead?</p>
<p>I wish to make it so if the box is checked the intent will run, otherwise it'll state for you to check the box. I have tried saving the checkboxing and then loading it using savepreferences and loadpreferences but I find that is too much hassle. Is there any other way to accomplish this?</p>
<p>This is in android btw.</p>
","54","1267","<java><android>","2011-08-20 23:32:47","TRUE","FALSE","7135402","2011-08-20 23:47:39","4","<p>As it's written, there's no difference since your function <code>onCheckedChanged()</code> literally does nothing: In two local blocks local variables get declared which immediately go out of scope, and there is no net effect of this function at all.</p>
<p>Perhaps you mean to modify some private class member instead?</p>
<hr>
<p>Suggestion: here's an idea on passing the state change through a private member:</p>
<pre><code>class Thing
{
private int cbcheck;
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
cbcheck = isChecked ? 1 : 0;
}
/* ... */
}
</code></pre>
","620","3","1","6","2011-08-20 23:37:34","5","TRUE","197735","0"
"http://stackoverflow.com/users/11114","http://stackoverflow.com/questions/7388397","http://stackoverflow.com/questions/7388397/#7388469","2011-09-12 13:35:23","0","123","0","6","Help in writing a Regular expression for a string","<p>Hi please help me out in getting regular expression for the
following requirement</p>
<p>I have string type as</p>
<pre><code>String vStr = ""Every 1 nature(s) - Universe: (Air,Earth,Water sea,Fire)"";
String sStr = ""Every 1 form(s) - Earth: (Air,Fire) "";
</code></pre>
<p>from these strings after using regex I need to get values as <code>""Air,Earth,Water sea,Fire""</code> and <code>""Air,Fire""</code></p>
<p>that means after </p>
<pre><code>String vStrRegex =""Air,Earth,Water sea,Fire"";
String sStrRegex =""Air,Fire"";
</code></pre>
<p>All the strings that are input will be seperated by <code>"":""</code> and values needed are inside brackets always</p>
<p>Thanks</p>
","49","675","<java><regex><string>","2011-09-12 13:11:13","TRUE","FALSE","7388469","2011-09-12 13:21:39","4","<p>The regular expression would be something like this:</p>
<pre><code>: \((.*?)\)
</code></pre>
<p>Spelt out:</p>
<pre><code>Pattern p = Pattern.compile("": \\((.*?)\\)"");
Matcher m = p.matcher(vStr);
// ...
String result = m.group(1);
</code></pre>
<p>This will capture the content of the parentheses as the first capture group.</p>
","338","3","2","6","2011-09-12 13:16:24","5","TRUE","197735","0"
"http://stackoverflow.com/users/17428","http://stackoverflow.com/questions/662598","http://stackoverflow.com/questions/662598/#662625","2009-03-27 21:55:48","14","8901","6","1","Howto design for extension","<p>There is a <a href=""http://checkstyle.sourceforge.net/"">Checkstyle</a> rule <a href=""http://checkstyle.sourceforge.net/config%5Fdesign.html#DesignForExtension"">DesignForExtension</a>. It says: if you have a public/protected method which is not abstract nor final nor empty it is not ""designed for extension"". Read the <a href=""http://checkstyle.sourceforge.net/config%5Fdesign.html#DesignForExtension"">description for this rule on the Checkstyle page</a> for the rationale.</p>
<p>Imagine this case. I have an abstract class which defines some fields and a validate method for those fields:</p>
<pre><code>public abstract class Plant {
private String roots;
private String trunk;
// setters go here
protected void validate() {
if (roots == null) throw new IllegalArgumentException(""No roots!"");
if (trunk == null) throw new IllegalArgumentException(""No trunk!"");
}
public abstract void grow();
}
</code></pre>
<p>I have also a subclass of Plant:</p>
<pre><code>public class Tree extends Plant {
private List&lt;String&gt; leaves;
// setters go here
@Overrides
protected void validate() {
super.validate();
if (leaves == null) throw new IllegalArgumentException(""No leaves!"");
}
public void grow() {
validate();
// grow process
}
}
</code></pre>
<p>Following the Checkstyle rule the Plant.validate() method is not designed for extension. But how do I design for extension in this case? </p>
","26","1486","<java><inheritance><class-design>","2009-03-19 15:18:34","TRUE","FALSE","662625","2009-03-19 15:36:56","12","<p>The rule is complaining because it is possible for a deriving (extending) class to completely replace the functionality you provided without telling you about it. It's a strong indication that you haven't fully considered how the type might be extended. What it wants you to do instead is something like this:</p>
<pre><code>public abstract class Plant {
private String roots;
private String trunk;
// setters go here
private void validate() {
if (roots == null) throw new IllegalArgumentException(""No roots!"");
if (trunk == null) throw new IllegalArgumentException(""No trunk!"");
validateEx();
}
protected void validateEx() { }
public abstract void grow();
}
</code></pre>
<p>Note that now someone can still supply their own validation code, but they can't replace your pre-written code. Depending on how you meant to use the <code>validate</code> method you could also make it public final instead.</p>
","968","2","1","9","2009-03-19 15:23:55","5","TRUE","195707","0"
"http://stackoverflow.com/users/13435","http://stackoverflow.com/questions/465886","http://stackoverflow.com/questions/465886/#465908","2009-01-21 19:50:49","3","2627","0","4","Determining which submit button was used?","<p>Is it possible to determine which submit button was used? I have a confirmation form with 2 submit buttons. The first would confirm the order, do some DB tasks, then redirect. The second, which is a Cancel button, will just redirect to the same page, without doing any DB tasks.</p>
<p>Is it possible in the servlet, preferably via the request object, to determine which submit button was used? I'd prefer not to be dependent on Javascript, as that is pretty simple, but will resort to it if the only possibility.</p>
<p>Thanks.</p>
","41","541","<java><html><http><forms><servlets>","2009-01-21 16:08:33","FALSE","FALSE","465908","2009-01-21 19:50:49","10","<pre><code>&lt;button name=""someName"" value=""someValue"" type=""submit""&gt;Submit&lt;/button&gt;
&lt;button name=""otherName"" value=""otherValue"" type=""submit""&gt;Cancel&lt;/button&gt;
</code></pre>
<p>You'll have <code>someName=someValue</code> or <code>otherName=otherValue</code> in your request data</p>
","305","1","1","4","2009-01-21 16:14:19","6","TRUE","195217","0"
"http://stackoverflow.com/users/505075","http://stackoverflow.com/questions/4830685","http://stackoverflow.com/questions/4830685/#4830771","2011-01-28 16:56:20","3","223","1","1","How to get the last 3 distinct ids from a mysql table","<p><img src=""http://i.stack.imgur.com/wLW8q.png"" alt=""Database""></p>
<p>Ok so basically I have my database table. The first column is the id. The second is a pkg_id. The 3rd is not important and the 4th is the previous id that the pkg_id was located at. I need to pull the last 3 pkg_id's from the table. So basically I need to pull the last 3 17879 pkg_id's and the last 3 3075. So in this example I need to pull id 9 , 7 , 6 for 17879 and id 8, 5, 3 for 3075.</p>
<p>I can't get my head around it. I do have access to the previous id that it was. So you see that for id 9 it says that 17879 was last in id 7. That id 8 was last in id 5.</p>
<p>If anybody could help me write a query that would be great. I'm also using Java for database access so it doesn't have to be just in mysql. Thanks so much.</p>
","53","820","<java><mysql><jdbc><greatest-n-per-group>","2011-01-28 16:36:58","FALSE","FALSE","4830771","2011-01-28 16:56:20","5","<pre><code>SELECT m.*
FROM (
SELECT pkg_id,
COALESCE(
(
SELECT id
FROM mytable mi
WHERE mi.pkg_id = md.pkg_id
ORDER BY
id DESC
LIMIT 2, 1
), 0) AS mid
FROM (
SELECT DISTINCT pkg_id
FROM mytable
) md
) q
JOIN mytable m
ON m.pkg_id &lt;= q.pkg_id
AND m.pkg_id &gt;= q.pkg_id
AND m.id &gt;= q.mid
</code></pre>
<p>Create an index on <code>mytable (pkg_id, id)</code> for this to work fast.</p>
<p>Note this condition: <code>m.pkg_id &lt;= q.pkg_id AND m.pkg_id &gt;= q.pkg_id</code> instead of mere <code>m.pkg_id = q.pkg_id</code>. This is required for the index to be used efficiently.</p>
","857","2","1","1","2011-01-28 16:44:27","8","TRUE","195217","0"
"http://stackoverflow.com/users/192351","http://stackoverflow.com/questions/4659287","http://stackoverflow.com/questions/4659287/#4659415","2011-01-11 15:57:56","2","1023","0","1","Error: column ""this_.phitorsionangle"" must appear in the GROUP BY clause or be used in an aggregate function","<p>I'm having some trouble with an sql query. I'm using Hibernate Criteria to build the query. I create some bins from a database by rounding the values with certain intervals (the binSize) and then grouping them. This works great when I try it directly in SQL with the query:</p>
<pre>
SELECT floor(phiTorsionAngle / 2) * 2 as phiTorsionAngleBin,
floor(psiTorsionAngle / 2) * 2 as psiTorsionAngleBin,
floor(phiTorsionAngle / 2) + 180 as phiTorsionAngleBinIndex,
floor(psiTorsionAngle / 2) + 180 as psiTorsionAngleBinIndex,
count(*) as numberOfResidues
FROM residue
WHERE phitorsionangle IS NOT NULL
AND psitorsionangle IS NOT NULL
GROUP BY phiTorsionAngleBin, psiTorsionAngleBin
</pre>
<p>But when I try it with Hibernate Criteria it fails. This is the code to build the query:</p>
<pre><code>ScrollableResults phiPsiBins = createCriteria()
.setProjection(Projections.projectionList()
.add(Projections.sqlGroupProjection(
""floor(phiTorsionAngle / "" + binSize + "") * "" + binSize + "" as phiTorsionAngleBin, "" +
""floor(psiTorsionAngle / "" + binSize + "") * "" + binSize + "" as psiTorsionAngleBin, "" +
""floor(phiTorsionAngle / "" + binSize + "") + 180 as phiTorsionAngleBinIndex, "" +
""floor(psiTorsionAngle / "" + binSize + "") + 180 as psiTorsionAngleBinIndex, "" +
""count(*) as numberOfResidues"",
""phiTorsionAngleBin, psiTorsionAngleBin"",
new String[] {""phiTorsionAngleBin"", ""psiTorsionAngleBin"", ""phiTorsionAngleBinIndex"", ""psiTorsionAngleBinIndex"", ""numberOfResidues""},
new Type[] {Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.INTEGER, Hibernate.INTEGER, Hibernate.INTEGER})))
.add(Restrictions.isNotNull(""phiTorsionAngle""))
.add(Restrictions.isNotNull(""psiTorsionAngle""))
.setResultTransformer(Transformers.aliasToBean(PhiPsiBinResult.class))
.setCacheMode(CacheMode.IGNORE)
.scroll(ScrollMode.FORWARD_ONLY);
</code></pre>
<p>This is the error message I'm getting, with the full stacktrace below it:</p>
<pre>
ERROR: column ""this_.phitorsionangle"" must appear in the GROUP BY clause or be used in an aggregate function
WARN 2011-01-11 16:13:43,047 main JDBCExceptionReporter:100 - SQL Error: 0, SQLState: 42803
ERROR 2011-01-11 16:13:43,047 main JDBCExceptionReporter:101 - ERROR: column ""this_.phitorsionangle"" must appear in the GROUP BY clause or be used in an aggregate function
Position: 143
Exception in thread ""main"" org.hibernate.exception.SQLGrammarException: could not execute query using scroll
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.scroll(Loader.java:2340)
at org.hibernate.loader.criteria.CriteriaLoader.scroll(CriteriaLoader.java:113)
at org.hibernate.impl.SessionImpl.scroll(SessionImpl.java:1561)
at org.hibernate.impl.CriteriaImpl.scroll(CriteriaImpl.java:320)
at nl.ru.cmbi.pdbeter.core.controller.DAO.ResidueDAO.getPhiPsiBinSet(ResidueDAO.java:236)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy27.getPhiPsiBinSet(Unknown Source)
at nl.ru.cmbi.pdbeter.statistics.controller.StatisticsFunctions.makeRamachandranPlot(StatisticsFunctions.java:26)
at nl.ru.cmbi.pdbeter.statistics.controller.StatisticsMain.start(StatisticsMain.java:39)
at nl.ru.cmbi.pdbeter.statistics.controller.StatisticsMain.main(StatisticsMain.java:33)
Caused by: org.postgresql.util.PSQLException: ERROR: column ""this_.phitorsionangle"" must appear in the GROUP BY clause or be used in an aggregate function
Position: 143
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2062)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1795)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:479)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:367)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:271)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1812)
at org.hibernate.loader.Loader.scroll(Loader.java:2305)
... 18 more
</pre>
<p>I tried adding the phiTorsionAngle and psiTorsionAngle to the GROUP BY, and this seems to work, but it makes no sense to do that. I don't want to group by every possible value for phiTorsionAngle, I want to group by the entire bin, probably containing a lot of different values for phiTorsionAngle. Why does it give me this error and how do I work around it?</p>
<p>UPDATE: I didn't actually try to let the query run until it was finished yet, and I got a Java out of heap space error, because it tried to load about 19 million entries, so adding the phiTorsionAngle and psiTorsionAngle to the grouping is now entirely out of the question :)</p>
","108","5913","<java><hibernate><postgresql><group-by><criteria>","2011-01-11 15:30:47","TRUE","FALSE","4659415","2011-01-11 15:57:56","0","<pre><code>SELECT phiTorsionAngleHalfFloor * 2 as phiTorsionAngleBin,
psiTorsionAngleHalfFloor * 2 as psiTorsionAngleBin,
phiTorsionAngleHalfFloor + 180 as phiTorsionAngleBinIndex,
psiTorsionAngleHalfFloor + 180 as psiTorsionAngleBinIndex,
numberOfResidues
FROM (
SELECT FLOOR(phiTorsionAngleHalf / 2) AS phiTorsionAngleHalfFloor,
FLOOR(psiTorsionAngleHalf / 2) AS psiTorsionAngleHalfFloor,
COUNT(*) AS numberOfResidues
FROM residue
WHERE phitorsionangle IS NOT NULL
AND psitorsionangle IS NOT NULL
GROUP BY
phiTorsionAngleHalfFloor, psiTorsionAngleHalfFloor
) q
</code></pre>
","727","0","1","2","2011-01-11 15:41:30","11","TRUE","195217","0"
"http://stackoverflow.com/users/348285","http://stackoverflow.com/questions/9191327","http://stackoverflow.com/questions/9191327/#9191375","2014-07-16 00:52:14","4","2399","0","1","Java regex pattern to remove a parameter from query string","<p>I am looking for removing <code>foo</code> parameter and its value from all the possible following query strings in Java. </p>
<p>Is there a regex pattern to do this?</p>
<pre><code>http://localhost/test?foo=abc&amp;foobar=def
http://localhost/test?foobar=def&amp;foo=abc
http://localhost/test?foo=abc
http://localhost/test?foobar=def&amp;foo=abc&amp;foobar2=def
</code></pre>
<p>The resulting strings would be </p>
<pre><code>http://localhost/test?foobar=def
http://localhost/test?foobar=def
http://localhost/test
http://localhost/test?foobar=def&amp;foobar2=def
</code></pre>
","58","587","<java><regex>","2012-02-08 10:16:53","TRUE","FALSE","9191375","2012-02-08 10:53:07","13","<p>This regex should match the GET param and its value...</p>
<pre><code>(?&lt;=[?&amp;;])foo=.*?($|[&amp;;])
</code></pre>
<p><a href=""http://regexr.com?2vuqj"">RegExr</a>.</p>
<p>Just replace it with an empty string.</p>
","225","3","1","6","2012-02-08 10:20:01","4","TRUE","193242","0"
"http://stackoverflow.com/users/717520","http://stackoverflow.com/questions/5797879","http://stackoverflow.com/questions/5797879/#5797904","2011-04-27 00:11:33","2","702","0","1","Reordering li elements for jQuery ""sortable"" problem","<p>I have built a sortable list using jQuery UI's sortable feature, this is working fine except that I need to be able to reorder the <code>&lt;li&gt;</code> at the beginning depending upon a string containing the element's order but I cannot figure out the syntax how to do this with JavaScript.</p>
<p>Lets say I have the following: </p>
<pre><code>&lt;ul&gt;
&lt;li id=""A"" &gt;Apple&lt;/li&gt;
&lt;li id=""B"" &gt;Banana&lt;/li&gt;
&lt;li id=""C"" &gt;Carrot&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<p>and the string ""C,A,B"" </p>
<p>I would like to have a JavaScript function for reordering my the items inside the which bases the ordering off of the order of the string. Ending up with this:</p>
<pre><code> &lt;ul&gt;
&lt;li id=""C"" &gt;Carrot&lt;/li&gt;
&lt;li id=""A"" &gt;Apple&lt;/li&gt;
&lt;li id=""B"" &gt;Banana&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<p>I will be naturally splitting the string back out by its "","" and ending up with an array of element Id's, but I am unsure of two main things in this.</p>
<p>1) What is the best way to get the element which the specified Id found in my split string array?</p>
<p>2) Once I have gotten that element and determined it is the correct element, what is the syntax for or best strategy for placing them in the proper order? </p>
","52","1302","<java><javascript><jquery><sortable><html-lists>","2011-04-27 00:01:05","TRUE","FALSE","5797904","2011-04-27 00:11:33","5","<p>This should answer both (1) and (2).</p>
<p>You can split the string on the <code>,</code> delimiter to get an array, and then just loop through changing the order of the <code>li</code> elements.</p>
<pre><code>var order = 'C,A,B'.split(','),
ul = $('ul');
$.each(order, function(index, sort) {
$('#' + sort).appendTo(ul);
});
</code></pre>
<p><a href=""http://jsfiddle.net/alexdickson/2TqBn/"" rel=""nofollow"">jsFiddle</a>.</p>
","442","3","1","2","2011-04-27 00:05:31","4","TRUE","193242","0"
"http://stackoverflow.com/users/782390","http://stackoverflow.com/questions/17872053","http://stackoverflow.com/questions/17872053/#17872078","2013-07-26 03:37:30","2","170","0","1","How to replace ""\n"" but not "">\n"" in a string","<p>Using Java how is it possible replace all <code>""\n""</code> but not <code>""&gt;\n""</code> with <code>""&lt;br/&gt;""</code>?</p>
<p>I need it because I want add a <code>""&lt;br/&gt;""</code> if I have a new line on plain text, but not if I have HTML.</p>
","45","256","<java><html><regex>","2013-07-26 02:47:34","FALSE","FALSE","17872078","2013-07-26 02:55:48","7","<p>Use a <a href=""http://www.regular-expressions.info/lookaround.html#lookbehind"" rel=""nofollow"">negative lookbehind</a>.</p>
<pre><code>String str = ""\n&gt;\n\n"";
str = str.replaceAll(""(?&lt;!&gt;)\n"", ""&lt;br /&gt;"");
</code></pre>
<p>This will match the <code>\n</code>, and then backtrack a character to ensure the preceding character wasn't a <code>&gt;</code>.</p>
","374","2","1","3","2013-07-26 02:49:47","2","TRUE","193242","0"
"http://stackoverflow.com/users/2897143","http://stackoverflow.com/questions/22976335","http://stackoverflow.com/questions/22976335/#22976342","2014-04-10 00:35:21","0","32","0","1","Illegal Start of Expression, trying to print","<p>I'm getting several errors here, a "";"" and "")"" expected error, an ""illegal start of expression error and a ""not a statement error.""</p>
<p>These two lines are the culprits.</p>
<pre><code>System.out.println(""Rectangle alpha has a width of ""+alpha.width+"", a height of ""+alpha.height+"" a perimeter of ""alpha.getPerimeter()+"" and an area of ""+alpha.getArea()+""."");
System.out.println(""Rectangle beta has a width of ""+beta.width+"", a height of ""+beta.height+"" a perimeter of ""beta.getPerimeter()+"" and an area of ""+beta.getArea()+""."");
</code></pre>
<p>Unfortunately this is one of those times where I don't even know what I don't know to look for what I need to understand/fix this. I actually wanted to use a method to print these two, but I got 'not a statement errors' when I decided to instead do the above and get many more errors...</p>
<p>Thank you so much, I was stuck on this for like 2 hours...not understanding what was wrong...The code itself took 10% of the time :|</p>
","44","989","<java><compiler-errors>","2014-04-10 00:16:37","TRUE","FALSE","22976342","2014-04-10 00:35:21","5","<p>You are missing a <code>+</code> in between your string and <code>alpha.getPerimeter()</code>/<code>beta.getPerimeter()</code>.</p>
<pre><code>System.out.println(""Rectangle alpha has a width of ""+alpha.width+"", a height of ""+alpha.height+"" a perimeter of ""+alpha.getPerimeter()+"" and an area of ""+alpha.getArea()+""."");
System.out.println(""Rectangle beta has a width of ""+beta.width+"", a height of ""+beta.height+"" a perimeter of ""+beta.getPerimeter()+"" and an area of ""+beta.getArea()+""."");
</code></pre>
<p>I always put a space on both sides of operators. This issue confirmed why I do that - you would have definitely noticed the missing <code>+</code> had you done this.</p>
","682","2","1","3","2014-04-10 00:17:23","1","TRUE","193242","0"
"http://stackoverflow.com/users/453435","http://stackoverflow.com/questions/19103036","http://stackoverflow.com/questions/19103036/#19103073","2013-09-30 20:19:13","0","157","0","1","How do I pass a binary literal to JavaScript eval?","<p><strong>Before I start, please don't tell me not to use <code>eval</code>; I know the input is perfectly sanitary, so it's safe, fast, and easy.</strong></p>
<p>I'm using a JavaScript engine to power a calculator I've written in Java. To do this, I simply concatonate input into a string and pass it to JavaScript. For instance, clicking the buttons <code>1</code>, <code>+</code>, and <code>5</code> results in building the String <code>""1+5""</code>. I got this working for hexadecimal, too, by putting <code>0x</code> before the letters, so <code>A</code>, <code>+</code>, and <code>8</code> gives me <code>""0xA+8</code>. My problem comes from programming its binary mode. I tried passing it <code>0b1101+0b10</code> (which is how Java does binary literals), but it just throws an error. <strong>How do I handle binary literals in JavaScript?</strong></p>
","50","862","<java><javascript><binary><eval><literals>","2013-09-30 20:17:08","FALSE","FALSE","19103073","2013-09-30 20:19:13","2","<p>You'd need to pre-process them. <code>parseInt()</code> is the best bet.</p>
<pre><code>var number = parseInt(binaryStr, 2);
</code></pre>
<p>A tip if passing user input directly to <code>eval()</code>. Use a regex to ensure the input only contains numbers and the operators you expect (<code>+</code>, <code>-</code>, etc).</p>
","334","2","1","1","2013-09-30 20:19:13","2","TRUE","193242","0"
"http://stackoverflow.com/users/1333332","http://stackoverflow.com/questions/10154097","http://stackoverflow.com/questions/10154097/#10154110","2012-09-14 21:33:49","-13","267","1","2","Regex to split by ' ', ';' and '\n'","<p>I need one to split code style text by a space, semicolon and new line (\n) to build a command parser. It shouldn't make a difference, but the language is Java.</p>
<p>Thanks</p>
","35","183","<java><regex>","2012-04-14 13:41:45","FALSE","FALSE","10154110","2012-09-14 21:33:49","5","<p><a href=""http://www.regular-expressions.info/"">Well, you <em>should</em> learn regexes</a>.</p>
<p>To select either a space, semicolon or newline, you could use...</p>
<pre><code>[ ;\n]
</code></pre>
<p>Don't forget a newline in a Windows text file is <code>\r\n</code>. This may need to be accounted for, in which case you could use...</p>
<pre><code>(?:\r\n|[ ;\n])
</code></pre>
<p>You shouldn't use regular expressions in a parser besides defining the grammar of tokens (unless your source is extremely simple).</p>
","528","4","2","5","2012-04-14 13:43:20","2","TRUE","193242","0"
"http://stackoverflow.com/users/458770","http://stackoverflow.com/questions/8445669","http://stackoverflow.com/questions/8445669/#8445716","2013-11-15 06:27:25","42","3835","15","11","Why can attributes in Java be public?","<p>As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the <em>only</em> interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?</p>
","37","411","<java><oop><visibility>","2011-12-09 12:44:54","FALSE","FALSE","8445716","2013-11-15 06:27:25","73","<p>I think it's possible because every rule has its exception, every best practice can be overridden in certain cases. </p>
<p>For example, I often expose public static final data members as public (e.g., constants). I don't think it's harmful.</p>
<p>I'll point out that this situation is true in other languages besides Java: C++, C#, etc.</p>
<p>Languages need not always protect us from ourselves. </p>
<p>In Oli's example, what's the harm if I write it this way?</p>
<pre><code>public class Point {
public final int x;
public final int y;
public Point(int p, int q) {
this.x = p;
this.y = q;
}
}
</code></pre>
<p>It's immutable and thread safe. The data members might be public, but you can't hurt them.</p>
<p>Besides, it's a dirty little secret that ""private"" isn't really private in Java. You can always use reflection to get around it.</p>
<p>So relax. It's not so bad.</p>
","922","8","1","4","2011-12-09 12:48:20","4","TRUE","191567","0"
"http://stackoverflow.com/users/710051","http://stackoverflow.com/questions/8898590","http://stackoverflow.com/questions/8898590/#8898617","2013-09-28 10:38:44","12","58783","9","5","Short form for Java If statement","<p>I know there is a way for writing java if statement in short form</p>
<pre><code>if (city.getName() != null) {
name = city.getName();
} else {
name=""N/A"";
}
</code></pre>
<p>does anyone know how to write short form for above 5 lines into one line...</p>
","32","267","<java><if-statement><ternary-operator><short>","2012-01-17 16:58:03","TRUE","FALSE","8898617","2013-05-30 15:11:02","49","<p>Use the ternary operator:</p>
<pre><code>name = ((city.getName() == null) ? ""N/A"" : city.getName());
</code></pre>
<p>I think you have the conditions backwards - if it's null, you want the value to be ""N/A"".</p>
<p>What if city is null? Your code *hits the bed in that case. I'd add another check:</p>
<pre><code>name = ((city == null) || (city.getName() == null) ? ""N/A"" : city.getName());
</code></pre>
<p>I'll follow along with the (very good) example below: </p>
<pre><code>name = ((city == null) || (city.getName() == null) ? ""N/A"" : city.getName());
</code></pre>
","581","4","3","11","2012-01-17 16:59:39","1","TRUE","191567","0"
"http://stackoverflow.com/users/166067","http://stackoverflow.com/questions/5720524","http://stackoverflow.com/questions/5720524/#5720542","2013-06-17 04:38:56","23","13773","3","5","How does one create an InputStream from a String?","<p>I'm not used to working with streams in Java - how do I create an <code>InputStream</code> from a <code>String</code>?</p>
","49","126","<java><string><stream>","2011-04-19 17:53:33","FALSE","FALSE","5720542","2011-04-19 18:01:17","32","<p>Here you go:</p>
<pre><code>InputStream is = new ByteArrayInputStream( myString.getBytes() );
</code></pre>
<p><strong>Update</strong> For multi-byte support use (thanks to <strong>Aaron Waibel</strong>'s comment):</p>
<pre><code>InputStream is = new ByteArrayInputStream(Charset.forName(""UTF-16"").encode(myString()).array());
</code></pre>
<p>Please see <a href=""http://download.oracle.com/javase/1.5.0/docs/api/java/io/ByteArrayInputStream.html"">ByteArrayInputStream</a> manual. </p>
<p>It is safe to use a charset argument in <a href=""http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#getBytes%28java.lang.String%29"">String#getBytes(charset)</a> method above.</p>
","696","4","2","3","2011-04-19 17:54:52","1","TRUE","188203","0"
"http://stackoverflow.com/users/1026764","http://stackoverflow.com/questions/10286677","http://stackoverflow.com/questions/10286677/#10286918","2012-04-23 21:13:15","17","2507","10","5","How to check for repeating sequence in an integer","<p>I have an alpha-numeric string and I want to check for pattern repetition in it just for the integers. And they should be continuous. </p>
<p><strong>Example</strong></p>
<ol>
<li><em>12341234qwe</em> should tell me <em>1234</em> is repeated.</li>
<li><em>1234qwe1234</em> should <strong>NOT</strong> tell me that <em>1234</em> is repeated since its not continuous. </li>
<li><em>12121212</em> should be treated as <em>12</em> being repeated as that is the first set which would be found being repeated. But if there is an algorithm which would find <em>1212</em> as the repeated set before <em>12</em> then I guess it has to perform the steps again on <em>1212</em>.</li>
</ol>
<p>What I thought was I can store the integer part by iterating and comparing it with <code>( &lt;= '0' &amp;&amp; &gt;= '9')</code> in a different <code>StringBuilder</code>. Then I read about performing FFT on the string and it shows the repeated patterns. But I have no idea on how to perform FFT in Java and look for the results, also, I was hoping to try to do this without going to Signal Processing. I read about KMP pattern matching but that only works with a given input. Is there any other way to do this?</p>
","49","1206","<java><regex><algorithm><pattern-matching>","2012-04-23 19:06:56","FALSE","FALSE","10286918","2012-04-23 20:07:23","41","<p>You can take help of regex to solve this I think. Consider code like this:</p>
<pre><code>String arr[] = {""12341234abc"", ""1234foo1234"", ""12121212""};
String regex = ""(\\d+?)\\1"";
Pattern p = Pattern.compile(regex);
for (String elem : arr) {
Matcher matcher = p.matcher(elem);
if (matcher.find())
System.out.println(elem + "" got repeated: "" + matcher.group(1));
else
System.out.println(elem + "" has no repeation"");
}
</code></pre>
<p><strong>OUTPUT:</strong></p>
<pre><code>12341234abc got repeated: 1234
1234foo1234 has no repeation
12121212 got repeated: 12
</code></pre>
<h3>Explanation:</h3>
<p>Regex being used is <code>(\\d+?)\\1</code> where</p>
<pre><code>\\d - means a numerical digit
\\d+ - means 1 or more occurrences of a digit
\\d+? - means reluctant (non-greedy) match of 1 OR more digits
( and ) - to group the above regex into group # 1
\\1 - means back reference to group # 1
(\\d+?)\\1 - repeat the group # 1 immediately after group # 1
</code></pre>
","1025","3","3","5","2012-04-23 19:26:46","20","TRUE","188203","0"
"http://stackoverflow.com/users/527583","http://stackoverflow.com/questions/5348310","http://stackoverflow.com/questions/5348310/#5348382","2014-06-17 03:14:05","16","28208","5","4","How to inject a Map<String, List> in java springs?","<p>How to inject a Map in java spring framework?
If possible please provide some sample code.</p>
<p>Is the following legal?</p>
<pre><code>&lt;property name=""testMap""&gt;
&lt;map&gt;
&lt;entry&gt;
&lt;key&gt;
&lt;value&gt;test&lt;/value&gt;
&lt;/key&gt;
&lt;value&gt;
&lt;list&gt;
&lt;value&gt;String&lt;/value&gt;
&lt;value&gt;String&lt;/value&gt;
&lt;/list&gt;
&lt;/value&gt;
&lt;/entry&gt;
&lt;/map&gt;
&lt;/property&gt;
</code></pre>
","50","602","<java><spring>","2011-03-18 05:02:46","TRUE","FALSE","5348382","2014-06-17 03:14:05","17","<p>Define a Map like this first inside your applicationContext.xml:</p>
<pre><code> &lt;util:list id=""list1""&gt;
&lt;value&gt;foo@bar.com&lt;/value&gt;
&lt;value&gt;foo1@bar.com&lt;/value&gt;
&lt;/util:list&gt;
&lt;util:list id=""list2""&gt;
&lt;value&gt;foo2@bar.com&lt;/value&gt;
&lt;value&gt;foo3@bar.com&lt;/value&gt;
&lt;/util:list&gt;
&lt;util:map id=""emailMap"" value-type=""java.util.List""&gt;
&lt;!-- Map between String key and List --&gt;
&lt;entry key=""entry1"" value-ref=""list1"" /&gt;
&lt;entry key=""entry2"" value-ref=""list2"" /&gt;
...
&lt;/util:map&gt;
</code></pre>
<p>Then use this Map in any bean of yours like this:</p>
<pre><code> &lt;bean id=""myBean"" class=""com.sample.beans""&gt;
&lt;property name=""emailMap"" ref=""emailMap"" /&gt;
&lt;/bean&gt;
</code></pre>
","853","2","2","5","2011-03-18 05:14:45","12","TRUE","188203","0"
"http://stackoverflow.com/users/750965","http://stackoverflow.com/questions/6337075","http://stackoverflow.com/questions/6337075/#6337141","2014-02-17 12:45:05","8","10087","2","9","Return two arrays in a method in Java","<p>Considering i have two arrays for exampple: </p>
<pre><code>String[] array1 = new String[10];
int[] array2= new int[10];
</code></pre>
<p>So that inside a method i have computed two arrays namely <code>array1</code> &amp; <code>array2</code><br>
and now i want to return both of these arrays. How should i go about it. </p>
<p>I read here that i can make another class and define certain object type and encapsulate these arrays in that class constructor, but i am still confused and did not understand completely.</p>
<p>If you could show me a working example which does that or may be any similar idea, it would be good.</p>
","37","636","<java><arrays><object><linked-list>","2011-06-13 22:17:58","TRUE","FALSE","6337141","2014-02-17 12:45:05","16","<p>You can actually return something like this also:</p>
<pre><code>return new Object[]{array1, array2};
</code></pre>
<p>And let's say outside where you call this method your returned object is <code>obj</code>. Then get access to array1 as <code>obj[0]</code> and access array2 as <code>obj[1]</code> (<em>proper casting will be needed</em>).</p>
","351","2","1","4","2011-06-13 22:25:42","8","TRUE","188203","4"
"http://stackoverflow.com/users/1503535","http://stackoverflow.com/questions/16218863","http://stackoverflow.com/questions/16218863/#16218947","2014-08-07 12:20:00","8","18395","0","5","Java, return if List contains String","<p>In Java, I want to check whether a String exists in a <code>List&lt;String&gt; myList</code>.</p>
<p>Something like this:</p>
<pre><code>if(myList.contains(""A"")){
//true
}else{
// false
}
</code></pre>
<p>The problem is myList can contain un-trimmed data:</p>
<pre><code>{' A', 'B ', ' C '}
</code></pre>
<p>I want it to return true if my item <code>'B'</code> is in the list. How should I do this? I would like to avoid a looping structure.</p>
","36","468","<java><arrays><string><list>","2013-04-25 15:29:48","TRUE","FALSE","16218947","2013-04-25 15:39:24","8","<p>You need to iterate your list and call <a href=""http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim%28%29""><code>String#trim</code></a> for searching:</p>
<pre><code>String search = ""A"";
for(String str: myList) {
if(str.trim().contains(search))
return true;
}
return false;
</code></pre>
<p>OR if you want to fo ignore case search, use:</p>
<pre><code>search = search.toLowerCase(); // outside loop
// inside the loop
if(str.trim().toLowerCase().contains(search))
</code></pre>
","515","2","2","3","2013-04-25 15:33:28","4","TRUE","188203","0"
"http://stackoverflow.com/users/2031872","http://stackoverflow.com/questions/18766780","http://stackoverflow.com/questions/18766780/#18766889","2014-01-27 20:02:15","5","3552","3","6","StringBuilder - Reset or create a new","<p>I have a condition that a StringBuilder keeps storing lines matching a pattern from a large flat file (100's of MB). However after reaching a condition I write the content of the StringBuilder varialble to a textfile. </p>
<p>Now I wonder if I should use the same variable by resetting the object -> </p>
<pre><code>stringBuilder.delete(0,stringBuilder.length())
</code></pre>
<p>OR</p>
<pre><code>stringBuilder=new StringBuilder();
</code></pre>
<p>Please suggest which would do you think is better as far as both performance and OOM issues are concerned.</p>
","37","570","<java><stringbuilder>","2013-09-12 14:18:14","TRUE","FALSE","18766889","2013-09-12 15:09:49","8","<p>I think <code>StringBuilder#delete(start, end)</code> is still expensive call, you should do:</p>
<pre><code>stringBuilder.setLength(0);
</code></pre>
<p>to reset it.</p>
<hr>
<p><strong>UPDATE:</strong> After looking at <a href=""http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.trimToSize%28%29"" rel=""nofollow""><strong>source code of <code>StringBuilder</code></strong></a> It seems <code>setLength(int)</code> leaves old buffer intact and it is better to call: <strong><code>StringBuilder#trimToSize()</code></strong> after above call which <strong><code>attempts to reduce storage used for the character sequence</code></strong>.</p>
<p>So something like this would be more efficient:</p>
<pre><code>stringBuilder.setLength(0); // set length of buffer to 0
stringBuilder.trimToSize(); // trim the underlying buffer
</code></pre>
","928","4","2","12","2013-09-12 14:22:44","4","TRUE","188203","0"
"http://stackoverflow.com/users/1261204","http://stackoverflow.com/questions/9872002","http://stackoverflow.com/questions/9872002/#9872051","2012-03-26 16:23:19","5","3940","0","4","keep only alphabet characters","<p>What method should I follow in java to produce</p>
<pre><code>""WordWord""
</code></pre>
<p>from</p>
<pre><code>""Word#$#$% Word 1234""
</code></pre>
","29","152","<java><string>","2012-03-26 12:21:11","TRUE","FALSE","9872051","2012-03-26 14:52:15","17","<p>You can use <a href=""http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29""><code>String.replaceAll(regex, replacement)</code></a> with the regex <code>[^A-Za-z]+</code> like this:</p>
<pre><code>String newstr = ""Word#$#$% Word 1234"".replaceAll(""[^A-Za-z]+"", """");
// newstr will become WordWord
</code></pre>
<p><strong>Edit:</strong> Although OP hasn't mentioned anything about <code>unicode characters</code> but since @Joey has made a comment and if at all there a requirement to keep unicode characters then <code>\\P{L}+</code> regex should be used like this:</p>
<pre><code>String newstr = ""Word#$#$% Word λ1234ä, ñ, ж"".replaceAll(""\\P{L}+"", """");
// newstr will become WordWordλäñж
</code></pre>
","770","2","2","10","2012-03-26 12:24:32","3","TRUE","188203","0"
"http://stackoverflow.com/users/1130155","http://stackoverflow.com/questions/8837048","http://stackoverflow.com/questions/8837048/#8837104","2012-01-25 07:44:58","5","2100","1","1","how to split string contains numbers in java?","<p>I have String like this: ""LODIXAL COMP 15""</p>
<p>How can i split it to ""LODIXAL COMP"" and ""15"" ?</p>
<pre><code>String a = ""LODIXAL COMP 15"";
String[] result = {""LODIXAL COMP"" , ""15""}
</code></pre>
","45","205","<java><regex><string><split>","2012-01-12 14:53:12","TRUE","FALSE","8837104","2012-01-25 07:44:58","13","<p>Use this <a href=""http://www.regular-expressions.info/lookaround.html"">positive lookahead</a> based regex:</p>
<pre><code>a.split("" (?=\\d+)"");
</code></pre>
<p><strong>TESTING:</strong></p>
<pre><code>System.out.println(Arrays.toString(a.split("" (?=\\d+)"")));
</code></pre>
<p><strong>OUTPUT:</strong></p>
<pre><code>[LODIXAL COMP, 15]
</code></pre>
","359","3","3","7","2012-01-12 14:56:51","3","TRUE","188203","0"
"http://stackoverflow.com/users/1637249","http://stackoverflow.com/questions/23561026","http://stackoverflow.com/questions/23561026/#23561058","2014-05-09 10:47:09","3","92","0","2","Regex to remove spaces between numbers only","<p>I need to remove the spaces between numbers only, so that a string like this:</p>
<pre><code>""Hello 111 222 333 World!""
</code></pre>
<p>becomes</p>
<pre><code>""Hello 111222333 World!""
</code></pre>
<p>I've tried this:</p>
<pre><code>message = message.replaceAll(""[\\d+](\\s+)[\\d+]"", """");
</code></pre>
<p>Doesn't seem to get it done.</p>
","43","349","<java><android><regex>","2014-05-09 09:24:57","TRUE","FALSE","23561058","2014-05-09 10:47:09","10","<p>You can use this lookaround based regex:</p>
<pre><code> String repl = ""Hello 111 222 333 World!"".replaceAll(""(?&lt;=\\d) +(?=\\d)"", """");
//=&gt; Hello 111222333 World!
</code></pre>
<p>This regex <code>""(?&lt;=\\d) +(?=\\d)""</code> makes sure to match space that are preceded and followed by a digit.</p>
","312","2","1","5","2014-05-09 09:26:21","2","TRUE","188203","0"
"http://stackoverflow.com/users/142","http://stackoverflow.com/questions/839407","http://stackoverflow.com/questions/839407/#839414","2009-05-08 19:09:11","4","2977","0","11","Replicating C struct padding in Java","<p>According to <a href=""http://c-faq.com/struct/padding.html"" rel=""nofollow"">here</a>, the C compiler will pad out values when writing a structure to a binary file. As the example in the link says, when writing a struct like this:</p>
<pre><code>struct {
char c;
int i;
} a;
</code></pre>
<p>to a binary file, the compiler will usually leave an unnamed, unused hole between the char and int fields, to ensure that the int field is properly aligned. </p>
<p>How could I to create an exact replica of the binary output file (generated in C), using a different language (in my case, Java)?</p>
<p>Is there an automatic way to apply C padding in Java output? Or do I have to go through compiler documentation to see how it works (the compiler is g++ by the way).</p>
","36","770","<java><c><compiler-construction><padding>","2009-05-08 11:27:34","TRUE","FALSE","839414","2009-05-08 19:09:11","8","<p>This is true not only when writing to files, but also in memory. It is the fact that the struct is padded in memory, that leads to the padding showing up in the file, if the struct is written out byte-by-byte.</p>
<p>It is in general very hard to replicate with certainty the exact padding scheme, although I guess some heuristics would get you quite far. It helps if you have the struct declaration, for analysis.</p>
<p>Typically, fields larger than one char will be aligned so that their starting offset inside the structure is a multiple of their size. This means <code>short</code>s will generally be on even offsets (divisible by 2, assuming <code>sizeof (short) == 2</code>), while <code>double</code>s will be on offsets divisible by 8, and so on.</p>
<p><strong>UPDATE</strong>: It is for reasons like this (and also reasons having to do with endianness) that it is generally a bad idea to dump whole structs out to files. It's better to do it field-by-field, like so:</p>
<pre><code>put_char(out, a.c);
put_int(out, a.i);
</code></pre>
<p>Assuming the <code>put</code>-functions only write the bytes needed for the value, this will emit a padding-less version of the struct to the file, solving the problem. It is also possible to ensure a proper, known, byte-ordering by writing these functions accordingly.</p>
","1331","5","1","3","2009-05-08 11:31:05","4","TRUE","187305","0"
"http://stackoverflow.com/users/2922388","http://stackoverflow.com/questions/1475807","http://stackoverflow.com/questions/1475807/#1475832","2012-08-28 20:36:37","4","13014","0","4","Insert string in beginning of another string","<p>How to insert a string enclosed with double quotes in the beginning of the StringBuilder and String?</p>
<p>Eg:</p>
<pre><code>StringBuilder _sb = new StringBuilder(""Sam"");
</code></pre>
<p>I need to insert the string ""Hello"" to the beginning of ""Sam"" and O/p is ""Hello Sam"".</p>
<pre><code>String _s = ""Jam"";
</code></pre>
<p>I need to insert the string ""Hello"" to the beginning of ""Jam"" and O/p is ""Hello Jam"".</p>
<p>How to achieve this?</p>
","44","454","<java><string>","2009-09-25 06:53:35","TRUE","FALSE","1475832","2009-09-25 07:10:34","11","<p>The first case is done using the <code><a href=""http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html#insert%28int,%20java.lang.String%29"">insert()</a></code> method:</p>
<pre><code>_sb.insert(0, ""Hello "");
</code></pre>
<p>The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:</p>
<pre><code>String s2 = ""Hello "" + _s;
</code></pre>
","418","2","2","4","2009-09-25 07:02:48","9","TRUE","187305","0"
"http://stackoverflow.com/users/537936","http://stackoverflow.com/questions/5717447","http://stackoverflow.com/questions/5717447/#5717481","2014-06-15 08:24:09","3","4230","1","3","Convert 16 bit pcm to 8 bit","<p>I have pcm audio stored in a byte array. It is 16 bits per sample. I want to make it 8 bit per sample audio. </p>
<p>Can anyone suggest a good algorithm to do that?</p>
<p>I haven't mentioned the bitrate because I think it isn't important for the algorithm - right?</p>
","27","276","<java><algorithm><audio><bit><pcm>","2011-04-19 13:52:49","FALSE","FALSE","5717481","2011-04-20 10:13:48","8","<p>I can't see right now why it's not enough to just take the upper byte, i.e. discard the lower 8 bits of each sample.</p>
<p>That of course assumes that the samples are linear; if they're not then maybe you need to do something to linearize them before dropping bits.</p>
<pre><code>short sixteenBit = 0xfeed;
byte eightBit = sixteenBit &gt;&gt; 8;
// eightBit is now 0xfe.
</code></pre>
<p>As suggested by AShelly in a comment, it might be a good idea to round, i.e. add 1 if the byte we're discarding is higher than half its maximum:</p>
<pre><code>eightBit += eightBit &lt; 0xff &amp;&amp; ((sixteenBit &amp; 0xff) &gt; 0x80);
</code></pre>
<p>The test against 0xff implements clamping, so we don't risk adding 1 to 0xff and wrapping that to 0x00 which would be bad.</p>
","781","4","2","4","2011-04-19 13:55:12","3","TRUE","187305","0"
"http://stackoverflow.com/users/176554","http://stackoverflow.com/questions/1472135","http://stackoverflow.com/questions/1472135/#1472160","2009-09-24 21:08:02","3","1081","2","7","Removing lowest order bit","<p>Given a binary number, what is the fastest way of removing the lowest order bit?</p>
<p>01001001010 -> 01001001000</p>
<p>It would be used in code to iterate over the bits of a variable. Pseudo-code follows.</p>
<pre><code>while(bits != 0){
index = getIndexOfLowestOrderBit(bits);
doSomething(index);
removeLowestOrderBit(bits);
}
</code></pre>
<p>The possible languages I'm considering using are C and Java.</p>
","25","427","<java><c><binary><bit-fiddling>","2009-09-24 14:38:13","TRUE","FALSE","1472160","2009-09-24 14:52:40","10","<p>Uh ... In your example, you already know the bit's index. Then it's easy:</p>
<pre><code>bits &amp;= ~(1 &lt;&lt; index);
</code></pre>
<p>This will mask off the bit whose index is <code>index</code>, regardless of its position in the value (highest, lowest, or in-between). Come to think of it, you can of course use the fact that you know the bit is already set, and use an XOR to knock it clear again:</p>
<pre><code>bits ^= (1 &lt;&lt; index);
</code></pre>
<p>That saves the inversion, which is probably one machine instruction.</p>
<p>If you instead want to mask off the <em>lowest</em> set bit, without knowing its index, the trick is:</p>
<pre><code>bits &amp;= (bits - 1);
</code></pre>
<p>See <a href=""http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan"">here</a> for instance.</p>
","824","5","3","5","2009-09-24 14:41:11","3","TRUE","187305","0"
"http://stackoverflow.com/users/54988","http://stackoverflow.com/questions/909956","http://stackoverflow.com/questions/909956/#909961","2012-10-18 08:21:48","3","682","0","6","How to combine two FORs into one","<p>This might be stupid, but I'm want to know if it's possible, lets start with 5x5 a matrix</p>
<pre><code>int[][] x = new int[5][5];
Random rg = new Random();
</code></pre>
<p>now let's fill it with Pseudo Random information</p>
<pre><code>for(int i=0;i&lt;5;i++){
for(int j =0; j&lt;5;j++){
x[i][j] = rg.nextInt();
}
}
</code></pre>
<p>but how can I do this right with one Single for?</p>
<pre><code>for(int i=0, j=0; i&lt;5; (j==5?i++, j=0:j++){
x[i][j] = rg.nextInt();
}
</code></pre>
<p>this is not working :(</p>
","32","553","<java>","2009-05-26 10:16:54","TRUE","FALSE","909961","2009-05-26 10:29:20","21","<p>You need to compute the row and column from a single index, then:</p>
<pre><code>for(int i = 0; i &lt; 5 * 5; i++)
{
int row = i / 5;
int column = i % 5;
x[row][column] = rg.nextInt();
}
</code></pre>
<p>The use of / and % is classic, here: as you iterate over the indices of the matrix, the division is used to figure out which row you're on. The remainder (%) is then the column.</p>
<p>This gorgeous ASCII art shows how the 1-dimensional indices are located in the 2D matrix:</p>
<pre><code> 0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
</code></pre>
<p>It should be clear that for any value in the first row, that value divided by 5 is the row index itself, i.e. they're all 0.</p>
","732","4","2","6","2009-05-26 10:18:44","2","TRUE","187305","0"
"http://stackoverflow.com/users/131383","http://stackoverflow.com/questions/4155482","http://stackoverflow.com/questions/4155482/#4155499","2010-11-11 15:51:01","2","1616","0","5","Bitwise operators in Java acting on two bytes","<p>This should be simple but I'm having trouble changing some C code that uses bitwise operators and shifts into Java.</p>
<p>In C I have:</p>
<pre><code>unsigned short Color(byte r, byte g, byte b)
{
return( ((unsigned short)g &amp; 0x1F )&lt;&lt;10 | ((unsigned short)b &amp; 0x1F)&lt;&lt;5 | (unsigned short)r &amp; 0x1F);
}
</code></pre>
<p>This function, Color, returns 16bits where 15 of them represent three 5bit values for red, green, and blue color channels. I'm trying to do something similar in Java except I'm having trouble with data types. </p>
<p>In java I have:</p>
<pre><code>int r=someval, g=anotherval, b=yetanotherval;
</code></pre>
<p>And I want to convert these integers to a 2byte data type and use the same bitwise/shift operations as above.</p>
<p>What is the best way to approach this? I was thinking of a 2byte array but that seems unnecessary.</p>
<p><strong>edit</strong></p>
<p>So I gave it a try in Java with shorts but there still seems to be an issue. I started simple with:</p>
<pre><code>short r=someval, g=anotherval, b=yetanotherval;
short colorData = g &amp; 0x001F;
</code></pre>
<p>But the compiler complains: ""cannot convert from int to short""</p>
","45","1205","<java><c><types><bitwise>","2010-11-11 14:37:53","TRUE","FALSE","4155499","2010-11-11 14:49:55","2","<p>You have the <code>short</code> type in Java as well, but it's always signed, there is no unsigned in Java.</p>
<p>Therefore, it might be better to use an <code>int</code>, so you don't need to use the sign bit to hold actual color data, which can be a bit (no pun intended!) confusing.</p>
<p>This should work as a starting point, at least:</p>
<pre><code>int Color(int r, int g, int b)
{
return ((g &amp; 0x1F) &lt;&lt; 10) | ((b &amp; 0x1F) &lt;&lt; 5) | (r &amp; 0x1F);
}
</code></pre>
<p>I made the arguments <code>int</code> as well, for simplicity's sake.</p>
<p><strong>Update:</strong> It sounds (and seems) as if you can actually use <code>short</code>, since you only need 15 bits for the color format. Then let's do that:</p>
<pre><code>short Color(short r, short g, short b)
{
return ((g &amp; 0x1F) &lt;&lt; 10) | ((b &amp; 0x1F) &lt;&lt; 5) | (r &amp; 0x1F);
}
</code></pre>
<p>I haven't tried compiling the above, but it's likely that you'll get conversion errors and will need to add explicit <code>short</code> casts throughout to make it compile.</p>
","1084","6","2","1","2010-11-11 14:40:05","3","TRUE","187305","0"
"http://stackoverflow.com/users/1216152","http://stackoverflow.com/questions/14520830","http://stackoverflow.com/questions/14520830/#14530359","2013-06-28 05:32:19","30","1685","3","10","x > -1 vs x >= 0, is there a performance difference","<p>I have heard a teacher drop this once, and it has been bugging me ever since. Let's say we want to check if the integer <code>x</code> is bigger than or equal to 0. There are two ways to check this:</p>
<pre><code>if (x &gt; -1){
//do stuff
}
</code></pre>
<p>and</p>
<pre><code>if (x &gt;= 0){
//do stuff
}
</code></pre>
<p>According to this teacher <code>&gt;</code> would be slightly faster then <code>&gt;=</code>. In this case it was Java, but according to him this also applied for C, c++ and other languages. Is there any truth to this statement?</p>
","51","574","<java><c++><operators><micro-optimization><premature-optimization>","2013-01-25 11:25:11","TRUE","FALSE","14530359","2013-06-28 05:32:19","25","<p>There's no difference in any real-world sense.</p>
<p>Let's take a look at some code generated by various compilers for various targets.</p>
<ul>
<li>I'm assuming a signed int operation (which seem the intent of the OP)</li>
<li>I've limited by survey to C and to compilers that I have readily at hand (admittedly a pretty small sample - GCC, MSVC and IAR)</li>
<li>basic optimizations enabled (<code>-O2</code> for GCC, <code>/Ox</code> for MSVC, <code>-Oh</code> for IAR)</li>
<li><p>using the following module:</p>
<pre><code>void my_puts(char const* s);
void cmp_gt(int x)
{
if (x &gt; -1) {
my_puts(""non-negative"");
}
else {
my_puts(""negative"");
}
}
void cmp_gte(int x)
{
if (x &gt;= 0) {
my_puts(""non-negative"");
}
else {
my_puts(""negative"");
}
}
</code></pre></li>
</ul>
<p>And here's what each of them produced for the comparison operations:</p>
<p>MSVC 11 targeting ARM:</p>
<pre><code>// if (x &gt; -1) {...
00000 |cmp_gt| PROC
00000 f1b0 3fff cmp r0,#0xFFFFFFFF
00004 dd05 ble |$LN2@cmp_gt|
// if (x &gt;= 0) {...
00024 |cmp_gte| PROC
00024 2800 cmp r0,#0
00026 db05 blt |$LN2@cmp_gte|
</code></pre>
<p>MSVC 11 targeting x64:</p>
<pre><code>// if (x &gt; -1) {...
cmp_gt PROC
00000 83 f9 ff cmp ecx, -1
00003 48 8d 0d 00 00 // speculative load of argument to my_puts()
00 00 lea rcx, OFFSET FLAT:$SG1359
0000a 7f 07 jg SHORT $LN5@cmp_gt
// if (x &gt;= 0) {...
cmp_gte PROC
00000 85 c9 test ecx, ecx
00002 48 8d 0d 00 00 // speculative load of argument to my_puts()
00 00 lea rcx, OFFSET FLAT:$SG1367
00009 79 07 jns SHORT $LN5@cmp_gte
</code></pre>
<p>MSVC 11 targeting x86:</p>
<pre><code>// if (x &gt; -1) {...
_cmp_gt PROC
00000 83 7c 24 04 ff cmp DWORD PTR _x$[esp-4], -1
00005 7e 0d jle SHORT $LN2@cmp_gt
// if (x &gt;= 0) {...
_cmp_gte PROC
00000 83 7c 24 04 00 cmp DWORD PTR _x$[esp-4], 0
00005 7c 0d jl SHORT $LN2@cmp_gte
</code></pre>
<p>GCC 4.6.1 targeting x64</p>
<pre><code>// if (x &gt; -1) {...
cmp_gt:
.seh_endprologue
test ecx, ecx
js .L2
// if (x &gt;= 0) {...
cmp_gte:
.seh_endprologue
test ecx, ecx
js .L5
</code></pre>
<p>GCC 4.6.1 targeting x86:</p>
<pre><code>// if (x &gt; -1) {...
_cmp_gt:
mov eax, DWORD PTR [esp+4]
test eax, eax
js L2
// if (x &gt;= 0) {...
_cmp_gte:
mov edx, DWORD PTR [esp+4]
test edx, edx
js L5
</code></pre>
<p>GCC 4.4.1 targeting ARM:</p>
<pre><code>// if (x &gt; -1) {...
cmp_gt:
.fnstart
.LFB0:
cmp r0, #0
blt .L8
// if (x &gt;= 0) {...
cmp_gte:
.fnstart
.LFB1:
cmp r0, #0
blt .L2
</code></pre>
<p>IAR 5.20 targeting an ARM Cortex-M3:</p>
<pre><code>// if (x &gt; -1) {...
cmp_gt:
80B5 PUSH {R7,LR}
.... LDR.N R1,??DataTable1 ;; `?&lt;Constant ""non-negative""&gt;`
0028 CMP R0,#+0
01D4 BMI.N ??cmp_gt_0
// if (x &gt;= 0) {...
cmp_gte:
80B5 PUSH {R7,LR}
.... LDR.N R1,??DataTable1 ;; `?&lt;Constant ""non-negative""&gt;`
0028 CMP R0,#+0
01D4 BMI.N ??cmp_gte_0
</code></pre>
<p>If you're still with me, here are the differences of any note between evaluating <code>(x &gt; -1)</code> and <code>(x &gt;= 0)</code> that show up:</p>
<ul>
<li>MSVC targeting ARM uses <code>cmp r0,#0xFFFFFFFF</code> for <code>(x &gt; -1)</code> vs <code>cmp r0,#0</code> for <code>(x &gt;= 0)</code>. The first instruction's opcode is two bytes longer. I suppose that may introduce some additional time, so we'll call this an advantage for <code>(x &gt;= 0)</code></li>
<li>MSVC targeting x86 uses <code>cmp ecx, -1</code> for <code>(x &gt; -1)</code> vs <code>test ecx, ecx</code> for <code>(x &gt;= 0)</code>. The first instruction's opcode is one byte longer. I suppose that may introduce some additional time, so we'll call this an advantage for <code>(x &gt;= 0)</code></li>
</ul>
<p>Note that GCC and IAR generated identical machine code for the two kinds of comparison (with the possible exception of which register was used). So according to this survey, it appears that <code>(x &gt;= 0)</code> has an ever-so-slight chance of being 'faster'. But whatever advantage the minimally shorter opcode byte encoding might have (and I stress <em>might have</em>) will be certainly completely overshadowed by other factors. </p>
<p>I'd be surprised if you found anything different for the jitted output of Java or C#. I doubt you'd find any difference of note even for a very small target like an 8 bit AVR.</p>
<p>In short, don't worry about this micro-optimization. I think my write up here has already spent more time than will be spent by any difference in the performance of these expressions accumulated across all the CPUs executing them in my lifetime. If you have the capability to measure the difference in performance, please apply your efforts to something more important like studying the behavior of sub-atomic particles or something.</p>
","5154","15","8","7","2013-01-25 21:03:28","578","TRUE","185964","0"
"http://stackoverflow.com/users/560204","http://stackoverflow.com/questions/5670287","http://stackoverflow.com/questions/5670287/#5670480","2011-04-15 07:28:20","7","3802","2","5","Cryptanalysis: XOR of two plaintext files","<p>I have a file which contains the result of two XORed plaintext files. How do I attack this file in order to decrypt either of the plaintext files? I have searched quite a bit, but could not find any answers. Thanks!</p>
<p><strong>EDIT:</strong></p>
<p>Well, I also have the two ciphertexts which i XORed to get the XOR of the two plaintexts. The reason I ask this question, is because, according to Bruce Schneier, pg. 198, Applied Cryptography, 1996 ""...she can XOR them together and get two plaintext messages XORed with each other. This is easy to break, and then she can XOR one of the plaintexts with the ciphertext to get the keystream."" (This is in relation to a simple stream cipher) But beyond that he provided no explanation. Which is why I asked here. Forgive my ignorance.</p>
<p>Also, the algorithm used is a simple one, and a symmetric key is used whose length is 3.</p>
<p><strong>FURTHER EDIT:</strong></p>
<p>I forgot to add: Im assuming that a simple stream cipher was used for encryption.</p>
","41","1021","<java><cryptography><encryption>","2011-04-14 22:07:37","FALSE","FALSE","5670480","2011-04-15 07:28:20","7","<p>I'm no cryptanalyst, but if you know <em>something</em> about the characteristics of the files you might have a chance. </p>
<p>For example, lets assume that you know that both original plaintexts:</p>
<ul>
<li>contain plain ASCII English text</li>
<li>are articles about sports (or whatever)</li>
</ul>
<p>Given those 2 pieces of information, one approach you might take is to scan through the ciphertext 'decrypting' using words that you might expect to be in them, such as ""football"", ""player"", ""score"", etc. Perform the decryption using ""football"" at position 0 of the ciphertext, then at position 1, then 2 and so on.</p>
<p>If the result of decrypting a sequence of bytes appears to be a word or word fragment, then you have a good chance that you've found plaintext from both files. That may give you a clue as to some surrounding plaintext, and you can see if that results in a sensible decryption. And so on.</p>
<p>Repeat this process with other words/phrases/fragments that you might expect to be in the plaintexts.</p>
<hr>
<p>In response to your question's edit: what Schneier is talking about is that if someone has 2 ciphertexts that have been XOR encrypted using the same key, XORing those ciphertexts will 'cancel out' the keystream, since:</p>
<pre><code>(A ^ k) - ciphertext of A
(B ^ k) - ciphertext of B
(A ^ k) ^ (B ^ k) - the two ciphertexts XOR'ed together which simplifies to:
A ^ B ^ k ^ k - which continues to simplify to
A ^ B ^ 0
A ^ B
</code></pre>
<p>So now, the attacker has a new ciphertext that's composed only of the two plaintexts. If the attacker knows one of the plaintexts (say the attacker has legitimate access to A, but not B), that can be used to recover the other plaintext:</p>
<pre><code>A ^ (A ^ B)
(A ^ A) ^ B
0 ^ B
B
</code></pre>
<p>Now the attacker has the plaintext for B.</p>
<p>It's actually worse than this - if the attacker has A and the ciphertext for A then he can recover the keystream already. </p>
<p>But, the guessing approach I gave above is a variant of the above with the attacker using (hopefully good) guesses instead of a known plaintext. Obviously it's not as easy, but it's the same concept, and it can be done without starting with known plaintext. Now the attacker has a ciphertext that 'tells' him when he's correctly guessed some plaintext (because it results in other plaintext from the decryption). So even if the key used in the original XOR operation is random gibberish, an attacker can use the file that has that random gibberish 'removed' to gain information when he's making educated guesses.</p>
","2603","10","2","4","2011-04-14 22:31:15","24","TRUE","185964","0"
"http://stackoverflow.com/users/386123","http://stackoverflow.com/questions/3217289","http://stackoverflow.com/questions/3217289/#3217304","2014-09-10 01:10:51","3","3516","0","3","Converting a byte array to string without using new operator in Java","<p>Is there a way to convert a byte array to string other than using <code>new String(bytearray)</code>? The exact problem is I transmit a json-formatted string over the network through UDP connection. At the other end, I receive it in a fixed-size byte array(as I am not aware of the array size) and create a new string out of the byte array. If I do this, the whole memory that I allocated is being held unnecessary. </p>
<p>To avoid this I get the byte array convert it to string, truncate the string till the last valid character and then convert it to a byte array and create a new string out of it. If I do this, it just uses up the required memory but the garbage collection frequency becomes so high as it involves more number of allocations. What is the best way to do this? </p>
","68","791","<java><string><performance><bytearray>","2010-07-10 00:22:01","FALSE","FALSE","3217304","2010-07-10 05:37:08","1","<p>Would something like:</p>
<pre><code>String s = new String( bytearray, 0, lenOfValidData, ""US-ASCII"");
</code></pre>
<p>do what you want (change the charset to whatever encoding is appropriate)?</p>
<hr>
<p>Update:</p>
<p>Based on your comments, you might want to try:</p>
<pre><code>socket.receive(packet);
String strPacket = new String( packet.getData(), 0, packet.getLength(), ""US-ASCII"");
receiver.onReceive( strPacket);
</code></pre>
<p>I'm not familiar enough with Java's datagram support to know if <code>packet.getLength()</code> returns the truncated length or the original length of the datagram (before truncation to fit in the receive buffer). It might be safer to create the string like so:</p>
<pre><code>String strPacket = new String( packet.getData(),
0,
Math.min( packet.getLength(), packet.getData().length),
""US-ASCII"");
</code></pre>
<p>Then again, it might be unnecessary.</p>
","1005","6","3","9","2010-07-10 00:28:12","6","TRUE","185964","0"
"http://stackoverflow.com/users/109849","http://stackoverflow.com/questions/2349727","http://stackoverflow.com/questions/2349727/#2349974","2010-02-28 03:30:52","0","577","0","1","TInyOS 1.x Generating an error when compiling BLINK","<p>root@everton-laptop:/opt/tinyos-1.x/apps/Blink# make pc</p>
<pre><code>compiling Blink to a pc binary
ncc -o build/pc/main.exe -g -O0 -board=micasb -pthread -target=pc -Wall -Wshadow -DDEF_TOS_AM_GROUP=0x7d -Wnesc-all -fnesc-nido-tosnodes=1000 -fnesc-cfile=build/pc/app.c Blink.nc -lm
In file included from /opt/tinyos-1.x/tos/platform/pc/packet_sim.h:55,
from /opt/tinyos-1.x/tos/platform/pc/nido.h:81,
from /opt/tinyos-1.x/tos/platform/pc/hardware.h:43,
from /opt/tinyos-1.x/tos/system/tos.h:144:
/opt/tinyos-1.x/tos/types/AM.h:155: parse error before `struct'
/opt/tinyos-1.x/tos/types/AM.h:156: parse error before `struct'
/opt/tinyos-1.x/tos/types/AM.h:158: parse error before `struct'
/opt/tinyos-1.x/tos/types/AM.h: In function `TOS_MsgLength':
/opt/tinyos-1.x/tos/types/AM.h:186: parse error before `TOS_Msg'
In file included from /opt/tinyos-1.x/tos/platform/pc/hardware.h:116,
from /opt/tinyos-1.x/tos/system/tos.h:144:
/opt/tinyos-1.x/tos/platform/pc/eeprom.c: At top level:
/opt/tinyos-1.x/tos/platform/pc/eeprom.c:115: warning: declaration of `length' shadows global declaration
/opt/tinyos-1.x/tos/types/AM.h:158: warning: location of shadowed declaration
/opt/tinyos-1.x/tos/platform/pc/eeprom.c:145: warning: declaration of `length' shadows global declaration
/opt/tinyos-1.x/tos/types/AM.h:158: warning: location of shadowed declaration
make: *** [build/pc/main.exe] Error 1
</code></pre>
<p>Tried compiling BLink and i keep getting the above error and not sure what to do next. any help would be nice .</p>
","51","1605","<java><c++><c><tinyos>","2010-02-28 01:36:54","TRUE","FALSE","2349974","2010-02-28 03:30:52","1","<p>Looking at the CVS repository for <code>tos/types/AM.h</code>, it looks like it's choking on the following code:</p>
<pre><code>154: enum {
155: MSG_DATA_SIZE = offsetof(struct TOS_Msg, crc) + sizeof(uint16_t), // 36 by default
156: TINYSEC_MSG_DATA_SIZE = offsetof(struct TinySec_Msg, mac) + TINYSEC_MAC_LENGTH, // 41 by default
157: DATA_LENGTH = TOSH_DATA_LENGTH,
158: LENGTH_BYTE_NUMBER = offsetof(struct TOS_Msg, length) + 1,
159: TINYSEC_NODE_ID_SIZE = sizeof(uint16_t)
160: };
</code></pre>
<p>The common item from lines 155, 156, and 158 are the <code>offsetof()</code> macro, which should be defined in <code>stddef.h</code> and which looks like should have been brought in by the <code>tos.h</code> before it causes <code>AM.h</code> to be included, so <code>offsetof()</code> should already be defined.</p>
<p>You might want to verify whether or not the compiler you're using has <code>offsetof()</code> properly defined and/or why it's not available for use in <code>AM.h</code>. If necessary, you can probably define it yourself using a more or less usual implementation:</p>
<pre><code>#define offsetof(st, m) ((size_t) ( (char *)&amp;((st *)(0))-&gt;m - (char *)0 )) // stolen from Wikipedia
</code></pre>
","1245","3","2","1","2010-02-28 03:30:52","114","TRUE","185964","0"
"http://stackoverflow.com/users/80796","http://stackoverflow.com/questions/4228975","http://stackoverflow.com/questions/4228975/#4229001","2014-05-23 16:59:19","77","54697","25","9","How to randomize ArrayList?","<p>I have two arraylist <code>filelist</code> and <code>imgList</code> which related to each other, e.g. ""H1.txt"" related to ""e1.jpg"". How to automatically randomized the list of <code>imgList</code> according to the randomization of <code>fileList</code>? Like in excel, if we sort certain column, the other column will automatically follow?</p>
<pre><code>String [] file = {""H1.txt"",""H2.txt"",""H3.txt"",""M4.txt"",""M5.txt"",""M6.txt""};
ArrayList&lt;String&gt; fileList = new ArrayList&lt;String&gt;(Arrays.asList(file));
String [] img = {""e1.jpg"",""e2.jpg"",""e3.jpg"",""e4.jpg"",""e5.jpg"",""e6.jpg""};
ArrayList&lt;String&gt; imgList = new ArrayList&lt;String&gt;(Arrays.asList(img));
//randomized files
Collections.shuffle(fileList);
</code></pre>
<p>output after randomization e.g.:</p>
<pre><code>fileList = {""M4.txt"",""M6.txt"",""H3.txt"",""M5.txt"",""H2.txt"",""H1.txt""};
</code></pre>
<p>intended output:</p>
<pre><code> imgList = {""e4.jpg"",""e6.jpg"",""e3.jpg"",""e5.jpg"",""e2.jpg"",""e1.jpg""};
</code></pre>
","27","994","<java><list><collections><arraylist>","2010-11-19 20:10:52","TRUE","FALSE","4229001","2014-05-23 16:59:19","191","<p>Use <a href=""http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List,%20java.util.Random%29""><code>Collections.shuffle()</code></a> twice, with two <code>Random</code> objects initialized with the same seed:</p>
<pre><code>long seed = System.nanoTime();
Collections.shuffle(fileList, new Random(seed));
Collections.shuffle(imgList, new Random(seed));
</code></pre>
","410","1","1","7","2010-11-19 20:14:15","4","TRUE","185840","0"
"http://stackoverflow.com/users/84916","http://stackoverflow.com/questions/1066589","http://stackoverflow.com/questions/1066589/#1066603","2014-03-06 09:49:58","1008","1090562","413","7","Java: iterate through HashMap","<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href=""http://stackoverflow.com/questions/46898/how-do-i-iterate-over-each-entry-in-a-collection-map"">How do I iterate over each Entry in a Collection Map?</a> </p>
</blockquote>
<p>What is the best way to iterate through a <code>HashMap</code>?</p>
","29","317","<java><hashmap>","2009-06-30 23:24:14","FALSE","FALSE","1066603","2014-03-06 09:49:58","1044","<p>Iterate through the <a href=""http://www.java2s.com/Code/JavaAPI/java.util/HashtableentrySet.htm""><code>entrySet</code></a> like so:</p>
<pre><code>public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + "" = "" + pairs.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
</code></pre>
<p>Read more on <a href=""http://docs.oracle.com/javase/7/docs/api/java/util/Map.html""><code>Map</code></a></p>
","578","2","1","15","2009-06-30 23:27:25","3","TRUE","182505","45"
"http://stackoverflow.com/users/41967","http://stackoverflow.com/questions/1004382","http://stackoverflow.com/questions/1004382/#1004404","2012-10-21 03:25:13","8","22412","1","3","How do I specify conditions from 2 different beans in a jsf rendered attribute?","<p>I want to do something along the lines of the following but when I use it like this I get a parse error telling me an entity needs to directly follow the '&amp;' character:</p>
<pre><code>&lt;ice:selectManyCheckbox
rendered=""#{!bean1.condition1 &amp;&amp; bean2.condition2}""
value=""#{bean1.selected}""&gt;
&lt;f:selectItems value=""#{bean2.items}"" /&gt;
&lt;/ice:selectManyCheckbox&gt;
</code></pre>
<p>How can I get rendered to check conditions from 2 different beans?</p>
","79","477","<java><jsf><rendered-attribute>","2009-06-16 23:16:26","TRUE","FALSE","1004404","2012-06-07 13:02:45","14","<p>Use 'and' instead:</p>
<pre><code>&lt;ice:selectManyCheckbox rendered=""#{!bean1.condition1 and bean2.condition2}"" value=""#{bean1.selected}""&gt;
</code></pre>
","162","1","1","1","2009-06-16 23:26:20","10","TRUE","182505","0"
"http://stackoverflow.com/users/28557","http://stackoverflow.com/questions/684841","http://stackoverflow.com/questions/684841/#684858","2009-04-30 17:26:58","0","607","0","4","Regular Expression (Java)","<p>How do I match the following string?</p>
<pre><code>http://localhost:8080/MenuTest/index.action
</code></pre>
<p>The regex should return true if it contains ""MenuTest"" in the above pattern.</p>
<p>Cheers</p>
","25","214","<java><regex><string>","2009-03-26 07:39:54","TRUE","FALSE","684858","2009-04-22 23:08:53","9","<p>Maybe you don't need a regex?</p>
<pre><code>String url = ""http://localhost:8080/MenuTest/index.action"";
boolean hasWhatImLookingFor = url.contains(""MenuTest"");
</code></pre>
","183","1","1","3","2009-03-26 07:48:07","9","TRUE","182505","0"
"http://stackoverflow.com/users/18853","http://stackoverflow.com/questions/924208","http://stackoverflow.com/questions/924208/#924220","2014-08-08 04:15:16","58","71304","17","5","How to convert nanoseconds to seconds using the TimeUnit enum?","<p>How to convert a value from nanoseconds to seconds? </p>
<p>Here's the code segment: </p>
<pre><code>import java.io.*;
import java.util.concurrent.*;
..
class Stamper {
public static void main (String[] args) {
long start = System.nanoTime();
//some try with nested loops
long end = System.nanoTime();
long elapsedTime = end - start;
System.out.println(""elapsed: "" + elapsedTime + ""nano seconds\n"");
//convert to seconds
TimeUnit seconds = new TimeUnit();
System.out.println(""which is "" + seconds.toSeconds(elapsedTime) + "" seconds"");
}}
</code></pre>
<p>The error is </p>
<pre><code>Stamper.java:16: enum types may not be instantiated.
</code></pre>
<p>What does this mean?</p>
","62","702","<java>","2009-05-29 02:56:37","TRUE","FALSE","924220","2014-08-08 04:15:16","81","<p>Well, you could just divide by 1,000,000,000:</p>
<pre><code>long elapsedTime = end - start;
double seconds = (double)elapsedTime / 1000000000.0;
</code></pre>
<p>If you use <code>TimeUnit</code> to convert, you'll get your result as a long, so you'll lose decimal precision but maintain whole number precision.</p>
","321","2","1","12","2009-05-29 03:00:33","4","TRUE","180595","12"
"http://stackoverflow.com/users/23572","http://stackoverflow.com/questions/408661","http://stackoverflow.com/questions/408661/#408668","2009-01-04 08:44:26","20","2225","2","4","What code does the compiler generate for autoboxing?","<p>When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls:</p>
<ul>
<li>The valueOf() method on the wrapper</li>
<li>The wrapper's constructor</li>
<li>Some other magic?</li>
</ul>
","52","260","<java><autoboxing>","2009-01-03 05:32:02","FALSE","FALSE","408668","2009-01-04 08:44:26","30","<p>You can use the <code>javap</code> tool to see for yourself. Compile the following code:</p>
<pre><code>public class AutoboxingTest
{
public static void main(String []args)
{
Integer a = 3;
int b = a;
}
}
</code></pre>
<p>To compile and disassemble:</p>
<pre><code>javac AutoboxingTest.java
javap -c AutoboxingTest
</code></pre>
<p>The output is:</p>
<pre><code>Compiled from ""AutoboxingTest.java""
public class AutoboxingTest extends java.lang.Object{
public AutoboxingTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object.""&lt;init&gt;"":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: aload_1
6: invokevirtual #3; //Method java/lang/Integer.intValue:()I
9: istore_2
10: return
}
</code></pre>
<p>Thus, as you can see, autoboxing invokes the static method <code>Integer.valueOf()</code>, and autounboxing invokes <code>intValue()</code> on the given <code>Integer</code> object. There's nothing else, really - it's just syntactic sugar.</p>
","1182","4","3","4","2009-01-03 05:40:09","8","TRUE","180595","0"
"http://stackoverflow.com/users/2077","http://stackoverflow.com/questions/663512","http://stackoverflow.com/questions/663512/#663523","2009-03-19 18:53:15","8","2247","0","8","In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around?","<p>In a Java program, I have multiple subclasses inheriting from a parent (which is abstract). I wanted to express that every child should have a member that is set once only (which I was planning to do from the constructor). My plan was to code s.th. like this:</p>
<pre><code>public abstract class Parent {
protected final String birthmark;
}
public class Child extends Parent {
public Child(String s) {
this.birthmark = s;
}
}
</code></pre>
<p>However, this seems to not please the Java gods. In the parent class, I get the message that <code>birthmark</code> ""might not have been initialized"", in the child class I get ""The final field <code>birthmark</code> cannot be accessed"".</p>
<p>So what's the Java way for this? What am I missing?</p>
","143","771","<java><final>","2009-03-19 18:45:35","TRUE","FALSE","663523","2009-03-19 18:53:15","15","<p>You can't do it because while comparing the parent class, the compiler can't be sure that the subclass will initialize it. You'll have to initialize it in the parent's constructor, and have the child call the parent's constructor:</p>
<pre><code>public abstract class Parent {
protected final String birthmark;
protected Parent(String s) {
birthmark = s;
}
}
public class Child extends Parent {
public Child(String s) {
super(s);
...
}
}
</code></pre>
","502","1","1","2","2009-03-19 18:48:42","3","TRUE","180595","0"
"http://stackoverflow.com/users/50940","http://stackoverflow.com/questions/419314","http://stackoverflow.com/questions/419314/#419317","2014-06-04 21:06:53","5","7521","1","3","invalid header file while using jar for archiving","<p>When i use this cmd line :
jar cmf arshad.mf ars.jar *.class
i get this error :</p>
<pre><code>invalid header field name:Manifest-version
</code></pre>
<p>This is my manifest file :</p>
<pre><code>Manifest-Version: 1.0
Main-Class:t
</code></pre>
<p>i made the manifest file with notepad in UTF-8 encoding - is there any problem with the manifest ?</p>
","49","360","<java><jar>","2009-01-07 05:40:53","TRUE","FALSE","419317","2014-06-04 21:06:53","11","<p>Add a space after the colons:</p>
<pre><code>Manifest-Version: 1.0
Main-Class: t
</code></pre>
","99","1","1","1","2009-01-07 05:44:23","4","TRUE","180595","0"
"http://stackoverflow.com/users/2332560","http://stackoverflow.com/questions/16329310","http://stackoverflow.com/questions/16329310/#16330367","2013-05-02 04:32:10","3","2222","2","1","Gottox socket.io-java-client ""Error while handshaking"" null pointer exception","<p>I'm trying to use socket.io to connect to a streaming server hosted by <a href=""https://community.geoloqi.com/discussion/75/viewing-real-time-group-location-in-a-map-using-ios-sdk/p1"" rel=""nofollow"" title=""Geoloqi"">Geoloqi</a></p>
<p>I grabbed the Gottox socket.io-java-client code straight from github and didn't make any modifications, except to change the url, but it's giving me the ""Error while handshaking"" message. The url should work as I got it from the makers of Geoloqi: <a href=""https://community.geoloqi.com/discussion/19/data-streaming#Item_11"" rel=""nofollow"">https://community.geoloqi.com/discussion/19/data-streaming#Item_11</a> (see the 1st response).</p>
<p>Here is the code, from BasicExample.java</p>
<pre><code>package basic;
/*
* socket.io-java-client Test.java
*
* Copyright (c) 2012, Enno Boland
* socket.io-java-client is a implementation of the socket.io protocol in Java.
*
* See LICENSE file for more information
*/
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import org.json.JSONException;
import org.json.JSONObject;
public class BasicExample implements IOCallback {
private SocketIO socket;
/**
* @param args
*/
public static void main(String[] args) {
try {
new BasicExample();
} catch (Exception e) {
e.printStackTrace();
}
}
public BasicExample() throws Exception {
socket = new SocketIO();
// socket.connect(""http://localhost:8080/"", this);
socket.connect(""https://subscribe.geoloqi.com:443"", this);
// Sends a string to the server.
socket.send(""Hello Server"");
// Sends a JSON object to the server.
socket.send(new JSONObject().put(""key"", ""value"").put(""key2"",
""another value""));
// Emits an event to the server.
socket.emit(""event"", ""argument1"", ""argument2"", 13.37);
}
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println(""Server said:"" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println(""Server said: "" + data);
}
@Override
public void onError(SocketIOException socketIOException) {
System.out.println(""an Error occured"");
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
System.out.println(""Connection terminated."");
}
@Override
public void onConnect() {
System.out.println(""Connection established"");
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println(""Server triggered event '"" + event + ""'"");
}
}
</code></pre>
<p>Here is the error message:</p>
<pre><code>an Error occured
io.socket.SocketIOException: Error while handshaking
at io.socket.IOConnection.handshake(IOConnection.java:322)
at io.socket.IOConnection.access$7(IOConnection.java:292)
at io.socket.IOConnection$ConnectThread.run(IOConnection.java:199)
Caused by: java.lang.NullPointerException
at io.socket.IOConnection.handshake(IOConnection.java:302)
... 2 more
May 1, 2013 10:02:49 PM io.socket.IOConnection cleanup
INFO: Cleanup
</code></pre>
<p>What's going wrong with the code?</p>
","77","3476","<java><nullpointerexception><socket.io>","2013-05-02 02:14:46","TRUE","FALSE","16330367","2013-05-02 04:32:10","7","<p>Looking at the <a href=""https://github.com/Gottox/socket.io-java-client/blob/master/src/io/socket/IOConnection.java"">source code</a> where the exception is coming from (<code>IOConnection.java:302</code>, from the inner <code>NullPointerException</code>), there's this block of code:</p>
<pre><code>if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection)
.setSSLSocketFactory(sslContext.getSocketFactory());
}
</code></pre>
<p>Clearly <code>connection</code> must be non-null, otherwise it wouldn't pass the <code>instanceof</code> test. Therefore, <code>sslContext</code> must be null. Since the only other places in that file that <code>sslContext</code> is referenced is in <code>setSslContext()</code> and <code>getSslContext()</code>, the only logical conclusion is that <strong>you must call <code>setSslContext()</code> prior to making an SSL connection</strong>. <code>SocketIO.setDefaultSSLSocketFactory()</code> also calls through to <code>IOConnection.setSslContext()</code>, so you can call that too instead.</p>
<p>Try this:</p>
<pre><code>SocketIO.setDefaultSSLSocketFactory(SSLContext.getDefault());
socket = new SocketIO();
socket.connect(""https://subscribe.geoloqi.com:443"", this);
...
</code></pre>
","1265","3","2","1","2013-05-02 04:32:10","138","TRUE","180595","0"
"http://stackoverflow.com/users/153086","http://stackoverflow.com/questions/1567788","http://stackoverflow.com/questions/1567788/#1567806","2009-10-14 17:33:20","2","227","0","2","Compilation error while compiling class within another","<p>I have two classes Hello1 and Hello, and I'm calling class Hello1 constructor within Hello class, but when I trying to compile the Hello class with command </p>
<p>javac Hello.java</p>
<p>I'm getting compile time error:</p>
<pre><code>Hello.java:6:cannot find the symbol
symbol: class Hello1
location: class Hello
Hello1=new Hello();
^
Hello.java:6:cannot find the symbol
symbol: class Hello1
location: class Hello
Hello1=new Hello();
^
</code></pre>
<p>But when I try to compile the compile the class with command:</p>
<p><strong>javac Hello.java Hello1.java</strong></p>
<p>it's working fine, but why I have to use this command every time to compile the class? Why the compiler can't use the already compiled .class Hello1 file, so that next time I use the command javac Hello.java. </p>
","54","811","<java><compiler-construction>","2009-10-14 17:27:09","TRUE","FALSE","1567806","2009-10-14 17:33:20","1","<p>You need to add the current directory to your classpath so the compiler can find it. By default, the classpath does not include the current working directory, so any .class files which have already been compiled won't be seen by the compiler. To do this, compile like this:</p>
<pre><code>javac Hello.java -cp .
</code></pre>
","332","1","1","1","2009-10-14 17:32:27","5","TRUE","180595","0"
"http://stackoverflow.com/users/16487","http://stackoverflow.com/questions/963007","http://stackoverflow.com/questions/963007/#963010","2009-06-07 23:47:39","1","2962","0","2","Javac cannot find jar for apache commons config","<p>I'm trying to compile a very simple program in Java 1.6 on Ubuntu Jaunty, using Apache Commons Config jar. I keep getting the ""package org.apache.commons.configuration does not exist"" error, even though the jar is in the same directory. Any ideas?</p>
<ul>
<li>Directory Listing</li>
</ul>
<pre>
~/source/UpdateStockHistory$ ll
total 304
-rw-r--r-- 1 crosse crosse 298829 2009-06-07 17:36 commons-configuration-1.6.jar
-rw-r--r-- 1 crosse crosse 149 2009-06-07 17:16 UpdateStockHistory.config.xml
-rw-r--r-- 1 crosse crosse 531 2009-06-07 17:46 UpdateStockHistory.java
</pre>
<ul>
<li>Java Version</li>
</ul>
<pre>
~/source/UpdateStockHistory$ javac -version
javac 1.6.0_13
</pre>
<ul>
<li>OS Version</li>
</ul>
<pre>
~/source/UpdateStockHistory$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 9.04
Release: 9.04
Codename: jaunty
</pre>
<ul>
<li>Compiler Version</li>
</ul>
<pre>
~/source/UpdateStockHistory$ javac UpdateStockHistory.java
UpdateStockHistory.java:2: package org.apache.commons.configuration does not exist
import org.apache.commons.configuration.*;
^
UpdateStockHistory.java:8: cannot find symbol
symbol : class ConfigurationFactory
location: class com.crosse.tradingresearch.UpdateStockHistory
ConfigurationFactory factory = new ConfigurationFactory(""UpdateStockHistory.config.xml"");
^
UpdateStockHistory.java:8: cannot find symbol
symbol : class ConfigurationFactory
location: class com.crosse.tradingresearch.UpdateStockHistory
ConfigurationFactory factory = new ConfigurationFactory(""UpdateStockHistory.config.xml"");
^
UpdateStockHistory.java:9: cannot find symbol
symbol : class Configuration
location: class com.crosse.tradingresearch.UpdateStockHistory
Configuration config = factory.getConfiguration();
^
4 errors
</pre>
<p>Hate to ask such a ""do it for me"" question, but I've run out of ideas.</p>
","47","2083","<java><linux><command-line><compilation>","2009-06-07 23:14:52","FALSE","FALSE","963010","2009-06-07 23:47:39","5","<p>Try adding the jar to your classpath as so:</p>
<pre><code>javac UpdateStockHistory.java -cp commons-configuration-1.6.jar
</code></pre>
","141","1","1","2","2009-06-07 23:18:05","4","TRUE","180595","0"
"http://stackoverflow.com/users/490268","http://stackoverflow.com/questions/4083708","http://stackoverflow.com/questions/4083708/#4083717","2010-11-03 03:13:08","1","374","0","2","StackOverflowError - adding a value to a heap","<p>I'm currently working on an applet that displays a heap as values are added and removed. I'm implementing the heaps as tree of integers - IntTrees. I'm writing the code for skew heaps, and the 'add' method is giving me some trouble. The add method usually works, but once in a while it causes a stack overflow error when a value is added, and I can't seem to figure out why.</p>
<p>Here's the code I have written for the add method</p>
<p>'t' is an instance variable - the heap itself.</p>
<pre><code> // adds value to heap
public void add(int value) {
IntTree smallTree = new IntTree(value, empty(), empty());
if (t == null) {
t = smallTree;
} else {
t = merge(t, smallTree);
}
}
public IntTree merge(IntTree left, IntTree right) {
if (isEmpty(left)) return right;
if (isEmpty(right)) return left;
int leftVal = left.value();
int rightVal = right.value();
IntTree result;
if (rightVal &lt;= leftVal) {
result = merge(right,left);
} else {
result = left;
if (result.isEmpty(left)) {
result.setLeft(right);
} else {
IntTree temp = result.right();
result.setRight(result.left());
result.setLeft(merge(temp,right));
}
}
return result;
}
</code></pre>
<p>Is there something in this code that would cause a stack overflow error, or is the problem perhaps elsewhere in the program? Thanks!</p>
","45","1348","<java><algorithm><heap>","2010-11-03 02:08:29","TRUE","FALSE","4083717","2010-11-03 03:13:08","2","<p>Take a look at this snippet</p>
<pre><code>if (rightVal &lt;= leftVal) {
result = merge(right,left);
</code></pre>
<p>What happens when <code>rightVal == leftVal</code>?</p>
","181","2","1","1","2010-11-03 02:12:02","4","TRUE","180595","0"
"http://stackoverflow.com/users/2383916","http://stackoverflow.com/questions/20754675","http://stackoverflow.com/questions/20754675/#20755167","2013-12-24 05:09:13","0","79","0","1","Error with JNI (Java and C++)","<p>I am trying to use <code>JNI</code> with <code>C++</code> but it is not going right I have justified all the steps to call a <code>c++</code> method from <code>java</code> . but I am getting following error (Java code and C++ code is given below)</p>
<p><strong>Java Code is here</strong></p>
<pre><code>public class KeyLogger {
public native void capture();
static{
System.loadLibrary(""KeyLogger"");
}
public static void main(String[]args){
KeyLogger obj = new KeyLogger();
obj.capture();
}
}
</code></pre>
<p><strong>C++ code here</strong></p>
<pre><code>**// All libraries included Fucntion goes here.**
JNIEXPORT void JNICALL Java_KeyLogger_capture
(JNIEnv *env, jobject obj){
cout&lt;&lt;""Working Fine""&lt;&lt;endl;
}
void main(){}
</code></pre>
<p><strong>Error</strong></p>
<pre><code>Exception in thread ""main"" java.lang.UnsatisfiedLinkError: KeyLogger.capture()V
at KeyLogger.capture(Native Method)
at KeyLogger.main(KeyLogger.java:10)
</code></pre>
<p>What should i do for this to get solved</p>
","29","1075","<java><c++><jni>","2013-12-24 04:00:25","TRUE","FALSE","20755167","2013-12-24 05:09:13","0","<p>You need to declare your C++ method as <code>extern ""C""</code> to ensure that its symbol name is not mangled and can be found by the dynamic linker:</p>
<pre><code>extern ""C""
{
...
JNIEXPORT void JNICALL Java_KeyLogger_capture(JNIEnv *env, jobject obj) {
...
}
...
} // end extern ""C""
</code></pre>
<p>Alternatively, instead of using generated function names which can be difficult to get exactly right, you can use the <a href=""http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp17734"" rel=""nofollow""><code>RegisterNatives()</code></a> function to register the native methods from within your <a href=""http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#JNI_OnLoad"" rel=""nofollow""><code>JNI_OnLoad()</code></a> routine.</p>
","791","2","1","1","2013-12-24 05:09:13","69","TRUE","180595","0"
"http://stackoverflow.com/users/784980","http://stackoverflow.com/questions/8913598","http://stackoverflow.com/questions/8913598/#8913733","2012-01-23 22:46:16","1","574","0","3","T-SQL stored procedure does not return zero by COUNT(*) on an empty SELECT result","<p>I am using the Spring Framework's <code>StoredProcedure</code> (I am extending it, of course) to get a result set and an output parameter (<code>@totalRowsReturned</code>) which is an Integer. The problem is that when the resultset being returned is supposed to be an empty list, I am getting a <code>NullPointerException</code> when I try to retrieve the output parameter (totalRows, which naively I would expect it to be zero).</p>
<p>I would like to mention that the code works fine when the result set being found is not empty.</p>
<p><strong>My questions are:</strong></p>
<ol>
<li><p>Why isn't <code>@totalRowsReturned</code> being set to zero in this case? (Or in case it is, why can't I retrieve it through the Java code?)</p></li>
<li><p>How can I make this code (Java code + T-SQL code) work in such a way that <code>@totalRowsReturned</code> will be set to zero when required, and I could retrieve it through the Java code?</p></li>
</ol>
<p><strong>Dao:</strong></p>
<pre><code>List&lt;Book&gt; books = null;
int totalRows = 0;
Map&lt;String, Object&gt; results = storedProcedure.execute(parameters);
books = (List&lt;Book&gt;) results.get(""rs"");
totalRows = (Integer) results.get(""totalRowsReturned""); // NullPointerException on this line if total rows are supposed to be zero!!
</code></pre>
<p><strong>T-SQL stored procedure:</strong></p>
<pre><code>CREATE PROCEDURE Find_Books
@authorName Varchar(250),
@totalRowsReturned INTEGER OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SelectQuery NVARCHAR(2000)
SET @SelectQuery = 'SELECT @totalRows=COUNT(*) OVER() FROM book b WHERE b.author_name = @authorName'
Execute sp_Executesql @SelectQuery, N'@authorName VARCHAR(250), @totalRows int OUTPUT', @authorName, @totalRows=@totalRowsReturned OUTPUT
-- Select resultset goes here...
END
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>Actually, my stored procedure looks more like this (the change is the additional <strong><code>@first_id = b.book_id</code></strong> in the SELECT):</p>
<pre><code>CREATE PROCEDURE Find_Books
@authorName Varchar(250),
@totalRowsReturned INTEGER OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SelectQuery NVARCHAR(2000)
DECLARE @first_id int
DECLARE @first_id_local_returned int
SET @SelectQuery = 'SELECT @first_id = b.book_id, @totalRows=COUNT(*) OVER() FROM book b WHERE b.author_name = @authorName'
Execute sp_Executesql @SelectQuery, N'@authorName VARCHAR(250), @first_id int OUTPUT, @totalRows int OUTPUT', @authorName, @first_id=@first_id_local_returned OUTPUT, @totalRows=@totalRowsReturned OUTPUT
-- Select resultset goes here... I am using the value of @first_id_local_returned in this SELECT...
END
</code></pre>
<p>The problem is, that when there are no rows returned from the SELECT, b.book_id is not defined, so I get an <strong><code>org.springframework.dao.TransientDataAccessResourceException ... Column 'book.book_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.</code></strong></p>
<p>So it seems like if I keep the <code>OVER()</code>, then <code>@totalRows=COUNT(*) OVER()</code> fails when there are zero rows returned, and if I remove the <code>OVER()</code>, then <code>@first_id = b.book_id</code> fails.</p>
<p>Any idea how I overcome this?</p>
","81","3372","<java><sql-server><spring><tsql><stored-procedures>","2012-01-18 16:22:44","TRUE","FALSE","8913733","2012-01-23 22:46:16","2","<p><code>COUNT(*) OVER ()</code> is not the correct thing to use here. Just use <code>COUNT(*)</code></p>
<p><code>COUNT(*) OVER ()</code> returns a result set with as many rows as the <code>COUNT</code>. e.g if the result is 3 the result set will be</p>
<pre><code>3
3
3
</code></pre>
<p>The effect of your query is then to repeatedly re-assign the value <code>3</code> to the <code>@totalRows</code> variable as many times as there are rows which is completely pointless.</p>
<p>Conversely if <code>COUNT(*) = 0</code> then the <code>COUNT(*) OVER ()</code> result set is empty so your variable is never assigned to at all.</p>
<p><code>COUNT(*)</code> will always give you a single row scalar resultset here that you can assign to the variable and will have a more efficient execution plan without unnecessary common subexpression spools too.</p>
<p><strong>Edit</strong></p>
<p>In response to your question in the comments. This does the same thing as your linked article. It can use a narrower index to find the (say) 10,000th Employee then joins onto Department only for the 1 subsequent page of records. This paging method only works correctly because each employee has exactly one department.</p>
<pre><code>WITH E1(RN, EmployeeID)
AS (SELECT ROW_NUMBER() OVER (ORDER BY EmployeeID),
EmployeeID
FROM Employees)
SELECT TOP (@maximumRows) e.*,
d.Name AS DepartmentName
FROM Employees e
INNER JOIN Departments d
ON e.DepartmentID = d.DepartmentID
WHERE EmployeeID &gt;= (SELECT EmployeeID
FROM E1
WHERE RN = @startRowIndex)
ORDER BY e.EmployeeID
</code></pre>
","1700","7","2","5","2012-01-18 16:31:08","9","TRUE","179833","0"
"http://stackoverflow.com/users/767843","http://stackoverflow.com/questions/11126263","http://stackoverflow.com/questions/11126263/#11126373","2013-03-07 07:02:43","19","1922","5","1","Bind method call in JavaScript script in Java Scripting","<p>Suppose I have a Javascript file</p>
<pre><code>function js_main(args){
/* some code */
var x = api_method1(some_argument);
/* some code */
}
</code></pre>
<p>And I try to run it with <code>javax.scripting</code> the usual way</p>
<pre><code>ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(""javascript"");
engine.eval(...);
</code></pre>
<p>Now the I'd like to handle the call to <code>api_method1</code> in Javascript with my Java class. I'd like to have some kind of mapping/binding of calls i.e. each time the script calls <code>api_method1(arg)</code> a method</p>
<pre><code>public Object api_method1(Object arg){ ... }
</code></pre>
<p>(placed in the same class as the engine) would be called.</p>
<p>Can I achieve this?</p>
","55","810","<java><javascript><scripting>","2012-06-20 18:53:44","TRUE","FALSE","11126373","2013-03-07 07:02:43","13","<ol>
<li>use <code>engine.createBindings()</code> to make a Bindings object;</li>
<li><p>put an object exposing your method into the bindings with some name:</p>
<pre><code>Bindings b = engine.createBindings();
b.put(""api"", yourApiObject);
engine.setBindings(b, ScriptContext.ENGINE_SCOPE);
</code></pre></li>
<li><p>Then in JavaScript there'll be a global ""api"" object you can call:</p>
<pre><code>api.method1( ""foo"", 14, ""whatever"" );
</code></pre></li>
</ol>
<p>The facility is easy to use, but be careful with what you pass back and forth; it doesn't do that much to convert JavaScript types to Java types.</p>
","618","3","2","4","2012-06-20 19:00:39","7","TRUE","178871","0"
"http://stackoverflow.com/users/742469","http://stackoverflow.com/questions/10913999","http://stackoverflow.com/questions/10913999/#10914138","2014-01-29 02:21:14","6","3093","0","6","JSON Representation of Map with Complex Key","<p>I want to serialize to JSON the following (java) data structure:</p>
<pre><code>class Machine {
String name;
Map&lt;PartDescriptor, Part&gt; parts;
}
class PartDescriptor {
String group;
String id;
hashCode()
equals()
}
class Part {
String group;
String id;
String description;
String compat;
...
...
}
</code></pre>
<p>What would be JSON representation of one <code>Machine</code>?</p>
<p>Also (<em>optional</em>), point me to a JSON to Java serializer/deserializer that will support your representation</p>
","43","542","<java><javascript><json><serialization>","2012-06-06 12:13:33","TRUE","FALSE","10914138","2014-01-29 02:21:14","4","<p>I'd do something like:</p>
<pre><code>{
""name"": ""machine name"",
""parts"": [
{ ""group"": ""part group"", ""id"": ""part id"", ""description"": ""..."", ... },
{ ""group"": ""part group"", ""id"": ""part id"", ""description"": ""..."", ... },
// ...
]
}
</code></pre>
<p>If the ""id"" for each Part is unique, then the ""parts"" property can be an object instead of an array, with the ""id"" of each part serving as the key.</p>
<pre><code>{
""name"": ""machine name"",
""parts"": {
""1st part id"": { ""group"": ""part group"", ""description"": ""..."", ... },
""2nd part id"": { ""group"": ""part group"", ""description"": ""..."", ... },
// ...
}
}
</code></pre>
","656","2","2","1","2012-06-06 12:21:49","8","TRUE","178871","0"
"http://stackoverflow.com/users/359862","http://stackoverflow.com/questions/3093580","http://stackoverflow.com/questions/3093580/#3093643","2013-12-09 15:35:51","4","4898","0","6","How to check whether the file is binary?","<p>I wrote the following method to see whether particular file contains ASCII text characters only or control characters in addition to that. Could you glance at this code, suggest improvements and point out oversights?</p>
<p>The logic is as follows: ""If first 500 bytes of a file contain 5 or more Control characters - report it as binary file""</p>
<p>thank you.</p>
<pre><code>public boolean isAsciiText(String fileName) throws IOException {
InputStream in = new FileInputStream(fileName);
byte[] bytes = new byte[500];
in.read(bytes, 0, bytes.length);
int x = 0;
short bin = 0;
for (byte thisByte : bytes) {
char it = (char) thisByte;
if (!Character.isWhitespace(it) &amp;&amp; Character.isISOControl(it)) {
bin++;
}
if (bin &gt;= 5) {
return false;
}
x++;
}
in.close();
return true;
}
</code></pre>
","40","919","<java><file><binary><ascii>","2010-06-22 13:35:26","TRUE","FALSE","3093643","2013-12-09 15:35:51","3","<p>Since you call this class ""isASCIIText"", you know exactly what you're looking for. In other words, it's not ""isTextInCurrentLocaleEncoding"". Thus you can be more accurate with:</p>
<pre><code>if (thisByte &lt; 32 || thisByte &gt; 127) bin++;
</code></pre>
<p><em>edit, a long time later</em> &mdash; it's pointed out in a comment that this simple check would be tripped up by a text file that started with a lot of newlines. It'd probably be better to use a table of ""ok"" bytes, and include printable characters (including carriage return, newline, and tab, and possibly form feed though I don't think many modern documents use those), and then check the table.</p>
","672","2","1","2","2010-06-22 13:41:07","6","TRUE","178871","0"
"http://stackoverflow.com/users/44286","http://stackoverflow.com/questions/2217750","http://stackoverflow.com/questions/2217750/#2217763","2010-02-07 18:57:53","3","1966","0","5","comparing todays date + 30 days to another date","<p>I'm trying an example:</p>
<pre><code>DateFormat df = new SimpleDateFormat(""MM/dd/yyyy"");
String date = ""03/09/2010""; //30 days from today
Date usefullDate = df.parse(date);
Calendar todaysDatePlus30Days = Calendar.getInstance();
todaysDatePlus30Days.add(Calendar.DAY_OF_YEAR, 30);
System.out.println (""Compared Value: "" +
usefullDate.compareTo(todaysDatePlus30Days.getTime()))
</code></pre>
<p>the printed value is <code>-1</code>. why is it not printing <code>0</code>?</p>
<p>I think the problem is that <code>todaysDatePlus30Days.getTime()</code> is bringing the actual time as well. whereas <code>usefullDate</code>'s time is <code>00:00:00</code>.</p>
<p>So next question is how can I just get the <code>date</code>?</p>
","47","737","<java><date>","2010-02-07 18:25:38","TRUE","FALSE","2217763","2010-02-07 18:40:02","3","<p>The date you parse is implicitly midnight of that date. The one you construct will be the current time of day.</p>
<p>Try:</p>
<pre><code>Calendar todayPlus30 = new GregorianCalendar() {{
add(Calendar.DAY_OF_YEAR, 30);
set(Calendar.HOUR_OF_DAY, 0);
set(Calendar.MINUTE, 0);
set(Calendar.SECOND, 0);
set(Calendar.MILLISECOND, 0);
}};
</code></pre>
<p><em>I might have a couple of those constants wrong, and you can do this with Calendar.newInstance() if you like, though the syntax is a little different.</em></p>
","530","3","1","3","2010-02-07 18:29:41","4","TRUE","178871","0"
"http://stackoverflow.com/users/702638","http://stackoverflow.com/questions/11438406","http://stackoverflow.com/questions/11438406/#11438816","2012-07-11 18:23:23","3","1261","0","1","Browser does not generate file download dialog","<p>My current scenario is that the JavaScript client has a bunch of data that I POST to the server to process/translate into different formats (e.g. CSV), now I want to send that transformed data from the server to the client.</p>
<p>I set the content type of the response, but the browser does not generate a file dialog.</p>
<p>Here is what my controller looks like:</p>
<pre><code>@RequestMapping(value=""/exportBoxes/{type}/{filename:.+}"", method=RequestMethod.POST)
public String exportBoxes(@RequestBody String body, @PathVariable String type,
@PathVariable String filename, HttpServletResponse response) throws IOException
{
JsonObject jsonObject = new JsonParser().parse(body).getAsJsonObject();
//grab the data from the JSONobject
String data = jsonObject.get(""JSONdata"").getAsString();
//create output stream writer
PrintWriter p = new PrintWriter(response.getOutputStream());
//set response type and print header
if(type.equals(""csv""))
{
response.setContentType(""text/csv"");
response.setHeader(""Content-Disposition"", ""attachment; filename=\"""" + filename + ""\"""");
}
//print the points to the file
for(int i = 0; i &lt; splitPoints.length; i++)
{
//print remainder of CSV file - abstracted
}
p.flush(); //flush the stream
response.flushBuffer();
p.close(); //close the stream
return ""success"";
}
</code></pre>
<p>And here is the client function that POSTs the data:</p>
<pre><code>DAService.prototype.exportBoxes = function(type, filename, data) {
var path = 'api/rest/da/exportBoxes/' + type + '/' + filename
var url = (this.connection) ? this.connection + path : path;
var JSONdata = '';
var returnType = ''
//create JSON string to pass to Java controller
if(type == 'csv')
{
JSONdata = '{ ""JSONdata"" : ""' + data.replace(/ /g, '') + '"" }';
returnType = 'text/csv';
}
else
{
throw ""Invalid export format "" + type;
}
$j.ajax({
url: url,
contentType: 'application/json',
type: 'POST',
dataType: returnType,
data: JSONdata,
success: function(returnedData){
console.log(""exportBox successful"");
},
error: function(x,y,z) {
console.log(""exportBox failed with error '"" + y + ""'"");
},
complete: function(empty, textStatus){
console.log(""exportBox complete textStatus='"" + textStatus + ""'"");
}
});
};
</code></pre>
<p>No errors are generated by this code and the server's response has the CSV file in it, I just can't get the client to generate the download dialog.</p>
<p>There is one piece that I am missing that I don't see, can anyone help me out? </p>
","46","2838","<java><javascript><jquery><spring-mvc>","2012-07-11 17:45:08","TRUE","FALSE","11438816","2012-07-11 18:23:23","3","<p>You might want to try posting a form instead of using <code>$.ajax</code>:</p>
<pre><code>var form = $('&lt;form/&gt;', {
action: url,
method: 'POST',
css: { display: 'none' },
html: $('&lt;input/&gt;', {name: 'JSONdata', value: data.replace(/ /g, '') })
});
$('body').append(form);
form.submit();
</code></pre>
<p>(I haven't tested that.) The point is that when you really post a form, the browser knows to interpret the response body, and it should notice your attachment.</p>
","493","2","1","5","2012-07-11 18:13:43","28","TRUE","178871","0"
"http://stackoverflow.com/users/281535","http://stackoverflow.com/questions/2387760","http://stackoverflow.com/questions/2387760/#2387771","2010-03-05 15:31:37","2","1556","1","1","Manual setting CLASSPATH with -cp or -classpath does not work as expected","<p>MyClassWithMainMethod.java uses classes of someJar.jar.</p>
<p>If I call:</p>
<pre><code>java -cp someJar.jar MyClassWithMainMethod
</code></pre>
<p>I get the exception:</p>
<pre><code>Exception in thread ""main"" java.lang.NoClassDefFoundError: MyClassWithMainMethod
Caused by: java.lang.ClassNotFoundException: MyClassWithMainMethod
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:315)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:330)
at java.lang.ClassLoader.loadClass(ClassLoader.java:250)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:398)
</code></pre>
<p>But when I set the CLASSPATH to my jar manually</p>
<pre><code>export CLASSPATH=:/path/to/someJar.jar
</code></pre>
<p>it works calling</p>
<pre><code>java MyClassWithMainMethod
</code></pre>
<p>What am I doing wrong?</p>
","73","1010","<java><jar><classpath>","2010-03-05 15:19:57","TRUE","FALSE","2387771","2010-03-05 15:31:37","7","<p>What about</p>
<pre><code>java -cp /path/to/someJar.jar MyClassWithMainMethod
</code></pre>
<p>If you don't give Java the complete path to the jar file, how do you expect that it would find it?</p>
<p>OK well the argument you give to ""-cp"" is the same sort of thing you use with the CLASSPATH variable - what happens when you do this:</p>
<pre><code>java -cp .:someJar.jar MyClassWithMainMethod
</code></pre>
","416","3","2","7","2010-03-05 15:21:43","2","TRUE","178871","0"
"http://stackoverflow.com/users/245626","http://stackoverflow.com/questions/2426380","http://stackoverflow.com/questions/2426380/#2426431","2013-07-29 04:46:43","1","10092","0","2","Capture multiple check box selection JSP Parameters","<p>I found this <a href=""http://stackoverflow.com/questions/1617569/failing-to-retrieve-multiple-checked-value-from-jsp"">post</a> that shows how to pass multiple check box selections to another JSP page, but it's not working for me. When I try to get the selected values I get:</p>
<p>checked boxes: [Ljava.lang.String;@3f3fbd</p>
<p>Here are my two pages (be gentle, this is my first attempt at JSP!)</p>
<p>createSHAREfile.jsp basically runs a query to find all the terms that have not been processed and show each term with a check box next to it:</p>
<pre><code> &lt;title&gt;Create SHARE Files&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;jsp:include page=""../menu/header.jsp"" flush=""false"" /&gt;
&lt;form name='SelectSHARETerms' method='post' action=""SHAREProcessing.jsp""&gt;
&lt;fieldset&gt;&lt;legend&gt;Select Terms to Process for SHARE&lt;/legend&gt;
&lt;table align='left'&gt;
&lt;% String termDetail = """", currDate = """";
currentDateTime datetime = new currentDateTime();
datetime.setCurrDate();
currDate = datetime.getCurrDate();
java.sql.Date todayDate = java.sql.Date.valueOf(currDate);
Terms terms = new Terms();
ArrayList&lt;Terms.termsTable&gt; termsObjList = new ArrayList&lt;Terms.termsTable&gt;();
terms.setTermsSql(""Select * from Terms where TermDate &lt;= '"" + currDate + ""' AND VoucherProcessDate Is Null"");
boolean indicator = terms.setListOfTerms();
if (indicator == true) {
int size = terms.getListSize();
termsObjList = terms.getTermsList();
for (int i=0; i&lt;size; ++i) {
Terms.termsTable eachTerm = (Terms.termsTable)termsObjList.get(i);
java.sql.Date termDate = eachTerm.TermDate;
%&gt;
&lt;tr&gt;&lt;td&gt;&lt;input type=checkbox name=SelectedTermDate id='SelectedTermDate&lt;%=i%&gt;' value=""&lt;%=i%&gt;""&gt;&lt;%=termDate %&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;%
}
}
%&gt;
&lt;tr&gt;&lt;td align='center'&gt;&lt;input type='submit' value='Submit'&gt;&lt;/input&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;/fieldset&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>When the submit button is pressed I call SHAREProcessing.jsp. Right now all i'm trying to do on this page is show which termdates the user has selected so I can use them as parameters to a Java Class that will create the files for the selected terms:</p>
<pre><code> &lt;title&gt;SHARE Processing&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;jsp:include page=""../menu/header.jsp"" flush=""false"" /&gt;
&lt;table width='50%' align='center' border='1'&gt;
&lt;% String[] SelectedValues = request.getParameterValues(""SelectedTermDate"");
System.out.println(""checked boxes: "" + SelectedValues);
%&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Here's where I'm trying to use the code shown in the other post but it's not working :(</p>
<p>Thanks for any help!
Leslie</p>
","51","2985","<java><arrays><jsp>","2010-03-11 15:47:10","TRUE","FALSE","2426431","2013-07-29 04:46:43","3","<p>You're trying to print the whole string array with System.out.println, and so you get that. It's probably working fine.</p>
<p>Try this:</p>
<pre><code>System.out.println(""checked boxes:"");
for (int i = 0; i &lt; SelectedValues.length; ++i)
System.out.println("" "" + SelectedValues[i]);
</code></pre>
<p>Also, I beg you: in your spare time, find out about a modern web framework (there are zillions for Java) and strive to escape from the painful world of coding Java inside JSP files.</p>
","498","3","1","7","2010-03-11 15:52:41","5","TRUE","178871","0"
"http://stackoverflow.com/users/268627","http://stackoverflow.com/questions/4829347","http://stackoverflow.com/questions/4829347/#4829373","2011-01-28 14:46:23","1","2427","1","1","How to invoke java method from javascript","<p>As described in the title, what I am trying to achieve is the following:</p>
<ol>
<li>Create java object</li>
<li>Pass it to JavaScript</li>
<li>Invoke a method (a setter for instance) on the passed object</li>
<li>Continue work with the object in java</li>
</ol>
<p>I am using the scripting included in java.
I will be happy if someone can help me to do this.</p>
","41","370","<java><javascript><rhino>","2011-01-28 14:33:54","FALSE","FALSE","4829373","2011-01-28 14:46:23","4","<p>If you're working with the ScriptEngine framework, this is really easy. You can ""pass"" Java objects to JavaScript in two ways:</p>
<ol>
<li>You can ""seed"" the execution environment for JavaScript code and arrange for Java objects to just be ""there"" in the global namespace</li>
<li>You can pass Java objects in as arguments to JavaScript functions.</li>
</ol>
<p>You can also access Java constructors from JavaScript and instantiate Java objects if you want.</p>
<p>To do the first thing, you have to set up the ""bindings"" for the script engine. It's just like a Map:</p>
<pre><code>final Bindings globals = engine.createBindings();
globals.put(""foo"", yourObject);
</code></pre>
<p>Now, when JavaScript code runs in that engine, the global symbol ""foo"" will serve as a reference to a Java object. You can bind in as many references as you like.</p>
<p>If you want to pass a Java object as a parameter to a JavaScript function, the first thing you need is a way to <em>call</em> a JavaScript function. To do that, you use the ""invokeFunction"" or ""invokeMethod"" method exposed by the ""Invocable"" interface:</p>
<pre><code>final Object result = ((Invocable) engine).invokeMethod(context, methodName, arg, arg, ... );
</code></pre>
<p>The ""context"" there is just a reference to something you want <code>this</code> to refer to in the function that's called. The ""methodName"" is just a string giving the name of your global JavaScript function.</p>
<p>Java classes are available to the JavaScript environment via their fully-qualified pathnames:</p>
<pre><code>var javaHashMap = new java.util.HashMap();
</code></pre>
<p>That would give you a Java HashMap instance as a JavaScript variable.</p>
","1706","8","3","4","2011-01-28 14:36:18","3","TRUE","178871","0"
"http://stackoverflow.com/users/255494","http://stackoverflow.com/questions/2487414","http://stackoverflow.com/questions/2487414/#2487424","2010-03-21 17:43:21","1","292","0","5","Counter that will remember its value","<p>I have a task to operate on complex number. Each number consists of double r = real part, double i = imaginary part and String name. Name must be set within constructor, so I've created int counter, then I'm sending its value to setNextName function and get name letter back. Unfortunately incrementing this 'counter' value works only within costructor and then it is once again set to 0. How to deal with that?Some constant value? And second problem is that I also need to provide setNextNames(char c) function that will change the counter current value.</p>
<p>The code :</p>
<pre><code>public class Imaginary {
private double re;
private double im;
private String real;
private String imaginary;
private String name;
private int counter=0;
public Imaginary(double r, double u){
re = r;
im = u;
name = this.setNextName(counter);
counter++;
}
public static String setNextName(int c){
String nameTab[] = {""A"",""B"",""C"",""D"",""E"",""F"",""G"",""H"",""I"",""J"",""K"",""L"",""M"",""N"",
""O"",""P"",""Q"",""R"",""S"",""T"",""U"",""W"",""V"",""X"",""Y"",""Z""};
String setName = nameTab[c];
System.out.println(""c: ""+c);
return setName;
}
public static String setNextName(char c){
//
//don't know how to deal with this part
//
}
</code></pre>
","36","1260","<java><constants>","2010-03-21 14:30:12","TRUE","FALSE","2487424","2010-03-21 17:43:21","4","<p>It's hard to tell what you're doing, but I suspect this will solve your immediate problem:</p>
<pre><code>private static int counter = 0;
</code></pre>
","156","1","1","3","2010-03-21 14:32:39","2","TRUE","178871","0"
"http://stackoverflow.com/users/87234","http://stackoverflow.com/questions/11227809","http://stackoverflow.com/questions/11227809/#11227902","2014-09-20 05:58:31","8686","489600","4853","9","Why is processing a sorted array faster than an unsorted array?","<p>Here is a piece of C++ code that seems very peculiar. For some strange reason, sorting the data miraculously makes the code almost six times faster:</p>
<pre class=""lang-cpp prettyprint-override""><code>#include &lt;algorithm&gt;
#include &lt;ctime&gt;
#include &lt;iostream&gt;
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c &lt; arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i &lt; 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c &lt; arraySize; ++c)
{
if (data[c] &gt;= 128)
sum += data[c];
}
}
double elapsedTime = static_cast&lt;double&gt;(clock() - start) / CLOCKS_PER_SEC;
std::cout &lt;&lt; elapsedTime &lt;&lt; std::endl;
std::cout &lt;&lt; ""sum = "" &lt;&lt; sum &lt;&lt; std::endl;
}
</code></pre>
<ul>
<li>Without <code>std::sort(data, data + arraySize);</code>, the code runs in <strong>11.54</strong> seconds.</li>
<li>With the sorted data, the code runs in <strong>1.93</strong> seconds.</li>
</ul>
<hr>
<p>Initially, I thought this might be just a language or compiler anomaly. So I tried it in Java:</p>
<pre class=""lang-java prettyprint-override""><code>import java.util.Arrays;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];
Random rnd = new Random(0);
for (int c = 0; c &lt; arraySize; ++c)
data[c] = rnd.nextInt() % 256;
// !!! With this, the next loop runs faster
Arrays.sort(data);
// Test
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i &lt; 100000; ++i)
{
// Primary loop
for (int c = 0; c &lt; arraySize; ++c)
{
if (data[c] &gt;= 128)
sum += data[c];
}
}
System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println(""sum = "" + sum);
}
}
</code></pre>
<p>With a somewhat similar, but less extreme result.</p>
<hr>
<p>My first thought was that sorting brings the data into the cache, but my next thought was how silly that is, because the array was just generated.</p>
<ul>
<li>What is going on? </li>
<li>Why is a sorted array faster than an unsorted array? </li>
<li>The code is summing up some independent terms, and the order should not matter. </li>
</ul>
","63","2731","<java><c++><performance><optimization><branch-prediction>","2012-06-27 13:51:36","FALSE","FALSE","11227902","2014-03-16 20:54:41","13171","<p><strong>You are the victim of <a href=""//en.wikipedia.org/wiki/Branch_predictor"">branch prediction</a> fail.</strong></p>
<hr>
<h2>What is Branch Prediction?</h2>
<p>Consider a railroad junction:</p>
<p><a href=""//commons.wikimedia.org/wiki/File%3aEntroncamento_do_Transpraia.JPG""><img src=""//i.stack.imgur.com/muxnt.jpg"" alt=""""></a>
<sub><a href=""//commons.wikimedia.org/wiki/File%3aEntroncamento_do_Transpraia.JPG"">Image</a> by Mecanismo, via Wikimedia Commons. Used under the <a href=""//creativecommons.org/licenses/by-sa/3.0/deed.en"">CC-By-SA 3.0</a> license.</sub></p>
<p>Now for the sake of argument, suppose this is back in the 1800s - before long distance or radio communication.</p>
<p>You are the operator of a junction and you hear a train coming. You have no idea which way it will go. You stop the train to ask the captain which direction he wants. And then you set the switch appropriately.</p>
<p><em>Trains are heavy and have a lot of inertia. So they take forever to start up and slow down.</em></p>
<p>Is there a better way? You guess which direction the train will go!</p>
<ul>
<li>If you guessed right, it continues on.</li>
<li>If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.</li>
</ul>
<p><strong>If you guess right every time</strong>, the train will never have to stop.<br>
<strong>If you guess wrong too often</strong>, the train will spend a lot of time stopping, backing up, and restarting.</p>
<hr>
<p><strong>Consider an if-statement:</strong> At the processor level, it is a branch instruction:</p>
<p><img src=""//i.stack.imgur.com/pyfwC.png"" alt=""enter image description here""></p>
<p>You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.</p>
<p><em>Modern processors are complicated and have long pipelines. So they take forever to ""warm up"" and ""slow down"".</em></p>
<p>Is there a better way? You guess which direction the branch will go!</p>
<ul>
<li>If you guessed right, you continue executing.</li>
<li>If you guessed wrong, you need to flush the pipeline and roll back to the branch. Then you can restart down the other path.</li>
</ul>
<p><strong>If you guess right every time</strong>, the execution will never have to stop.<br>
<strong>If you guess wrong too often</strong>, you spend a lot of time stalling, rolling back, and restarting.</p>
<hr>
<p>This is branch prediction. I admit it's not the best analogy since the train could just signal the direction with a flag. But in computers, the processor doesn't know which direction a branch will go until the last moment.</p>
<p>So how would you strategically guess to minimize the number of times that the train must back up and go down the other path? You look at the past history! If the train goes left 99% of the time, then you guess left. If it alternates, then you alternate your guesses. If it goes one way every 3 times, you guess the same...</p>
<p><em><strong>In other words, you try to identify a pattern and follow it.</em></strong> This is more or less how branch predictors work.</p>
<p>Most applications have well-behaved branches. So modern branch predictors will typically achieve >90% hit rates. But when faced with unpredictable branches with no recognizable patterns, branch predictors are virtually useless.</p>
<p>Further reading: <a href=""//en.wikipedia.org/wiki/Branch_predictor"">""Branch predictor"" article on Wikipedia</a>.</p>
<hr>
<h2>As hinted from above, the culprit is this if-statement:</h2>
<pre><code>if (data[c] &gt;= 128)
sum += data[c];
</code></pre>
<p>Notice that the data is evenly distributed between 0 and 255.
When the data is sorted, roughly the first half of the iterations will not enter the if-statement. After that, they will all enter the if-statement.</p>
<p>This is very friendly to the branch predictor since the branch consecutively goes the same direction many times.
Even a simple saturating counter will correctly predict the branch except for the few iterations after it switches direction.</p>
<p><strong>Quick visualization:</strong></p>
<pre><code>T = branch taken
N = branch not taken
data[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...
branch = N N N N N ... N N T T T ... T T T ...
= NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT (easy to predict)
</code></pre>
<p>However, when the data is completely random, the branch predictor is rendered useless because it can't predict random data.
Thus there will probably be around 50% misprediction. (no better than random guessing)</p>
<pre><code>data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118, 14, 150, 177, 182, 133, ...
branch = T, T, N, T, T, T, T, N, T, N, N, T, T, T, N ...
= TTNTTTTNTNNTTTN ... (completely random - hard to predict)
</code></pre>
<hr>
<p><strong>So what can be done?</strong></p>
<p>If the compiler isn't able to optimize the branch into a conditional move, you can try some hacks if you are willing to sacrifice readability for performance.</p>
<p>Replace:</p>
<pre><code>if (data[c] &gt;= 128)
sum += data[c];
</code></pre>
<p>with:</p>
<pre><code>int t = (data[c] - 128) &gt;&gt; 31;
sum += ~t &amp; data[c];
</code></pre>
<p>This eliminates the branch and replaces it with some bitwise operations.</p>
<p><sub>(Note that this hack is not strictly equivalent to the original if-statement. But in this case, it's valid for all the input values of <code>data[]</code>.)</sub></p>
<p><strong>Benchmarks: Core i7 920 @ 3.5 GHz</strong></p>
<p>C++ - Visual Studio 2010 - x64 Release</p>
<pre><code>// Branch - Random
seconds = 11.777
// Branch - Sorted
seconds = 2.352
// Branchless - Random
seconds = 2.564
// Branchless - Sorted
seconds = 2.587
</code></pre>
<p>Java - Netbeans 7.1.1 JDK 7 - x64</p>
<pre><code>// Branch - Random
seconds = 10.93293813
// Branch - Sorted
seconds = 5.643797077
// Branchless - Random
seconds = 3.113581453
// Branchless - Sorted
seconds = 3.186068823
</code></pre>
<p>Observations:</p>
<ul>
<li><strong>With the Branch:</strong> There is a huge difference between the sorted and unsorted data.</li>
<li><strong>With the Hack:</strong> There is no difference between sorted and unsorted data.</li>
<li>In the C++ case, the hack is actually a tad slower than with the branch when the data is sorted.</li>
</ul>
<p>A general rule of thumb is to avoid data-dependent branching in critical loops. (such as in this example)</p>
<hr>
<p><strong>Update :</strong></p>
<ul>
<li><p>GCC 4.6.1 with <code>-O3</code> or <code>-ftree-vectorize</code> on x64 is able to generate a conditional move. So there is no difference between the sorted and unsorted data - both are fast.</p></li>
<li><p>VC++ 2010 is unable to generate conditional moves for this branch even under <code>/Ox</code>.</p></li>
<li><p>Intel Compiler 11 does something miraculous. It <a href=""//en.wikipedia.org/wiki/Loop_interchange"">interchanges the two loops</a>, thereby hoisting the unpredictable branch to the outer loop. So not only is it immune the mispredictions, it is also twice as fast as whatever VC++ and GCC can generate! In other words, ICC took advantage of the test-loop to defeat the benchmark...</p></li>
<li><p>If you give the Intel Compiler the branchless code, it just out-right vectorizes it... and is just as fast as with the branch (with the loop interchange).</p></li>
</ul>
<p>This goes to show that even mature modern compilers can vary wildly in their ability to optimize code...</p>
","7763","40","7","70","2012-06-27 13:56:42","5","TRUE","176175","250"
"http://stackoverflow.com/users/256196","http://stackoverflow.com/questions/13995885","http://stackoverflow.com/questions/13995885/#13995983","2012-12-26 00:15:04","42","3148","10","6","How to predict the maximum call depth of a recursive method?","<p>For the purposes of estimating the maximum call depth a recursive method may achieve with a given amount of memory, what is the (approximate) formula for calculating the memory used before a stackoverflow error is likely to occur?</p>
<h3>Edit:</h3>
<p>Many have responded with ""it depends"", which is reasonable, so let's remove some of the variables by using a trivial but concrete example:</p>
<pre><code>public static int sumOneToN(int n) {
return n &lt; 2 ? 1 : n + sumOneToN(n - 1);
}
</code></pre>
<p>It is easy to show that running this in my Eclipse IDE explodes for <code>n</code> just under 1000 (surprisingly low to me).
Could this call depth limit have been estimated without executing it?</p>
<p>Edit: I can't help thinking that Eclipse has a fixed max call depth of 1000, because I got to <code>998</code>, but there's one for the main, and one for the initial call to the method, making <code>1000</code> in all. This is ""too round"" a number IMHO to be a coincidence. I'll investigate further. I have just Dux overhead the -Xss vm parameter; it's the maximum stack size, so Eclipse runner must have <code>-Xss1000</code> set somewhere </p>
","60","1167","<java><memory><recursion><jvm><stackoverflow>","2012-12-21 19:15:03","TRUE","FALSE","13995983","2012-12-22 10:03:50","21","<p>This is clearly JVM- and possibly also architecture-specific.</p>
<p>I've measured the following:</p>
<pre><code> static int i = 0;
public static void rec0() {
i++;
rec0();
}
public static void main(String[] args) {
...
try {
i = 0; rec0();
} catch (StackOverflowError e) {
System.out.println(i);
}
...
}
</code></pre>
<p>using </p>
<pre><code>Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode)
</code></pre>
<p>running on x86.</p>
<p>With a 20MB Java stack (<code>-Xss20m</code>), the amortized cost fluctuated around 16-17 bytes per call. The lowest I've seen was 16.15 bytes/frame. I therefore conclude that the cost is 16 bytes and the rest is other (fixed) overhead.</p>
<p>A function that takes a single <code>int</code> has basically the same cost, 16 bytes/frame.</p>
<p>Interestingly, a function that takes ten <code>ints</code> requires 32 bytes/frame. I am not sure why the cost is so low.</p>
<p>The above results apply after the code's been JIT compiled. Prior to compilation the per-frame cost is <em>much, much</em> higher. I haven't yet figured out a way to estimate it reliably. <strong>However, this does mean that you have no hope of reliably predicting maximum recursion depth until you can reliably predict whether the recursive function has been JIT compiled.</strong></p>
<p>All of this was tested with a <code>ulimit</code> stack sizes of 128K and 8MB. The results were the same in both cases.</p>
","1572","9","2","9","2012-12-21 19:24:12","9","TRUE","173646","0"
"http://stackoverflow.com/users/586986","http://stackoverflow.com/questions/8896758","http://stackoverflow.com/questions/8896758/#8896824","2014-08-28 19:04:34","34","52086","4","8","Initial size for the arraylist","<p>This may be a stupid question but here it is. So you can set the initial size for an array list by doing</p>
<pre><code>ArrayList&lt;Integer&gt; arr=new ArrayList&lt;Integer&gt;(10);
</code></pre>
<p>However you cant do (causes an out of bounds exception)</p>
<pre><code>arr.add(5, 10);
</code></pre>
<p>So my question is what is the use of setting an initial size then if you cant access the space you allocated ?</p>
<p>UPDATE: The add function is defined as <code>add(int index, Object element)</code> so I am not adding to index 10. </p>
","30","550","<java><arraylist><indexoutofboundsexception>","2012-01-17 14:56:01","TRUE","FALSE","8896824","2012-01-17 15:18:52","66","<p>You're confusing the size of the array list with its capacity:</p>
<ul>
<li>the <strong>size</strong> is the number of elements in the list;</li>
<li>the <strong>capacity</strong> is how many elements the list can potentially accommodate without reallocating its internal structures.</li>
</ul>
<p>When you call <code>new ArrayList&lt;Integer&gt;(10)</code>, you are setting the list's initial <em>capacity</em>, not its size. In other words, when constructed in this manner, the array list starts its life empty.</p>
<p>One way to add ten elements to the array list is by using a loop:</p>
<pre><code>for (int i = 0; i &lt; 10; i++) {
arr.add(0);
}
</code></pre>
<p>Having done this, you can now modify elements at indices 0..9.</p>
","744","4","1","2","2012-01-17 14:59:25","3","TRUE","173646","0"
"http://stackoverflow.com/users/91497","http://stackoverflow.com/questions/7593969","http://stackoverflow.com/questions/7593969/#7594052","2013-08-24 15:17:11","34","10873","11","5","RegEx to split camelCase or TitleCase (advanced)","<p>I found a <a href=""http://jason.diamond.name/weblog/2009/08/15/splitting-camelcase-with-regular-expressions/"">brilliant RegEx</a> to extract the part of a camelCase or TitleCase expression.</p>
<pre><code> (?&lt;!^)(?=[A-Z])
</code></pre>
<p>It works as expected:</p>
<ul>
<li>value -> value</li>
<li>camelValue -> camel / Value</li>
<li>TitleValue -> Title / Value</li>
</ul>
<p>For example with Java:</p>
<pre><code>String s = ""loremIpsum"";
words = s.split(""(?&lt;!^)(?=[A-Z])"");
//words equals words = new String[]{""lorem"",""Ipsum""}
</code></pre>
<p>My problem is that it does not work in some cases:</p>
<ul>
<li>Case 1: VALUE -> V / A / L / U / E</li>
<li>Case 2: eclipseRCPExt -> eclipse / R / C / P / Ext</li>
</ul>
<p>To my mind, the result shoud be:</p>
<ul>
<li>Case 1: VALUE</li>
<li>Case 2: eclipse / RCP / Ext</li>
</ul>
<p>In other words, given n uppercase chars:</p>
<ul>
<li>if the n chars are followed by lower case chars, the groups should be: (n-1 chars) / (n-th char + lower chars)</li>
<li>if the n chars are at the end, the group should be: (n chars).</li>
</ul>
<p>Any idea on how to improve this regex?</p>
","48","1147","<java><regex><camelcasing><title-case>","2011-09-29 07:36:39","TRUE","FALSE","7594052","2011-09-29 18:50:07","30","<p>The following regex works for all of the above examples:</p>
<pre><code>public static void main(String[] args)
{
for (String w : ""camelValue"".split(""(?&lt;!(^|[A-Z]))(?=[A-Z])|(?&lt;!^)(?=[A-Z][a-z])"")) {
System.out.println(w);
}
}
</code></pre>
<p>It works by forcing the negative lookbehind to not only ignore matches at the start of the string, but to also ignore matches where a capital letter is preceded by another capital letter. This handles cases like ""VALUE"".</p>
<p>The first part of the regex on its own fails on ""eclipseRCPExt"" by failing to split between ""RPC"" and ""Ext"". This is the purpose of the second clause: <code>(?&lt;!^)(?=[A-Z][a-z]</code>. This clause allows a split before every capital letter that is followed by a lowercase letter, except at the start of the string.</p>
","824","3","1","3","2011-09-29 07:45:57","9","TRUE","173646","0"
"http://stackoverflow.com/users/443854","http://stackoverflow.com/questions/7770183","http://stackoverflow.com/questions/7770183/#7770240","2014-04-01 20:58:47","13","8229","4","5","List contents of multiple jar files","<p>I am searching for a .class file inside a bunch of jars.</p>
<pre><code>jar tf abc.jar
</code></pre>
<p>works for one file. I tried </p>
<pre><code>find -name ""*.jar"" | xargs jar tf
</code></pre>
<p>prints nothing. The only solution I can think of, is unzip all, then search. Is there a better way? I'm on LUnix.</p>
<p><strong>Edit</strong>:
When scanning many jars, it is useful to print the jar file name along with the class. This method works well:</p>
<pre><code>find . | grep jar$ | while read fname; do jar tf $fname | grep SchemaBuilder &amp;&amp; echo $fname; done
</code></pre>
<p>Sample output produced:</p>
<pre><code> 1572 Wed Jul 25 10:20:18 EDT 2007 org/apache/ws/commons/schema/SchemaBuilder$1.class
1718 Wed Jul 25 10:20:18 EDT 2007 org/apache/ws/commons/schema/SchemaBuilder$2.class
42607 Wed Jul 25 10:20:18 EDT 2007 org/apache/ws/commons/schema/SchemaBuilder.class
./XmlSchema-1.3.2.jar
1572 Wed Jul 25 10:20:18 EDT 2007 org/apache/ws/commons/schema/SchemaBuilder$1.class
1718 Wed Jul 25 10:20:18 EDT 2007 org/apache/ws/commons/schema/SchemaBuilder$2.class
42607 Wed Jul 25 10:20:18 EDT 2007 org/apache/ws/commons/schema/SchemaBuilder.class
./XmlSchema.jar
</code></pre>
","35","1213","<java><linux><shell><jar>","2011-10-14 15:48:50","TRUE","FALSE","7770240","2011-10-14 15:59:11","23","<p>You need to pass <code>-n 1</code> to <code>xargs</code> to force it to run a separate <code>jar</code> command for each filename that it gets from <code>find</code>:</p>
<pre><code>find -name ""*.jar"" | xargs -n 1 jar tf
</code></pre>
<p>Otherwise <code>xargs</code>'s command line looks like <code>jar tf file1.jar file2.jar...</code>, which has a different meaning to what is intended.</p>
<p>A useful debugging technique is to stick <code>echo</code> before the command to be run by <code>xargs</code>:</p>
<pre><code>find -name ""*.jar"" | xargs echo jar tf
</code></pre>
<p>This would print out the full <code>jar</code> command instead of executing it, so that you can see what's wrong with it.</p>
","711","4","2","3","2011-10-14 15:52:10","4","TRUE","173646","0"
"http://stackoverflow.com/users/321397","http://stackoverflow.com/questions/2850203","http://stackoverflow.com/questions/2850203/#2850259","2013-09-15 19:07:10","15","21259","3","9","Count the number of lines in a Java String","<p>Need some compact code for counting the number of lines in a string in Java. The string is to be separated by <code>\r</code> or <code>\n</code>. Each instance of those newline characters will be considered as a separate line. For example,</p>
<pre><code>""Hello\nWorld\nThis\nIs\t""
</code></pre>
<p>should return 4. The prototype is </p>
<pre><code>private static int countLines(String str) {...}
</code></pre>
<p>Can someone provide a compact set of statements? I have solution at here but it is too long, I think. Thank you.</p>
","42","538","<java><string>","2010-05-17 15:08:47","TRUE","FALSE","2850259","2013-09-15 19:07:10","26","<pre><code>private static int countLines(String str){
String[] lines = str.split(""\r\n|\r|\n"");
return lines.length;
}
</code></pre>
","140","0","1","2","2010-05-17 15:14:38","6","TRUE","173500","0"
"http://stackoverflow.com/users/549432","http://stackoverflow.com/questions/6866694","http://stackoverflow.com/questions/6866694/#6866756","2014-08-21 14:37:04","0","6976","0","4","Java Delete files older than N days","<p>I would like some Java code to Delete files older than N days. </p>
<p>Here is my attempt, but it doesn't work quite right.</p>
<pre><code>public void deleteFilesOlderThanNdays(final int daysBack, final String dirWay) {
System.out.println(dirWay);
System.out.println(daysBack);
final File directory = new File(dirWay);
if(directory.exists()){
System.out.println("" Directory Exists"");
final File[] listFiles = directory.listFiles();
final long purgeTime =
System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
System.out.println(""System.currentTimeMillis "" +
System.currentTimeMillis());
System.out.println(""purgeTime "" + purgeTime);
for(File listFile : listFiles) {
System.out.println(""Length : ""+ listFiles.length);
System.out.println(""listFile.getName() : "" +listFile.getName());
System.out.println(""listFile.lastModified() :""+
listFile.lastModified());
if(listFile.lastModified() &lt; purgeTime) {
System.out.println(""Inside File Delete"");
}
}
}
else
{
}
}
</code></pre>
<p>Is there some simple code to delete files older than N days in a directory?</p>
","35","1296","<java><file><file-management>","2011-07-28 22:48:52","TRUE","FALSE","6866756","2011-07-28 23:04:58","2","<p>Try to use the <a href=""http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html"" rel=""nofollow"">Calendar</a>-Class instead:</p>
<pre><code> Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, daysBack * -1);
long purgeTime = cal.getTimeInMillis();
</code></pre>
<p>Or try <a href=""http://www.coderanch.com/t/538161/java/java/Couldn-delete-all-files-older"" rel=""nofollow"">this solution</a>:</p>
<p>Is your number of days over 24? If so, you have an overflow problem.</p>
<p>If the number of days is 25, the value will be 25 * 24 * 60 * 60 *
1000. The mathematical value is 2160000000. However, this is larger than Integer.MAX_VALUE, and therefore the value overflows to
-12516353. As a result, the purge time will be in the future, and will never be met. Values larger than 25 will only make the problem worse; it's even possible the overflow is so bad that the multiplication results in a positive value again leading to perhaps purge all files.</p>
<p>The fix is easy:</p>
<ol>
<li>declare daysBack as a long</li>
<li><p>cast daysBack as a long</p>
<p>long purgeTime = System.currentTimeMillis() - ((long)daysBack * 24 * 60 * 60 * 1000); </p></li>
<li><p>Use explicit long literals inside the calculation:</p>
<p>long purgeTime = System.currentTimeMillis() - (daysBack * 24L * 60L * 60L * 1000L); </p></li>
</ol>
<p>For all three solutions, the fact that the first and/or second operand is a long turns the entire result into a long, allowing a value of 2160000000 without overflowing.</p>
","1548","10","1","1","2011-07-28 22:57:31","9","TRUE","173500","0"
"http://stackoverflow.com/users/2444240","http://stackoverflow.com/questions/18690098","http://stackoverflow.com/questions/18690098/#18690152","2013-12-21 10:07:35","5","324","1","3","What is the most programatically efficient way to determine if a number is a power of 2?","<p>Just a simple of boolean true/false that is very efficient would be nice. Should I use recursion, or is there some better way to determine it?</p>
","88","150","<java><performance><math><recursion><binary>","2013-09-09 00:41:38","FALSE","FALSE","18690152","2013-12-21 10:07:35","13","<p>From <a href=""http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2"" rel=""nofollow"">here</a>:</p>
<blockquote>
<p><strong>Determining if an integer is a power of 2</strong> </p>
<pre><code>unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v &amp; (v - 1)) == 0;
</code></pre>
<p>Note that 0 is incorrectly considered a power of 2 here. To remedy
this, use: </p>
<pre><code>f = v &amp;&amp; !(v &amp; (v - 1));
</code></pre>
</blockquote>
<p>Why does this work? An integer power of two only ever has a single bit set. Subtracting 1 has the effect of changing that bit to a zero and all the bits below it to one. <code>AND</code>'ing that with the original number will always result in all zeros. </p>
","787","4","2","1","2013-09-09 00:49:12","8","TRUE","173049","0"
"http://stackoverflow.com/users/2536791","http://stackoverflow.com/questions/20507739","http://stackoverflow.com/questions/20507739/#20507763","2013-12-10 23:57:47","4","87","0","2","What am I doing wrong with this quadratic formula?","<pre><code> a = 1, b = -7, c = 12
public static void quadratic(double a, double b, double c){
double r1;
double r2;
double turducken;
turducken = Math.pow(b,2)-(4*a*c);
r1 = (-1*b) + ((Math.sqrt(turducken))/(2*a));
r2 = (-1*b) - ((Math.sqrt(turducken))/(2*a));
System.out.println(""r1: ""+r1);
System.out.println(""r2: ""+r2);
</code></pre>
<p>The System prints out 7.5 and 6.5 when the answers should be 4 and 3.</p>
<p>I cant quite figure out what im doing wrong here. </p>
","50","512","<java><math>","2013-12-10 23:43:47","TRUE","FALSE","20507763","2013-12-10 23:57:47","10","<p>Should be:</p>
<pre><code> r1 = ((-1*b) + Math.sqrt(turducken))/(2*a);
r2 = ((-1*b) - Math.sqrt(turducken))/(2*a);
</code></pre>
<p>(i.e. everything divided by <code>2 * a</code>)</p>
<p>You could simplify your expression slightly further:</p>
<pre><code> double sq = Math.sqrt(b*b - 4*a*c);
r1 = (-b + sq)/(2*a);
r2 = (-b - sq)/(2*a);
</code></pre>
<p>(I find the simpler the expression, the easier it is to spot mistakes)</p>
","439","4","2","1","2013-12-10 23:45:45","2","TRUE","173049","0"
"http://stackoverflow.com/users/1125547","http://stackoverflow.com/questions/8696529","http://stackoverflow.com/questions/8696529/#8696549","2012-01-02 01:28:44","2","3611","0","3","Java Integer add leading zeros?","<p>I need to add leading zeros to an array for mathematical use.
Specifically, I am making something to add two large numbers. The numbers are stored as an int array, where each element of the array is 5 digits. One example is
53498 93784 45891 45982 48933 58947
I need to add another to this, say,
23584 42389 32479 34289 39281 48237
To add them I would take the last 5 digits of both and add them 58947+48237
This gives 107184. Then I set the carry value to 1 and subtract 100,000. </p>
<p>This is the problem:
It sets the int to 7184, then the sum says ...882157184 instead of 8821507184, making a (very) incorrect sum.
So how do I get my Sum int array to say 88215 07184?
If this is not possible, please list another way of getting the same result, maybe a string instead of a int array?
If at all possible, please try to find a way to have a leading 0 with an int value.</p>
","31","882","<java><integer><int>","2012-01-02 00:28:59","FALSE","FALSE","8696549","2012-01-02 00:45:46","15","<p>Have you considered using Java's <a href=""http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html"">BigInteger</a> class?</p>
<ul>
<li><p><a href=""http://stackoverflow.com/questions/849813/large-numbers-in-java"">Large Numbers in Java</a></p></li>
<li><p><a href=""http://wiki.compsci.ca/index.php?title=Java_Big_Integers"">Java Big Integers</a></p></li>
<li><p><a href=""http://stackoverflow.com/questions/4095024/java-comparing-biginteger-values"">Java, comparing BigInteger values</a></p></li>
<li><p><a href=""http://stackoverflow.com/questions/3878192/converting-from-integer-to-biginteger"">Converting from Integer, to BigInteger</a></p></li>
</ul>
<p>e.g.</p>
<pre><code>BigInteger quiteBig = new BigInteger(""534989378445891459824893358947"");
</code></pre>
","777","6","1","4","2012-01-02 00:33:24","5","TRUE","173049","0"
"http://stackoverflow.com/users/2280545","http://stackoverflow.com/questions/20436809","http://stackoverflow.com/questions/20436809/#20436817","2013-12-07 19:17:15","1","271","0","1","Java Swing weird Gui output when creating a 10x10 grid of JPanels in GridLayout","<p>So I have been looking at this problem and debugging for days, and I cant find where is the problem.
I am making a Battleship game, and I need to create 2 10x10 grids for player and opponent.
I was using NetBeans Designer tool to create this simple layout. 2 Labels, 3 Buttons, and 2 Panels which will act as a wrapper for my grids.
(I set layout of those wrapper pannels to GridLayout with 10 columns and 10 rows)</p>
<p><a href=""http://i.imgur.com/KlZ7EjF.jpg"" rel=""nofollow"">http://i.imgur.com/KlZ7EjF.jpg</a></p>
<p>Then I made a simple code to populate those wrappers with grids.</p>
<pre><code>public void initFields()
{
pan = new JPanel[10][10];
for(int i=0; i&lt;10; i++)
{
for(int j=0; j&lt;10; j++)
{
pan[i][j] = new JPanel();
pan[i][j].setBackground(Color.WHITE);
pan[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
pan[i][j].setPreferredSize(new Dimension(25,25));
wrapper1.add(pan[i][j]);
}
}
pan2 = new JPanel[10][10];
for(int i=0; i&lt;10; i++)
{
for(int j=0; j&lt;10; j++)
{
pan2[i][j] = new JPanel();
pan2[i][j].setBackground(Color.WHITE);
pan2[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
pan2[i][j].setPreferredSize(new Dimension(25,25));
wrapper2.add(pan[i][j]);
}
}
}
</code></pre>
<p>And at the end I get this:</p>
<p><a href=""http://i.imgur.com/92y9K5y.jpg"" rel=""nofollow"">http://i.imgur.com/92y9K5y.jpg</a></p>
<p>My JPannel pan gets populated in wrapper2, and wrapper1 stays empty.
Tried debugging, making Gui Snapshot, and everything seems as it should be, but the end result is contrary to everything else.</p>
","79","1782","<java><swing><variables><netbeans><jpanel>","2013-12-07 02:25:38","TRUE","FALSE","20436817","2013-12-07 19:17:15","3","<p>In the second loop You are adding <code>pan[][]</code> again instead of <code>pan2[][]</code>:</p>
<pre><code>wrapper2.add(pan2[i][j]);
^
</code></pre>
","172","1","1","2","2013-12-07 02:26:54","1","TRUE","173049","0"
"http://stackoverflow.com/users/587884","http://stackoverflow.com/questions/7913694","http://stackoverflow.com/questions/7913694/#7913713","2011-10-31 15:59:49","1","429","0","2","From Java to C#: storing couple of int using Dimension","<p>Usually in Java when I need to store 2 int value related to some graphic properties I use Dimension Object:</p>
<pre><code>Dimension d = new Dimension(x,y);
</code></pre>
<p>Is there any similar object in C# (and XNA)? I'm currently using Vector2 but it's designed for floating values.
Actually I need such a structure to create a list of screen coordinates. I'm looking for something to use this way:</p>
<pre><code>IList&lt;Dimension&gt; list = new List&lt;Dimension&gt;();
list.add(new Dimension(800,600));
...
</code></pre>
","54","535","<c#><java><xna>","2011-10-27 08:58:34","TRUE","FALSE","7913713","2011-10-31 15:59:49","3","<p><a href=""http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.point.aspx"" rel=""nofollow""><code>Point</code></a>:</p>
<blockquote>
<p>Defines a point in 2D space.</p>
</blockquote>
<pre><code>IList&lt;Point&gt; list = new List&lt;Point&gt;();
</code></pre>
","274","2","1","1","2011-10-27 08:59:56","1","TRUE","173049","0"
"http://stackoverflow.com/users/810860","http://stackoverflow.com/questions/6700717","http://stackoverflow.com/questions/6700717/#6700737","2014-09-14 07:57:07","81","303861","24","8","How to Iterate Through an Array List (ArrayIndexOutOfBoundsException)","<p>So right now I have a program containing a piece of code that looks like this...</p>
<pre><code>while (arrayList.iterator().hasNext())
{
if( arrayList.iterator().next().equals(value)) //value is equal to a String value
{
//do something...
}
}
</code></pre>
<p>Am I doing that right, as far as iterating through the Arraylist goes? </p>
<p>The error I am getting is:</p>
<pre><code>java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.get(Unknown Source)
at main1.endElement(main1.java:244)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at main1.traverse(main1.java:73)
at main1.traverse(main1.java:102)
at main1.traverse(main1.java:102)
at main1.main(main1.java:404)
</code></pre>
<p>I would show the rest of the code, but it's pretty extensive, and if I am not doing the iteration correctly, I would assume the only possibility is that I am not initializing the array list properly. So thank you in advance for any help/advice that is offered.</p>
","69","2064","<java><iterator><arraylist><iteration><indexoutofboundsexception>","2011-07-14 22:29:32","TRUE","FALSE","6700737","2012-12-09 14:56:15","187","<blockquote>
<p>Am I doing that right, as far as iterating through the Arraylist goes?</p>
</blockquote>
<p>No: by calling <code>iterator</code> twice in each iteration, you're getting new iterators all the time.</p>
<p>The easiest way to write this loop is using the <a href=""http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html"">for-each</a> construct:</p>
<pre><code>for (String s : arrayList)
if (s.equals(value))
// ...
</code></pre>
<p>As for</p>
<blockquote>
<p><code>java.lang.ArrayIndexOutOfBoundsException: -1</code></p>
</blockquote>
<p>You just tried to get element number <code>-1</code> from an array. Counting starts at zero.</p>
","687","6","1","5","2011-07-14 22:31:38","2","TRUE","172261","0"
"http://stackoverflow.com/users/1155474","http://stackoverflow.com/questions/9883113","http://stackoverflow.com/questions/9883113/#9883119","2014-01-07 21:00:41","30","14710","1","4","Java Switch Statement - Is ""or""/""and"" possible?","<p>I implemented a font system that finds out which letter to use via char switch statements. There are only capital letters in my font image. I need to make it so that, for example, 'a' and 'A' both have the same output. Instead of having 2x the amount of cases, could it be something like the following:</p>
<pre><code>char c;
switch(c){
case 'a' &amp; 'A': /*get the 'A' image*/; break;
case 'b' &amp; 'B': /*get the 'B' image*/; break;
...
case 'z' &amp; 'Z': /*get the 'Z' image*/; break;
}
</code></pre>
<p>Is this possible in java?</p>
","47","546","<java><char><switch-statement>","2012-03-27 03:44:49","TRUE","FALSE","9883119","2014-01-07 21:00:41","69","<p>You can use switch-case fall through by omitting the <code>break;</code> statement.</p>
<pre><code>char c = /* whatever */;
switch(c) {
case 'a':
case 'A':
//get the 'A' image;
break;
case 'b':
case 'B':
//get the 'B' image;
break;
// (...)
case 'z':
case 'Z':
//get the 'Z' image;
break;
}
</code></pre>
<p>...or you could just normalize to <a href=""http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#toLowerCase%28char%29"">lower case</a> or <a href=""http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#toUpperCase%28char%29"">upper case</a> before <code>switch</code>ing.</p>
<pre><code>char c = Character.toUpperCase(/* whatever */);
switch(c) {
case 'A':
//get the 'A' image;
break;
case 'B':
//get the 'B' image;
break;
// (...)
case 'Z':
//get the 'Z' image;
break;
}
</code></pre>
","964","2","2","3","2012-03-27 03:45:51","1","TRUE","169705","6"
"http://stackoverflow.com/users/527583","http://stackoverflow.com/questions/8053095","http://stackoverflow.com/questions/8053095/#8053125","2013-03-05 06:47:18","25","47098","14","7","What is the actual use of Class.forName(""oracle.jdbc.driver.OracleDriver"") while connecting to a DataBase?","<p>What will the command </p>
<pre><code>Class.forName(""oracle.jdbc.driver.OracleDriver"")
</code></pre>
<p>will exactly do while connecting to a Oracle database? Is there an alternate way of doing the same thing? </p>
<p>Thanks</p>
","106","235","<java><jdbc>","2011-11-08 15:44:49","TRUE","FALSE","8053125","2011-11-08 15:56:25","22","<p>It obtains a reference to the class object with the FQCN (fully qualified class name) <code>oracle.jdbc.driver.OracleDriver</code>.</p>
<p>It doesn't ""do"" anything in terms of connecting to a database, <em>aside from ensure that the specified class is loaded by the current classloader</em>. There is no fundamental difference between writing</p>
<pre><code>Class&lt;?&gt; driverClass = Class.forName(""oracle.jdbc.driver.OracleDriver"");
// and
Class&lt;?&gt; stringClass = Class.forName(""java.lang.String"");
</code></pre>
<p><code>Class.forName(""com.example.some.jdbc.driver"")</code> calls show up in <em>legacy</em> code that uses JDBC because <a href=""http://stackoverflow.com/questions/5484227/jdbc-class-forname-vs-drivermanager-registerdriver"">that is the <em>legacy</em> way of loading a JDBC driver</a>.</p>
<p>From <a href=""http://download.oracle.com/javase/tutorial/jdbc/basics/connecting.html#drivermanager"">The Java Tutorial</a>:</p>
<blockquote>
<p>In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method <code>Class.forName</code>. This methods required an object of type <code>java.sql.Driver</code>. Each JDBC driver contains one or more classes that implements the interface <code>java.sql.Driver</code>.<br>
...<br>
Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method <code>Class.forName</code>.)</p>
</blockquote>
<h3>Further reading <sub><sup>(read: questions this is a dup of)</sup></sub></h3>
<ul>
<li><a href=""http://stackoverflow.com/questions/1310494/what-purpose-does-class-forname-serve-if-you-dont-use-the-return-value"">What purpose does Class.forName() serve if you don&#39;t use the return value?</a></li>
<li><a href=""http://stackoverflow.com/questions/4202252/how-does-class-forname-work"">how does Class.forName() work</a></li>
<li><a href=""http://stackoverflow.com/questions/6740601/what-does-class-fornameorg-sqlite-jdbc-do"">What does &#39;Class.forName(&quot;org.sqlite.JDBC&quot;);&#39; do?</a></li>
<li><a href=""http://stackoverflow.com/questions/7662902/what-is-the-purpose-class-fornamemy-jdbc-driver"">What is the purpose &#39;Class.forName(&quot;MY_JDBC_DRIVER&quot;)&#39; ?</a></li>
<li><a href=""http://stackoverflow.com/questions/5992126/loading-jdbc-driver"">Loading JDBC driver </a></li>
</ul>
","2425","5","1","7","2011-11-08 15:46:47","2","TRUE","169705","0"
"http://stackoverflow.com/users/245549","http://stackoverflow.com/questions/4377842","http://stackoverflow.com/questions/4377842/#4377856","2012-05-10 18:47:58","19","55866","1","5","How can I convert integer into float in Java?","<p>I have two integers <code>x</code> and <code>y</code>. I need to calculate <code>x/y</code> and as outcome I would like to get float. For example as an outcome of <code>3/2</code> I would like to have 1.5. I thought that easiest (or the only) way to do it is to convert <code>x</code> and <code>y</code> into float type. Unfortunately, I cannot find an easy way to do it. Could you please help me with that?</p>
","45","415","<java><integer><floating-point>","2010-12-07 14:42:00","FALSE","FALSE","4377856","2012-05-10 18:47:58","41","<p>You just need to <strong>cast</strong> at least one of the operands to a float:</p>
<pre><code>float z = (float) x / y;
</code></pre>
<p>or</p>
<pre><code>float z = x / (float) y;
</code></pre>
<p>or (unnecessary)</p>
<pre><code>float z = (float) x / (float) y;
</code></pre>
","284","3","3","3","2010-12-07 14:43:30","1","TRUE","169705","3"
"http://stackoverflow.com/users/705414","http://stackoverflow.com/questions/8628365","http://stackoverflow.com/questions/8628365/#8628380","2014-02-21 06:49:40","12","7422","1","5","How to auto-complete main() in eclipse?","<p>I am using Eclipse Helios. I am wondering if there is anyway to add the <code>main()</code> method quickly in Eclipse?</p>
","39","126","<java><eclipse>","2011-12-25 05:31:27","FALSE","FALSE","8628380","2011-12-25 05:47:14","21","<p>Type</p>
<pre><code>main
</code></pre>
<p>then your content assist shortcut key.</p>
<p><img src=""http://i.stack.imgur.com/IcPEo.png"" alt=""enter image description here""></p>
<hr>
<blockquote>
<p>You can also add a main method from the class creation wizard. There's a checkbox to have it put in a main method for you. – <a href=""http://stackoverflow.com/users/557500/rfeak"">rfreak</a></p>
</blockquote>
","413","4","1","1","2011-12-25 05:37:23","6","TRUE","169705","0"
"http://stackoverflow.com/users/2618395","http://stackoverflow.com/questions/17908771","http://stackoverflow.com/questions/17908771/#17908795","2013-07-28 13:49:23","10","6680","3","1","How to get class annotation in java?","<p>I have created my own annotation type like this:</p>
<pre><code>public @interface NewAnnotationType {}
</code></pre>
<p>and attached it to a class:</p>
<pre><code>@NewAnnotationType
public class NewClass {
public void DoSomething() {}
}
</code></pre>
<p>and I tried to get the class annotation via reflection like this :</p>
<pre><code>Class newClass = NewClass.class;
for (Annotation annotation : newClass.getDeclaredAnnotations()) {
System.out.println(annotation.toString());
}
</code></pre>
<p>but it's not printing anything. What am I doing wrong?</p>
","36","574","<java><reflection><annotations>","2013-07-28 13:35:58","TRUE","FALSE","17908795","2013-07-28 13:47:39","16","<p>The default retention policy is <a href=""http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html#CLASS""><code>RetentionPolicy.CLASS</code></a> which means that, by default, annotation information is not retained at runtime:</p>
<blockquote>
<p>Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. This is the default behavior.</p>
</blockquote>
<p>Instead, use <a href=""http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html#RUNTIME""><code>RetentionPolicy.RUNTIME</code></a>:</p>
<blockquote>
<p>Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.</p>
</blockquote>
<p>...which you specify using the <a href=""http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html""><code>@Retention</code> meta-annotation</a>:</p>
<pre><code>@Retention(RetentionPolicy.RUNTIME)
public @interface NewAnnotationType {
}
</code></pre>
","1047","5","1","5","2013-07-28 13:39:37","4","TRUE","169705","0"
"http://stackoverflow.com/users/979256","http://stackoverflow.com/questions/7653813","http://stackoverflow.com/questions/7653813/#7653879","2013-08-20 18:18:22","10","9905","3","2","Jackson JSON: get node name from json-tree","<p>How can I recieve the node names from a JSON tree using Jackson?
The JSON-File looks something like this:</p>
<pre><code>{
node1 : ""value1"",
node2 : ""value2"",
node3 : {node3.1 : ""value3.1"",
node3.2 : ""value3.2""}
}
</code></pre>
<p>I have</p>
<pre><code>JsonNode rootNode = mapper.readTree(fileReader);
</code></pre>
<p>and need something like </p>
<pre><code>for (JsonNode node : rootNode){
if (node.getName().equals(""foo""){
//bar
}
}
</code></pre>
<p>thanks.</p>
","42","497","<java><json><jackson>","2011-10-04 20:45:27","TRUE","FALSE","7653879","2011-10-04 20:58:53","15","<p>The JSON terms for what you're calling the ""node name"" is, I think, the <strong>key.</strong> Since <a href=""http://jackson.codehaus.org/1.8.4/javadoc/org/codehaus/jackson/JsonNode.html#iterator%28%29""><code>JsonNode#iterator()</code></a>
does not include keys, you need to iterate <a href=""http://jackson.codehaus.org/1.8.4/javadoc/org/codehaus/jackson/JsonNode.html#getFields%28%29"">a bit differently</a>:</p>
<pre><code>for (Map.Entry&lt;String, JsonNode&gt; elt : rootNode.getFields()
{
if (""foo"".equals(elt.getKey())
{
// bar
}
}
</code></pre>
<p>If you <em>only</em> need to see the keys, you can simplify things a bit with <a href=""http://jackson.codehaus.org/1.8.4/javadoc/org/codehaus/jackson/JsonNode.html#getFieldNames%28%29""><code>JsonNode#getFieldNames()</code></a>:</p>
<pre><code>for (String key : rootNode.getFieldNames()
{
if (""foo"".equals(key)
{
// bar
}
}
</code></pre>
<hr>
<p>And if you just want to find the node with key <code>""foo""</code>, you can <a href=""http://jackson.codehaus.org/1.8.4/javadoc/org/codehaus/jackson/JsonNode.html#get%28java.lang.String%29"">access it directly</a>. This will yield better performance (constant-time lookup) and cleaner/clearer code than using a loop:</p>
<pre><code>JsonNode foo = rootNode.get(""foo"");
if (foo != null)
{
// frob that widget
}
</code></pre>
","1370","3","3","1","2011-10-04 20:52:14","7","TRUE","169705","0"
"http://stackoverflow.com/users/1267125","http://stackoverflow.com/questions/10178980","http://stackoverflow.com/questions/10178980/#10179008","2014-04-15 15:58:54","10","17697","3","4","How to convert a Binary String to a base 10 integer in Java","<p>I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:</p>
<pre><code>binary 1011 becomes integer 11
binary 1001 becomes integer 9
binary 11 becomes integer 3 etc.
</code></pre>
<p>What's the best way to proceed? I've been exploring java.lang.number.* without finding a direct conversion method. <code>Integer.parseInt(b)</code> yields an integer EQUAL to the String...e.g., 1001 becomes 1,001 instead of 9...and does not seem to include a parameter for an output base. <code>toBinaryString</code> does the conversion the wrong direction. I suspect I'll need to do a multistep conversion, but can't seem to find the right combination of methods or subclasses. I'm also not sure the extent to which leading zeros or lack thereof will be an issue. Anyone have any good directions to point me?</p>
","59","905","<java><string><binary><radix>","2012-04-16 17:45:39","TRUE","FALSE","10179008","2014-04-15 15:58:54","35","<p>You need to <a href=""http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29"">specify the radix</a>. There's an overload of <code>Integer#parseInt()</code> which allows you to.</p>
<pre><code>int foo = Integer.parseInt(""1001"", 2);
</code></pre>
","295","1","1","1","2012-04-16 17:47:23","2","TRUE","169705","0"
"http://stackoverflow.com/users/2084637","http://stackoverflow.com/questions/14944419","http://stackoverflow.com/questions/14944419/#14944513","2014-02-25 08:58:45","10","5667","2","2","Gson to HashMap","<p>Is there a way to convert a String containing json to a HashMap, where every key is a json-key and the value is the value of the json-key? The json has no nested values. I am using the Gson lib.</p>
<p>For example, given JSON:</p>
<pre><code>{
""id"":3,
""location"":""NewYork""
}
</code></pre>
<p>resulting HashMap:</p>
<pre><code>&lt;""id"", ""3""&gt;
&lt;""location"", ""NewYork""&gt;
</code></pre>
<p>Thanks</p>
","15","410","<java><android><gson>","2013-02-18 20:06:13","TRUE","FALSE","14944513","2013-02-18 20:15:28","24","<p>Use <a href=""http://google-gson.googlecode.com/svn/tags/1.1.1/docs/javadocs/com/google/gson/reflect/TypeToken.html""><code>TypeToken</code></a>, as per <a href=""https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Generic-Types"">the GSON FAQ</a>:</p>
<pre><code>Gson gson = new Gson();
Type stringStringMap = new TypeToken&lt;Map&lt;String, String&gt;&gt;(){}.getType();
Map&lt;String,String&gt; map = gson.fromJson(json, stringStringMap);
</code></pre>
<p>No casting. No unnecessary object creation.</p>
","541","2","1","3","2013-02-18 20:12:49","6","TRUE","169705","0"
"http://stackoverflow.com/users/1293653","http://stackoverflow.com/questions/9949020","http://stackoverflow.com/questions/9949020/#9949048","2012-03-30 19:14:13","9","1901","0","2","Iterate through multiple collections in the same ""for"" loop?","<p>I wonder if there's such a way to iterate thru multiple collections with the extended for each loop in java.</p>
<p>So something like:</p>
<pre><code>for (Object element : collection1, collection2, ....)
// do something ...
</code></pre>
<p>Thanks</p>
","60","267","<java><syntax><for-loop><iterator>","2012-03-30 19:04:27","TRUE","FALSE","9949048","2012-03-30 19:14:13","16","<p>You can do exactly this with <a href=""http://code.google.com/p/guava-libraries/"">Guava</a>'s <a href=""http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html#concat%28java.lang.Iterable...%29""><code>Iterables.concat()</code></a>:</p>
<pre><code>for (Foo element : Iterables.concat(collection1, collection2)) {
foo.frob();
}
</code></pre>
","386","1","1","1","2012-03-30 19:06:35","2","TRUE","169705","0"
"http://stackoverflow.com/users/514744","http://stackoverflow.com/questions/4252187","http://stackoverflow.com/questions/4252187/#4252197","2013-04-13 16:23:36","8","22142","5","5","How to stop execution after a certain time in Java?","<p>In the code, the variable timer would specify the duration after which to end the while loop, 60 sec for example.</p>
<pre><code> while(timer) {
//run
//terminate after 60 sec
}
</code></pre>
","51","209","<java><time>","2010-11-23 02:25:44","TRUE","FALSE","4252197","2013-04-13 16:23:36","17","<pre><code>long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() &lt; end)
{
// run
}
</code></pre>
","181","0","1","10","2010-11-23 02:28:22","3","TRUE","169705","0"
"http://stackoverflow.com/users/383986","http://stackoverflow.com/questions/5488212","http://stackoverflow.com/questions/5488212/#5488222","2011-03-30 15:19:20","4","3675","2","6","Should I declare/Initialize ArrayLists as Lists, ArrayLists, or ArrayLists of <Cat>","<p>What is the difference in declaring a collection as such</p>
<pre><code>public class CatHerder{
private List cats;
public CatHerder(){
this.cats = new ArrayList&lt;Cat&gt;();
}
}
//or
public class CatHerder{
private ArrayList cats;
public CatHerder(){
this.cats = new ArrayList();
}
}
//or
public class CatHerder{
private ArrayList&lt;Cat&gt; cats;
public CatHerder(){
this.cats = new ArrayList&lt;Cat&gt;();
}
}
</code></pre>
","83","491","<java><list><collections><arraylist>","2011-03-30 15:10:31","TRUE","FALSE","5488222","2011-03-30 15:16:39","15","<p>You should declare it as a <code>List&lt;Cat&gt;</code>, and initialize it as an <code>ArrayList&lt;Cat&gt;</code>.</p>
<p><a href=""http://download.oracle.com/javase/6/docs/api/java/util/List.html""><code>List</code></a> is an interface, and <a href=""http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html""><code>ArrayList</code></a> is an implementing class. It's almost always preferable to code against the interface and not the implementation. This way, if you need to change the implementation later, it won't break consumers who code against the interface.</p>
<p>Depending on how you actually use the list, you might even be able to use the less-specific <a href=""http://download.oracle.com/javase/6/docs/api/java/util/Collection.html""><code>java.util.Collection</code></a> (an interface which <code>List</code> extends).</p>
<p>As for <code>List&lt;Cat&gt;</code> (you can read that as ""list of cat"") vs <code>List</code>: that's Java's <a href=""http://download.oracle.com/javase/tutorial/java/generics/index.html"">generics</a>, which ensure compile-time type safely. In short, it lets the compiler make sure that the <code>List</code> only contains <code>Cat</code> objects.</p>
<hr>
<pre><code>public class CatHerder{
private final List&lt;Cat&gt; cats;
public CatHerder(){
this.cats = new ArrayList&lt;Cat&gt;();
}
}
</code></pre>
","1384","4","1","2","2011-03-30 15:11:23","1","TRUE","169705","0"
"http://stackoverflow.com/users/479180","http://stackoverflow.com/questions/6045943","http://stackoverflow.com/questions/6045943/#6046027","2011-05-19 01:58:08","3","7035","0","4","adding a key to HashMap without the value?","<p>Is there a way to add a key to a HashMap without also adding a value? I know it seems strange, but I have a <code>HashMap&lt;String, ArrayList&lt;Object&gt;&gt;</code> amd I want to first be able to create keys as needed and then check if a certain key exists and, if so, put the appropriate value, namely the <code>ArrayList&lt;Object&gt;</code></p>
<p>Was that confusing enough?</p>
","42","389","<java><collections><guava>","2011-05-18 13:59:49","FALSE","FALSE","6046027","2011-05-18 14:11:26","16","<p>Since you're using a <code>Map&lt;String, List&lt;Object&gt;&gt;</code>, you're <strong><em>really</em></strong> looking for a <a href=""http://en.wikipedia.org/wiki/Multimap"">multimap</a>. I highly recommend using a third-party library such as Google Guava for this - see <a href=""http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimaps.html"">Guava's <code>Multimaps</code></a>.</p>
<pre><code>Multimap&lt;String, Object&gt; myMultimap = ArrayListMultimap.create();
// fill it
myMultimap.put(""hello"", ""hola"");
myMultimap.put(""hello"", ""buongiorno"");
myMultimap.put(""hello"", ""สวัสดี"");
// retrieve
List&lt;String&gt; greetings = myMultimap.get(""hello"");
// [""hola"", ""buongiorno"", ""สวัสดี""]
</code></pre>
","766","1","1","1","2011-05-18 14:04:23","5","TRUE","169705","0"
"http://stackoverflow.com/users/3150","http://stackoverflow.com/questions/137212","http://stackoverflow.com/questions/137212/#137288","2014-04-09 18:57:56","58","39836","30","12","How to solve performance problem with Java SecureRandom?","<p>If you want a cryptographically strong random number in Java, you use SecureRandom. Unfortunately, SecureRandom can be very slow. If it uses /dev/random on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the peformance penalty?</p>
<p>Has anyone used <a href=""https://uncommons-maths.dev.java.net/"">Uncommon Maths</a> as a solution to this problem?</p>
<p>Can anybody confirm that this performance problem has been solved in JDK 6?</p>
","56","474","<java><performance><security><random><entropy>","2008-09-26 01:07:04","FALSE","FALSE","137288","2009-11-14 04:18:57","29","<p>If you want true random data, then unfortunately you have to wait for it. This includes the seed for a SecureRandom PRNG. Uncommon Maths can't gather true random data any faster than SecureRandom, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than /dev/random where that's available.</p>
<p>If you want a PRNG, do something like this:</p>
<pre><code>SecureRandom.getInstance(""SHA1PRNG"");
</code></pre>
<p>What strings are supported depends on the SecureRandom SPI provider, but you can enumerate them using Security.getProviders() and Provider.getService().</p>
<p>Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.</p>
<p>The exception is that if you don't call setSeed() before getting data, then the PRNG will seed itself once the first time you call next() or nextBytes(). It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of ""hash the current time together with the PID, add 27, and hope for the best"". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.</p>
","1460","5","1","4","2008-09-26 01:39:13","32","TRUE","169072","0"
"http://stackoverflow.com/users/4249","http://stackoverflow.com/questions/133988","http://stackoverflow.com/questions/133988/#134014","2013-08-22 19:34:17","13","10111","5","11","Problem with synchronizing on String objects?","<p>I have a webapp that I am in the middle of doing some load/performance testing on, particularily on a feature where we expect a few hundred users to be accessing the same page and hitting refresh about every 10 seconds on this page. One area of improvement that we found we could make with this function was to cache the responses from the web service for some period of time, since the data is not changing.</p>
<p>After implementing this basic caching, in some further testing I found out that I didn't consider how concurrent threads could access the Cache at the same time. I found that within the matter of ~100ms, about 50 threads were trying to fetch the object from the Cache, finding that it had expired, hitting the web service to fetch the data, and then putting the object back in the cache.</p>
<p>The original code looked something like this:</p>
<pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {
final String key = ""Data-"" + email;
SomeData[] data = (SomeData[]) StaticCache.get(key);
if (data == null) {
data = service.getSomeDataForEmail(email);
StaticCache.set(key, data, CACHE_TIME);
}
else {
logger.debug(""getSomeDataForEmail: using cached object"");
}
return data;
}
</code></pre>
<p>So, to make sure that only one thread was calling the web service when the object at <code>key</code> expired, I thought I needed to synchronize the Cache get/set operation, and it seemed like using the cache key would be a good candidate for an object to synchronize on (this way, calls to this method for email b@b.com would not be blocked by method calls to a@a.com).</p>
<p>I updated the method to look like this:</p>
<pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {
SomeData[] data = null;
final String key = ""Data-"" + email;
synchronized(key) {
data =(SomeData[]) StaticCache.get(key);
if (data == null) {
data = service.getSomeDataForEmail(email);
StaticCache.set(key, data, CACHE_TIME);
}
else {
logger.debug(""getSomeDataForEmail: using cached object"");
}
}
return data;
}
</code></pre>
<p>I also added logging lines for things like ""before synchronization block"", ""inside synchronization block"", ""about to leave synchronization block"", and ""after synchronization block"", so I could determine if I was effectively synchronizing the get/set operation.</p>
<p>However it doesn't seem like this has worked. My test logs have output like:</p>
<blockquote>
<p>(log output is 'threadname' 'logger name' 'message')<br />
http-80-Processor253 jsp.view-page - getSomeDataForEmail: about to enter synchronization block<br />
http-80-Processor253 jsp.view-page - getSomeDataForEmail: inside synchronization block<br />
http-80-Processor253 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired<br />
http-80-Processor253 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]<br />
http-80-Processor263 jsp.view-page - getSomeDataForEmail: about to enter synchronization block<br />
http-80-Processor263 jsp.view-page - getSomeDataForEmail: inside synchronization block<br />
http-80-Processor263 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired<br />
http-80-Processor263 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]<br />
http-80-Processor131 jsp.view-page - getSomeDataForEmail: about to enter synchronization block<br />
http-80-Processor131 jsp.view-page - getSomeDataForEmail: inside synchronization block<br />
http-80-Processor131 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired<br />
http-80-Processor131 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]<br />
http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block<br />
http-80-Processor104 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired<br />
http-80-Processor104 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null]<br />
http-80-Processor252 jsp.view-page - getSomeDataForEmail: about to enter synchronization block<br />
http-80-Processor283 jsp.view-page - getSomeDataForEmail: about to enter synchronization block<br />
http-80-Processor2 jsp.view-page - getSomeDataForEmail: about to enter synchronization block<br />
http-80-Processor2 jsp.view-page - getSomeDataForEmail: inside synchronization block </p>
</blockquote>
<p>I wanted to see only one thread at a time entering/exiting the synchronization block around the get/set operations.</p>
<p>Is there an issue in synchronizing on String objects? I thought the cache-key would be a good choice as it is unique to the operation, and even though the <code>final String key</code> is declared within the method, I was thinking that each thread would be getting a reference to <em>the same object</em> and therefore would synchronization on this single object.</p>
<p>What am I doing wrong here?</p>
<p><strong>Update</strong>: after looking further at the logs, it seems like methods with the same synchronization logic where the key is always the same, such as </p>
<pre><code>final String key = ""blah"";
...
synchronized(key) { ...
</code></pre>
<p>do not exhibit the same concurrency problem - only one thread at a time is entering the block.</p>
<p><strong>Update 2</strong>: Thanks to everyone for the help! I accepted the first answer about <code>intern()</code>ing Strings, which solved my initial problem - where multiple threads were entering synchronized blocks where I thought they shouldn't, because the <code>key</code>'s had the same value.</p>
<p>As others have pointed out, using <code>intern()</code> for such a purpose and synchronizing on those Strings does indeed turn out to be a bad idea - when running JMeter tests against the webapp to simulate the expected load, I saw the used heap size grow to almost 1GB in just under 20 minutes.</p>
<p>Currently I'm using the simple solution of just synchronizing the entire method - but I <strong>really</strong> like the code samples provided by martinprobst and MBCook, but since I have about 7 similar <code>getData()</code> methods in this class currently (since it needs about 7 different pieces of data from a web service), I didn't want to add almost-duplicate logic about getting and releasing locks to each method. But this is definitely very, very valuable info for future usage. I think these are ultimately the correct answers on how best to make an operation like this thread-safe, and I'd give out more votes to these answers if I could!</p>
","45","6733","<java><multithreading><synchronization>","2008-09-25 15:27:07","TRUE","TRUE","134014","2008-09-26 12:37:48","21","<p>Without putting my brain fully into gear, from a quick scan of what you say it looks as though you need to intern() your Strings:</p>
<pre><code>final String firstkey = ""Data-"" + email;
final String key = firstkey.intern();
</code></pre>
<p>Two Strings with the same value are otherwise not necessarily the same object.</p>
<p>Note that this may introduce a new point of contention, since deep in the VM, intern() may have to acquire a lock. I have no idea what modern VMs look like in this area, but one hopes they are fiendishly optimised.</p>
<p>I assume you know that StaticCache still needs to be thread-safe. But the contention there should be tiny compared with what you'd have if you were locking on the cache rather than just the key while calling getSomeDataForEmail.</p>
<p><strong>Response to question update</strong>:</p>
<p>I think that's because a string literal always yields the same object. Dave Costa points out in a comment that it's even better than that: a literal always yields the canonical representation. So all String literals with the same value anywhere in the program would yield the same object.</p>
<p><strong>Edit</strong></p>
<p>Others have pointed out that <strong>synchronizing on intern strings is actually a really bad idea</strong> - partly because creating intern strings is permitted to cause them to exist in perpetuity, and partly because if more than one bit of code anywhere in your program synchronizes on intern strings, you have dependencies between those bits of code, and preventing deadlocks or other bugs may be impossible.</p>
<p>Strategies to avoid this by storing a lock object per key string are being developed in other answers as I type.</p>
<p>Here's an alternative - it still uses a singular lock, but we know we're going to need one of those for the cache anyway, and you were talking about 50 threads, not 5000, so that may not be fatal. I'm also assuming that the performance bottleneck here is slow blocking I/O in DoSlowThing() which will therefore hugely benefit from not being serialised. If that's not the bottleneck, then:</p>
<ul>
<li>If the CPU is busy then this approach may not be sufficient and you need another approach.</li>
<li>If the CPU is not busy, and access to server is not a bottleneck, then this approach is overkill, and you might as well forget both this and per-key locking, put a big synchronized(StaticCache) around the whole operation, and do it the easy way.</li>
</ul>
<p>Obviously this approach needs to be soak tested for scalability before use -- I guarantee nothing.</p>
<p>This code does NOT require that StaticCache is synchronized or otherwise thread-safe. That needs to be revisited if any other code (for example scheduled clean-up of old data) ever touches the cache.</p>
<p>IN_PROGRESS is a dummy value - not exactly clean, but the code's simple and it saves having two hashtables. It doesn't handle InterruptedException because I don't know what your app wants to do in that case. Also, if DoSlowThing() consistently fails for a given key this code as it stands is not exactly elegant, since every thread through will retry it. Since I don't know what the failure criteria are, and whether they are liable to be temporary or permanent, I don't handle this either, I just make sure threads don't block forever. In practice you may want to put a data value in the cache which indicates 'not available', perhaps with a reason, and a timeout for when to retry.</p>
<pre><code>// do not attempt double-check locking here. I mean it.
synchronized(StaticObject) {
data = StaticCache.get(key);
while (data == IN_PROGRESS) {
// another thread is getting the data
StaticObject.wait();
data = StaticCache.get(key);
}
if (data == null) {
// we must get the data
StaticCache.put(key, IN_PROGRESS, TIME_MAX_VALUE);
}
}
if (data == null) {
// we must get the data
try {
data = server.DoSlowThing(key);
} finally {
synchronized(StaticObject) {
// WARNING: failure here is fatal, and must be allowed to terminate
// the app or else waiters will be left forever. Choose a suitable
// collection type in which replacing the value for a key is guaranteed.
StaticCache.put(key, data, CURRENT_TIME);
StaticObject.notifyAll();
}
}
}
</code></pre>
<p>Every time anything is added to the cache, all threads wake up and check the cache (no matter what key they're after), so it's possible to get better performance with less contentious algorithms. However, much of that work will take place during your copious idle CPU time blocking on I/O, so it may not be a problem.</p>
<p>This code could be commoned-up for use with multiple caches, if you define suitable abstractions for the cache and its associated lock, the data it returns, the IN_PROGRESS dummy, and the slow operation to perform. Rolling the whole thing into a method on the cache might not be a bad idea.</p>
","5032","15","2","7","2008-09-25 15:30:41","3","TRUE","169072","0"
"http://stackoverflow.com/users/384108","http://stackoverflow.com/questions/4234027","http://stackoverflow.com/questions/4234027/#4234143","2010-11-21 00:06:57","6","807","3","7","Given an array with multiple repeated entries, fnd one repeated entry O(N) time and constant space","<p>We have been given an array of size N that contains integers in the range 0 to N-2, both inclusive. </p>
<p>The array can have multiple repeated entries. We need to find one of the duplicated entries in O(N) time and constant space. </p>
<p>I was thinking of taking the product and sum of all the entires in the array, and the product and sum of all the numbers in the range 0 to N-2. </p>
<p>Then, the difference of the sums and the division of the products would give us two equations. This approach would work if it were given that there are only two repeated entries, but since there can be more than two, I think my approach fails.</p>
<p>Any suggestions? </p>
<p>Edit: The array is immutable. I realize that this is an important piece of information and I apologize that I forgot to include this earlier. </p>
","98","824","<java><arrays><algorithm>","2010-11-20 17:30:52","FALSE","FALSE","4234143","2010-11-21 00:06:57","7","<p>Here's a nice treatment. It passes through some easier problems before addressing this one.</p>
<p><a href=""http://aperiodic.net/phil/archives/Geekery/find-duplicate-elements.html"" rel=""nofollow"">http://aperiodic.net/phil/archives/Geekery/find-duplicate-elements.html</a></p>
<p>It contains a solution for when you can modify the input array, and another for when you can't.</p>
<p>Brief summary in case the link ever dies: the array indexes run from 0 .. N-1, and the array values run 0 .. N-2. Each array element can therefore be considered as an index (or ""pointer"") into the array itself: element <code>i</code> ""points to"" element <code>ra[i]</code>, <code>ra[i]</code> points to <code>ra[ra[i]]</code> and so on. By repeatedly following these pointers, me must eventually enter a cycle, because we certainly can't go forever without revisiting some node or other.</p>
<p>Now, the very last element, N-1, isn't pointed to by any other element. So if we start there and eventually enter a cycle, somewhere along the way there must be an element which can be reached from two different places: the route we took the first time, and the route which is part of the cycle. Something like this:</p>
<pre><code> N-1 -&gt; a1 -&gt; a2 -&gt; a3
^ \
/ v
a6 &lt;- a5 &lt;- a4
</code></pre>
<p>In this case, a2 is reachable from two different places.</p>
<p>But a node which is reachable from two different places is precisely what we're looking for, a duplicate in the array (two different array elements containing the same value).</p>
<p>The question then is how to identify a2, and the answer is to use <a href=""http://en.wikipedia.org/wiki/Cycle_detection"" rel=""nofollow"">Floyd's cycle-finding algorithm</a>. In particular it tells us the ""start"" of the loop in O(N) time and O(1) space.</p>
","1857","8","1","5","2010-11-20 17:59:00","29","TRUE","169072","0"
"http://stackoverflow.com/users/155695","http://stackoverflow.com/questions/5634237","http://stackoverflow.com/questions/5634237/#5634296","2011-04-12 11:38:26","3","367","0","2","What is a good algorithm for mapping random (barcode values) numbers to an String in a collection?","<p>Say that my application has a finite number of ""stuff"", in my case they will be items in my game but for the purposes of this question I'll use Strings.</p>
<p>Say I have 5 Strings : </p>
<ol>
<li>James</li>
<li>Dave</li>
<li>John</li>
<li>Steve</li>
<li>Jack</li>
</ol>
<p>There will be a set list of them, however I will increase that list in the future.</p>
<p><strong>Question</strong> : What is a good algorithm I can use, to go from a random number (generated from a barcode) into one of those values from above?</p>
<p>For example, if I have the value 4523542354254, then what algorithm could I use to map that onto <code>Dave</code>? If I have that same number again, I need to make sure it maps to <code>Dave</code> and not to something else each time.</p>
<p>One option I did consider was taking the last digit of the barcode and using the <code>0-9</code> that would map onto 10 items, but its not very future proof if I added an 11th item.</p>
<p>Any suggestions?</p>
","98","990","<java><algorithm><barcode>","2011-04-12 11:11:17","FALSE","FALSE","5634296","2011-04-12 11:38:26","4","<p>With the clarification that ""If I have that same number again, I need to make sure it maps to Dave and not to something else each time."" only applies as long as the set of strings doesn't change.</p>
<p>Simplest is what Maverik says, <code>name = names[barcode % names.length];</code></p>
<p>A Java <code>long</code> is big enough to store any UPC barcode, <code>int</code> isn't, so I assume here <code>barcode</code> is a <code>long</code>. Note that the last digit of a UPC barcode is base-11, it can be <code>X</code>. I leave it as an exercise for the reader how you actually map barcodes to numbers. One option is just discard the check digit once you've established that it's correct - it's computed from the others, so it doesn't add any information or discriminate between any otherwise-equal codes.</p>
<p>But as Stephen C says, barcodes aren't random, so this might not give you a uniform distribution across the names.</p>
<p>To get a better distribution, you could first hash the barcode. For example <code>name = names[String.valueOf(barcode).hashCode() % names.length];</code></p>
<p>This still might not be entirely uniform -- there are better but usually slower hash functions than <code>String.hashCode</code> -- but it probably avoids any major biases that there may be in real-life barcodes.</p>
<p>Also, I can't remember whether the Java modulus operator returns negative results for negative input - if so then you need to coerce it into a positive range:</p>
<pre><code>int idx = String.valueOf(barcode).hashCode() % names.length;
if (idx &lt; 0) idx += names.length;
</code></pre>
","1615","7","1","2","2011-04-12 11:17:19","6","TRUE","169072","0"
"http://stackoverflow.com/users/1816025","http://stackoverflow.com/questions/15460199","http://stackoverflow.com/questions/15460199/#15460368","2013-03-17 11:58:36","0","187","0","3","Post-Increment in Returns: How are They Implemented?","<p>So, I know that many C-style languages have decrement (<code>--</code>) and increment (<code>++</code>) operators, and allow the mutation to happen before or after the whole expression is evaluated.</p>
<p>What happens when a post-increment happens on a return? I'm not asking in terms of behaviour, but rather implementation.</p>
<p>Given a virtual machine (e.g. JavaScript/JVM) or physical machine (e.g. compiled C++), are the generated opcodes something like the following? (Assuming stack-based arguments/returns.)</p>
<pre><code>int x = 4, y = 8;
return f(++a) + y++;
</code></pre>
<p>Turns into this: (Maybe?)</p>
<pre><code>LOAD 4 A
LOAD 8 B
INC A
PUSH A
CALL F
POP INTO C
ADD C BY B
INC B
RET C
</code></pre>
<p>If so, how do such operations in these languages decide where to embed the incrementation when the expression becomes complex, perhaps even a little Lispish?</p>
","52","892","<java><c++><return><increment><evaluation>","2013-03-17 11:22:48","TRUE","FALSE","15460368","2013-03-17 11:58:36","2","<p>Once the code has been optimized (either by a C++ compiler or by a JIT), I would expect something similar to the following:</p>
<p>Source:</p>
<pre><code>int x = 4, y = 8;
return f(++x) + y++;
</code></pre>
<p>Instructions:</p>
<pre><code>PUSH 5
CALL f
POP INTO A
ADD 8 to A
RET A
</code></pre>
<p>The instructions I've listed are correct (unless I've made some silly error), and they only require code transformations that I know optimizers to be capable of making. Basically, unused results are not calculated and operations with known results are computed at optimization time.</p>
<p>It's quite possible that on a particular architecture there's a more efficient way to do it, though, in which case there's a good chance that the optimizer will know about it and use it. Optimizers often beat my expectations, since I'm not an expert assembly programmer. In this case, it's quite likely that the calling convention dictates the same location for the return value in the case of function <code>f</code> and this code. So there might be no need for any POP -- the return register/stack location can just have 8 added to it. Furthermore, if the function <code>f</code> is inlined then optimization will be applied <em>after</em> inlining.</p>
<p>So for example if <code>f</code> returns <code>input * 2</code> then the whole function might optimize to:</p>
<pre><code>RET 18
</code></pre>
","1401","6","3","3","2013-03-17 11:42:50","20","TRUE","169072","0"
"http://stackoverflow.com/users/274117","http://stackoverflow.com/questions/3681798","http://stackoverflow.com/questions/3681798/#3681856","2012-07-08 01:09:07","0","710","0","5","How to optimize my current getMax method to retrieve the highest number in an array?","<p>What would be the best way to optimize this code below to make it more efficient while applying the 'best practices'. This is just a simple school project and it works, I've tested it. But I just feel like there's a better and more efficient way to write this method. What do you think?</p>
<ol>
<li>I have an array that
is pre-populated with a bunch of
numbers. The <code>getMax()</code> method
retrieves the highest number in the
array. But if the array is empty it
returns <code>-1</code>.</li>
<li><p>nElems is simply a variable that keep tracks of how many elements are present in the array.</p></li>
<li><p><code>array</code> is the private array declared at the beginning of the class.</p>
<pre><code>public int getMax() {
int k = 0;
int max = array[0];
for(int j=0; j&lt;nElems; j++) {
if(max &lt; array[j])
max = array[j];
}
if(k == nElems)
return -1;
else return max;
} // end of method
</code></pre></li>
</ol>
<p>Oh and what should I name my k variable to make it more readable? Its purpose is to be 0, so it could be checked against the number of elements in an array to return either -1 or highest number;</p>
<p><em>Assume all array values are positive.</em></p>
","84","1205","<java><algorithm><optimization><search>","2010-09-10 01:44:24","TRUE","FALSE","3681856","2010-09-10 02:57:12","3","<blockquote>
<p>Its purpose is to be 0, so it could be
checked against the number of elements
in an array to return either -1 or
highest number;</p>
</blockquote>
<p>Zero doesn't need a name - if you mean 0, use the literal <code>0</code>.</p>
<p>Your loop is fine. There are things you could do to try to optimise it, but they won't necessarily help. Almost always you may as well just leave such localised, ""keyhole"" optimisation to the JIT. If you just want to try a few things as a learning exercise, then you could experiment as follows:</p>
<ul>
<li>rather than using the array twice, set a variable to the array value, then use it twice.</li>
<li><a href=""http://stackoverflow.com/questions/2349211/when-if-ever-is-loop-unrolling-still-useful"">unroll the loop</a> by different amounts. Be careful not to make the error of accessing the wrong indices if <code>numElem</code> isn't a multiple of the number of times you're unrolling.</li>
<li>work backwards through the array instead of forwards</li>
<li>return immediately if you encounter a value of <code>Integer.MAX_VALUE</code>. You aren't going to find anything bigger. It's difficult to define the performance effect of this, since it will speed it up for large arrays with a MAX_VALUE that isn't too near the end, but most likely slow it down for everything else. It might be interesting to see how much difference it makes, though.</li>
<li>anything else you can think of.</li>
</ul>
<p>I'm not saying any of these will make a difference, faster or slower, but they could. So run them and time how fast each goes. What you'll most likely learn, is that compared with leaving it to the JIT this stuff isn't worth your time. But you never know ;-)</p>
<p>The surrounding code can be cleaned up, though, to make it more comprehensible rather than to make it faster. For example:</p>
<pre><code>public int getMax() {
int max = -1;
if (nElems &gt; 0) {
max = array[0];
for(int j=1; j&lt;nElems; j++) {
if(max &lt; array[j])
max = array[j];
}
}
return max;
}
</code></pre>
<p>This also removes the error in your code, that if the array is size 0, then you access out of bounds in the second line. ColinD's way of doing that is just as good, I'm showing something different for the sake of variety.</p>
<p>Here's the shorter code assuming all values are non-negative:</p>
<pre><code>public int getMax() {
int max = -1;
for(int j=0; j&lt;nElems; j++) {
if(max &lt; array[j])
max = array[j];
}
return max;
}
</code></pre>
","2598","7","2","6","2010-09-10 02:01:38","17","TRUE","169072","0"
"http://stackoverflow.com/users/705773","http://stackoverflow.com/questions/7369493","http://stackoverflow.com/questions/7369493/#7369502","2013-01-26 18:50:18","5","4832","0","6","Integer to byte casting in Java","<p>In Java we can do </p>
<pre><code>byte b = 5;
</code></pre>
<p>But why can't we pass same argument to a function which accepts <code>byte</code></p>
<pre><code>myObject.testByte(5);
public void testByte (byte b)
{
System.out.println(""Its byte"");
}
</code></pre>
<p>It gives following error </p>
<pre><code>The method testByte(byte) in the type Apple is not applicable for the arguments (int)
</code></pre>
<p>PS: May be a silly question, I think I need to revise my basics again. </p>
<p>Thanks.</p>
","31","523","<java>","2011-09-10 03:50:57","TRUE","FALSE","7369502","2013-01-26 18:50:18","5","<p>Hard-coded initializer values are somewhat special in Java - they're assumed to have a coercion to the type of the variable you're initializing. Essentially, that first bit of code effectively looks like this:</p>
<pre><code>byte b = (byte) 5;
</code></pre>
<p>If you did this...</p>
<pre><code>myObject.testByte((byte) 5);
</code></pre>
<p>...you wouldn't get that error, but if you don't do that, then the <code>5</code> is created by default as an <code>int</code>, and not automatically coerced.</p>
","511","3","2","3","2011-09-10 03:54:32","4","TRUE","166257","0"
"http://stackoverflow.com/users/1344109","http://stackoverflow.com/questions/11332772","http://stackoverflow.com/questions/11332772/#11332792","2012-07-04 16:38:26","5","5610","0","2","java string split on all non-alphanumeric except apostrophes","<p>So I want to split a string in java on any non-alphanumeric characters. </p>
<p>Currently I have been doing it like this</p>
<pre><code>words= Str.split(""\\W+"");
</code></pre>
<p>However I want to keep apostrophes(""'"") in there. Is there any regular expression to preserve apostrophes but kick the rest of the junk? Thanks. </p>
","60","339","<java><regex>","2012-07-04 16:34:13","TRUE","FALSE","11332792","2012-07-04 16:38:26","15","<pre><code>words = Str.split(""[^\w']+"");
</code></pre>
<p>Just add it to the character class. <code>\W</code> is equivaelent to <code>[^\w]</code>, which you can then add <code>'</code> to.</p>
<p>Do note, however, that <code>\w</code> also actually includes underscores. If you want to split on underscores as well, you should be using <code>[^a-zA-Z0-9']</code> instead.</p>
","379","2","1","3","2012-07-04 16:35:47","1","TRUE","166257","0"
"http://stackoverflow.com/users/384706","http://stackoverflow.com/questions/3869570","http://stackoverflow.com/questions/3869570/#3869589","2010-10-08 16:12:07","4","1817","2","6","java vs C++ pass by reference","<p><br>
I am confused in the following:<br>
In C++ we can pass a parameter to a function by reference (having declared it as a pointer or reference variable) and if we modify it inside the function, the changes are reflected to the caller when the function returns.<br>
This is not happening in java and I am not sure I understand why.</p>
<p>E.g. this is a method from an object X</p>
<pre><code>public boolean aMethod(int id, myClass aClass)
{
//do some logic
aClass = new MyClass();
//configure argument object aClass
return true;
}
</code></pre>
<p>In the <strong>calling code</strong>: </p>
<pre><code>//some code processing
myClass obj = null;
if(X.aMethod(2,obj))
{
obj.methodA();//start using the object
}
</code></pre>
<p>I use it in C++, i.e. to return a result that notifies that the function parameter can be used, but in java this does not work.<br>
I enter the if(X.aMethod(2,obj)) branch but the obj is null. Why is it null?<br>
Haven't I assigned a memory address from the heap using new inside the method aMethod(int id, myClass aClass)? Am I not passing the ""address"" of obj in the function?
I was expecting to have the obj properly constructed and usable in the calling code. Have I misunderstood something concerning memory in java?</p>
","29","1278","<java><c++><function><pass-by-reference>","2010-10-06 04:52:23","TRUE","FALSE","3869589","2010-10-06 05:34:42","21","<p>Java passes everything by value - <em>including references</em>.</p>
<p>What this means is that if you pass an object, you can modify <em>properties</em> of that object, and they will persist after you return, but you can't <em>replace</em> the object in its entirety with a completely new object, because you can't actually modify the <em>reference</em> - only what the reference points to.</p>
<p>Before your <code>aClass =</code> line:</p>
<pre><code>Outside the function:
obj ---&gt; &lt;foo&gt;
Inside the function:
aClass ---&gt; &lt;foo&gt;
</code></pre>
<p>After your <code>aClass =</code> line:</p>
<pre><code>Inside the function:
aClass ---&gt; &lt;bar&gt;
Outside the function:
obj ---&gt; &lt;foo&gt;
</code></pre>
<p>The key thing to notice here is that <code>aClass</code> doesn't point to <code>obj</code> - it points to <code>&lt;foo&gt;</code>. You're not passing the address of <code>obj</code>, you're passing <em>the address of what <code>obj</code> points to</em>. Thus, when you change what <code>aClass</code> points to, that doesn't touch <code>obj</code>.</p>
<hr>
<p>As an alternative way of thinking about it:</p>
<p>In Java,</p>
<pre><code>Bar foo = new Bar();
</code></pre>
<p>is equivalent to C++,</p>
<pre><code>Bar *foo = new Bar();
</code></pre>
<p>Thus when you pass <code>foo</code> to a function, you're not passing the address of <code>foo</code> - you're passing the address of the allocated object. Java doesn't have the <code>&amp;</code>-operator style pass-by-reference that C/C++ do.</p>
","1569","9","4","2","2010-10-06 04:57:20","5","TRUE","166257","0"
"http://stackoverflow.com/users/157027","http://stackoverflow.com/questions/2652932","http://stackoverflow.com/questions/2652932/#2652950","2014-04-17 12:13:48","4","4658","0","5","Problem in java.util.Set.addAll() method","<p>I have a <code>java.util.Set&lt;City&gt; cities</code> and I need to add cities to this set in 2 ways:</p>
<ul>
<li><p>By adding individual city (with the help of <code>cities.add(city)</code> method call)</p></li>
<li><p>By adding another set of cities to this set (with the help of <code>cities.addAll(anotherCitiesSet)</code> method call)</p></li>
</ul>
<p>But the problem in second approach is that i don't know whether there were any duplicate cities in the <code>anotherCitiesSet</code>.</p>
<p>I want to do some processing whenever a duplicate entry is tried to be entered in the<code>cities</code> set.</p>
","40","621","<java><set>","2010-04-16 12:36:48","FALSE","FALSE","2652950","2014-04-17 12:13:48","8","<p>Copy the <code>cities</code> set (to say, <code>citiesCopy</code>), and then call <code>citiesCopy.retainAll(anotherCitiesSet)</code> - the resulting set in <code>citiesCopy</code> will contain the intersection of the two sets, thus allowing you to easily see which cities are duplicated, if any.</p>
<p>Alternatively, loop through the second set and manually add each of the elements, checking the return value from <code>add()</code> each time:</p>
<pre><code>for(java.util.Set&lt;City&gt; c : anotherCitiesSet) {
if(!cities.add(c)) {
// c was a duplicate, do something?
}
}
</code></pre>
","612","2","1","1","2010-04-16 12:39:52","3","TRUE","166257","0"
"http://stackoverflow.com/users/401881","http://stackoverflow.com/questions/3331865","http://stackoverflow.com/questions/3331865/#3331873","2012-07-16 03:43:15","3","461","0","5","Which regular expression to find a string not containing a substring?","<p>I am working on a simple tool to check Java coding guidelines on a project.
One of those guidelines is to verify that there is no variable declared like ""private static ..."", only ""private static final ..."" is allowed.</p>
<p>I am wondering how I can get this result. I wrote this one:</p>
<pre><code>pattern = ""private\\\s*static\\\s*(?!final)"";
</code></pre>
<p>But it is not working. How can I get only the entries without the ""final"" keyword?</p>
<p>Thanks,
Med.</p>
","69","479","<java><regex>","2010-07-26 02:19:25","TRUE","FALSE","3331873","2010-07-26 02:31:13","3","<p>That should work, yes. You might want to move the second whitespace inside the lookahead:</p>
<pre><code>pattern = ""private\\s*static(?!\\s*final)"";
</code></pre>
","167","1","1","1","2010-07-26 02:22:17","3","TRUE","166257","1"
"http://stackoverflow.com/users/89566","http://stackoverflow.com/questions/1236113","http://stackoverflow.com/questions/1236113/#1236121","2009-08-05 22:44:54","0","1012","0","3","How can I split out individual column values from each line in a text file?","<p>I have lines in an ASCII text file that I need to parse.
The columns are separated by a variable number of spaces, for instance:</p>
<pre><code>column1 column2 column3
</code></pre>
<p>How would i split this line to return an array of only the values?</p>
<p>thanks</p>
","75","280","<java><parsing><text-parsing>","2009-08-05 22:32:05","TRUE","FALSE","1236121","2009-08-05 22:44:54","7","<pre><code>String testvar = ""Some Data separated by whitespace"";
String[] vals = testvar.split(""\\s+"");
</code></pre>
<p><code>\s</code> means a whitespace character, the <code>+</code> means 1 or more. <code>.split()</code> splits a string into parts divided by the specified delimiter (in this case 1 or more whitespace characters).</p>
","350","1","1","3","2009-08-05 22:34:46","2","TRUE","166257","0"
"http://stackoverflow.com/users/192247","http://stackoverflow.com/questions/2079170","http://stackoverflow.com/questions/2079170/#2079758","2014-09-01 16:18:01","71","4579","24","18","What is the point of the class Option[T]?","<p>I am a beginner to functional programming and I have recently started studying Scala and I really love this language for the all goodies it provides like closures, pattern matching, <a href=""http://en.wikipedia.org/wiki/Currying"">currying</a>, etc.</p>
<p>However, I am not able to understand the point of <code>Option[T]</code> class in Scala. I mean, I am not able to see any advanages of <code>None</code> over <code>null</code>.</p>
<p>For example, consider the code:</p>
<pre><code>object Main{
class Person(name: String, var age: int){
def display = println(name+"" ""+age)
}
def getPerson1: Person = {
// returns a Person instance or null
}
def getPerson2: Option[Person] = {
// returns either Some[Person] or None
}
def main(argv: Array[String]): Unit = {
val p = getPerson1
if (p!=null) p.display
getPerson2 match{
case Some(person) =&gt; person.display
case None =&gt; /* Do nothing */
}
}
}
</code></pre>
<p>Now suppose, the method <code>getPerson1</code> returns <code>null</code>, then the call made to <code>display</code> on first line of <code>main</code> is bound to fail with <code>NPE</code>. Similarly if <code>getPerson2</code> returns <code>None</code>, the <code>display</code> call will again fail with some similar error.</p>
<p>If so, then why does Scala complicate things by introducing a new value wrapper (<code>Option[T]</code>) instead of following a simple approach used in Java?</p>
<p><strong>UPDATE:</strong></p>
<p>I have edited my code as per <a href=""http://stackoverflow.com/users/164075"">@Mitch</a>'s suggestion. I am still not able to see any particular advantage of <code>Option[T]</code>. I have to test for the exceptional <code>null</code> or <code>None</code> in both cases. :(</p>
<p>If I have understood correctly from <a href=""http://stackoverflow.com/questions/2079170/why-optiont/2079247#2079247"">@Michael's reply</a>, is the only advantage of <code>Option[T]</code> is that it explicitly tells the programmer that <em>this method could return None</em>? Is this the only reason behind this design choice?</p>
","41","2130","<java><scala><null><functional-programming><monads>","2010-01-16 22:39:25","TRUE","FALSE","2079758","2010-01-17 16:33:35","56","<p>You'll get the point of <code>Option</code> better if you force yourself to never, ever, use <code>get</code>. That's because <code>get</code> is the equivalent of ""ok, send me back to null-land"".</p>
<p>So, take that example of yours. How would you call <code>display</code> without using <code>get</code>? Here are some alternatives:</p>
<pre><code>getPerson2 foreach (_.display)
for (person &lt;- getPerson2) person.display
getPerson2 match {
case Some(person) =&gt; person.display
case _ =&gt;
}
getPerson2.getOrElse(Person(""Unknown"", 0)).display
</code></pre>
<p>None of this alternatives will let you call <code>display</code> on something that does not exist.</p>
<p>As for why <code>get</code> exists, Scala doesn't tell you how your code should be written. It may gently prod you, but if you want to fall back to no safety net, it's your choice.</p>
<p><strong>EDIT</strong></p>
<p>You nailed it here:</p>
<blockquote>
<p>is the only advantage of Option[T] is
that it explicitly tells the
programmer that this method could
return None?</p>
</blockquote>
<p>Except for the ""only"". But let me restate that in another way: the <em>main</em> advantage of <code>Option[T]</code> over <code>T</code> is type safety. It ensures you won't be sending a <code>T</code> method to an object that may not exist, as the compiler won't let you.</p>
<p>You said you have to test for nullability in both cases, but if you forget -- or don't know -- you have to check for null, will the compiler tell you? Or will your users?</p>
<p>Of course, because of its interoperability with Java, Scala allows nulls just as Java does. So if you use Java libraries, if you use badly written Scala libraries, or if you use badly written <em>personal</em> Scala libraries, you'll still have to deal with null pointers.</p>
<p>Other two important advantages of <code>Option</code> I can think of are:</p>
<ul>
<li><p>Documentation: a method type signature will tell you whether an object is always returned or not.</p></li>
<li><p>Monadic composability.</p></li>
</ul>
<p>The latter one takes much longer to fully appreciate, and it's not well suited to simple examples, as it only shows its strength on complex code. So, I'll give an example below, but I'm well aware it will hardly mean anything except for the people who get it already.</p>
<pre><code>for {
person &lt;- getUsers
email &lt;- person.getEmail // Assuming getEmail returns Option[String]
} yield (person, email)
</code></pre>
","2503","14","2","1","2010-01-17 02:26:16","227","TRUE","163946","0"
"http://stackoverflow.com/users/47630","http://stackoverflow.com/questions/2429944","http://stackoverflow.com/questions/2429944/#2430517","2013-12-29 00:14:55","28","12155","4","7","How to convert a scala.List to a java.util.List?","<p>I'm trying to use some Scala code and am having a hard time figuring out how to convert the Scala lists into standard Java lists.</p>
<p>Any ideas?</p>
","48","156","<java><scala><interop>","2010-03-12 01:37:17","FALSE","FALSE","2430517","2013-12-29 00:14:55","32","<p>Scala List and Java List are two different beasts, because the former is immutable and the latter is mutable. So, to get from one to another, you first have to convert the Scala List into a mutable collection.</p>
<p>On Scala 2.7:</p>
<pre><code>import scala.collection.jcl.Conversions.unconvertList
import scala.collection.jcl.ArrayList
unconvertList(new ArrayList ++ List(1,2,3))
</code></pre>
<p>On Scala 2.8:</p>
<pre><code>import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
asList(ListBuffer(List(1,2,3): _*))
val x: java.util.List[Int] = ListBuffer(List(1,2,3): _*)
</code></pre>
<p>However, <code>asList</code> in that example is not necessary if the type expected is a Java <code>List</code>, as the conversion is implicit, as demonstrated by the last line.</p>
","812","4","2","2","2010-03-12 04:30:08","173","TRUE","163946","0"
"http://stackoverflow.com/users/761180","http://stackoverflow.com/questions/8287360","http://stackoverflow.com/questions/8287360/#8288029","2013-03-13 01:31:56","18","9445","7","4","Scala equivalent of java.util.ArrayList","<p>I am doing a project in Scala, but am fairly new to the language and have a Java background. I see that Scala doesn't have ArrayList, so I am wondering what Scala's equivalent of Java's ArrayList is called, and if there are any important differences between the Java and Scala versions.</p>
<p><strong>EDIT:</strong> I'm not looking for a specific behavior so much as an internal representation (data stored in an array, but the whole array isn't visible, only the part you use).</p>
","39","490","<java><scala><arraylist>","2011-11-27 17:13:53","FALSE","FALSE","8288029","2013-03-13 01:31:56","48","<p><code>ArrayList</code> is a widely misused ""default"" <code>List</code> in Java. It has terrible performance when elements are added/removed frequently, but works pretty well as a replacement for <code>Array</code>. So, when you ask what is the equivalent in Scala, I can think of three different <em>actual</em> questions:</p>
<ul>
<li>What is Scala's default collection?</li>
<li>What Scala collection has characteristics similar to <code>ArrayList</code>?</li>
<li>What's a good replacement for <code>Array</code> in Scala?</li>
</ul>
<p>So here are the answers for these:</p>
<h2>What is Scala's default collection?</h2>
<p>Scala's equivalent of Java's <code>List</code> interface is the <code>Seq</code>. A more general interface exists as well, which is the <code>GenSeq</code> -- the main difference being that a <code>GenSeq</code> may have operations processed serially or in parallel, depending on the implementation.</p>
<p>Because Scala allows programmers to use <code>Seq</code> as a factory, they don't often bother with defining a particular implementation unless they care about it. When they do, they'll usually pick either Scala's <code>List</code> or <code>Vector</code>. They are both immutable, and <code>Vector</code> has good indexed access performance. On the other hand, <code>List</code> does very well the operations it does well.</p>
<h2>What Scala collection has characteristics similar to <code>ArrayList</code>?</h2>
<p>That would be <code>scala.collection.mutable.ArrayBuffer</code>.</p>
<h2>What's a good replacement for <code>Array</code> in Scala?</h2>
<p>Well, the good news is, you can just use <code>Array</code> in Scala! In Java, <code>Array</code> is often avoided because of its general incompatibility with generics. It is a co-variant collection, whereas generics is invariant, it is mutable -- which makes it's co-variance a danger, it accepts primitives where generics don't, and it has a pretty limited set of methods.</p>
<p>In Scala, <code>Array</code> -- which is still the same <code>Array</code> as in Java -- is invariant, which makes most problems go away. Scala accepts <code>AnyVal</code> (the equivalent of primitives) as types for its ""generics"", even though it will do auto-boxing. And through the ""enrich my library"" pattern, <strong>ALL</strong> of <code>Seq</code> methods are available to <code>Array</code>.</p>
<p>So, if you want a more powerful <code>Array</code>, just use an <code>Array</code>.</p>
<h2>What about a collection that shrinks and grows?</h2>
<p>The default methods available to all collections all produce <em>new</em> collections. For example, if I do this:</p>
<pre><code>val ys = xs filter (x =&gt; x % 2 == 0)
</code></pre>
<p>Then <code>ys</code> will be a <em>new</em> collection, while <code>xs</code> will still be the same as before this command. This is true no matter what <code>xs</code> was: <code>Array</code>, <code>List</code>, etc.</p>
<p>Naturally, this has a cost -- after all, you <em>are</em> producing a new collection. Scala's immutable collections are much better at handling this cost because they are <em>persistent</em>, but it depends on what operation is executed.</p>
<p>No collection can do much about <code>filter</code>, but a <code>List</code> has excellent performance on generating a new collection by prepending an element or removing the head -- the basic operations of a stack, as a matter of fact. <code>Vector</code> has good performance on a bunch of operations, but it only pays if the collection isn't small. For collections of, say, up to a hundred elements, the overall cost might exceed the gains.</p>
<p>So you can actually add or remove elements to an <code>Array</code>, and Scala will produce a <em>new</em> <code>Array</code> for you, but you'll pay the cost of a full copy when you do that.</p>
<p>Scala mutable collections add a few other methods. In particular, the collections that can increase or decrease size -- without producing a new collection -- implement the <a href=""http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html#scala.collection.generic.Growable""><code>Growable</code></a> and <a href=""http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html#scala.collection.generic.Shrinkable""><code>Shrinkable</code></a> traits. They don't guarantee good performance on these operations, though, but they'll point you to the collections you want to check out.</p>
","4499","14","1","26","2011-11-27 18:40:33","87","TRUE","163946","0"
"http://stackoverflow.com/users/770361","http://stackoverflow.com/questions/6638933","http://stackoverflow.com/questions/6638933/#6639181","2014-02-19 15:44:37","17","3773","13","5","Dynamic programming in the functional paradigm","<p>I'm looking at <a href=""http://projecteuler.net/index.php?section=problems&amp;id=31"">Problem thirty one</a> on Project Euler, which asks, how many different ways are there of making £2 using any number of coins of 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).</p>
<p>There are recursive solutions, such as this one in Scala (credit to Pavel Fatin)</p>
<pre><code>def f(ms: List[Int], n: Int): Int = ms match {
case h :: t =&gt;
if (h &gt; n) 0 else if (n == h) 1 else f(ms, n - h) + f(t, n)
case _ =&gt; 0
}
val r = f(List(1, 2, 5, 10, 20, 50, 100, 200), 200)
</code></pre>
<p>and although it runs fast enough, it's relatively inefficient, calling the <code>f</code> function around 5.6 million times.</p>
<p>I saw someone else's solution in Java which was programmed dynamically (credit to wizeman from Portugal)</p>
<pre><code>final static int TOTAL = 200;
public static void main(String[] args) {
int[] coins = {1, 2, 5, 10, 20, 50, 100, 200};
int[] ways = new int[TOTAL + 1];
ways[0] = 1;
for (int coin : coins) {
for (int j = coin; j &lt;= TOTAL; j++) {
ways[j] += ways[j - coin];
}
}
System.out.println(""Result: "" + ways[TOTAL]);
}
</code></pre>
<p>This is much more efficient and passes the inner loop only 1220 times.</p>
<p>While I could obviously translate this more or less verbatim into Scala using <code>Array</code> objects, is there an idiomatic functional way to do this using immutable data structures, preferably with similar conciseness and performance?</p>
<p>I have tried and become stuck trying to recursively update a <code>List</code> before deciding I'm probably just approaching it the wrong way.</p>
","46","1709","<java><scala><functional-programming><project-euler><dynamic-programming>","2011-07-10 03:08:37","TRUE","FALSE","6639181","2011-07-10 07:22:48","12","<p>Whenever some part of a list of data is computed based on a previous element, I think of <code>Stream</code> recursion. Unfortunately, such recursion cannot happen inside method definitions or functions, so I had to turn a function into a class to make it work.</p>
<pre><code>class IterationForCoin(stream: Stream[Int], coin: Int) {
val (lower, higher) = stream splitAt coin
val next: Stream[Int] = lower #::: (higher zip next map { case (a, b) =&gt; a + b })
}
val coins = List(1, 2, 5, 10, 20, 50, 100, 200)
val result = coins.foldLeft(1 #:: Stream.fill(200)(0)) { (stream, coin) =&gt;
new IterationForCoin(stream, coin).next
} last
</code></pre>
<p>The definitions of <code>lower</code> and <code>higher</code> are not necessary -- I could easily replace them with <code>stream take coin</code> and <code>stream drop coin</code>, but I think it's a little clearer (and more efficient) this way.</p>
","914","2","1","4","2011-07-10 04:36:17","88","TRUE","163946","0"
"http://stackoverflow.com/users/293686","http://stackoverflow.com/questions/6927873","http://stackoverflow.com/questions/6927873/#6928211","2013-05-30 23:52:39","6","4439","4","4","How can I read a file to an InputStream then write it into an OutputStream in Scala?","<p>I'm trying to use basic Java code in Scala to read from a file and write to an <strong>OutputStream</strong>, but when I use the usual <strong>while( != -1 )</strong> in Scala gives me a warning ""comparing types of Unit and Int with != will always yield true"". </p>
<p>The code is as follows:</p>
<pre><code> val file = this.cache.get(imageFileEntry).getValue().asInstanceOf[File]
response.setContentType( ""image/%s"".format( imageDescription.getFormat() ) )
val input = new BufferedInputStream( new FileInputStream( file ) )
val output = response.getOutputStream()
var read : Int = -1
while ( ( read = input.read ) != -1 ) {
output.write( read )
}
input.close()
output.flush()
</code></pre>
<p>How am I supposed to write from an input stream to an output stream in Scala?</p>
<p>I'm mostly interested in a <strong>Scala-like</strong> solution.</p>
","84","902","<java><scala><integration><inputstream><outputstream>","2011-08-03 14:12:23","TRUE","FALSE","6928211","2013-05-30 23:52:39","20","<p>You could do this:</p>
<pre><code>Iterator
.continually (input.read)
.takeWhile (-1 !=)
.foreach (output.write)
</code></pre>
","131","1","1","3","2011-08-03 14:35:11","23","TRUE","163946","0"
"http://stackoverflow.com/users/283998","http://stackoverflow.com/questions/8027801","http://stackoverflow.com/questions/8027801/#8029430","2011-11-25 00:09:59","4","863","4","4","scala ranges versus lists performance on large collections","<p>I ran a set of performance benchmarks for 10,000,000 elements, and I've discovered that the results vary greatly with each implementation.</p>
<p>Can anybody explain why creating a Range.ByOne, results in performance that is better than a simple array of primitives, but converting that same range to a list results in even worse performance than the worse case scenario?</p>
<p>Create 10,000,000 elements, and print out those that are modulos of 1,000,000. JVM size is always set to same min and max: -Xms?m -Xmx?m</p>
<pre><code>import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit._
object LightAndFastRange extends App {
def chrono[A](f: =&gt; A, timeUnit: TimeUnit = MILLISECONDS): (A,Long) = {
val start = System.nanoTime()
val result: A = f
val end = System.nanoTime()
(result, timeUnit.convert(end-start, NANOSECONDS))
}
def millions(): List[Int] = (0 to 10000000).filter(_ % 1000000 == 0).toList
val results = chrono(millions())
results._1.foreach(x =&gt; println (""x: "" + x))
println(""Time: "" + results._2);
}
</code></pre>
<p>It takes 141 milliseconds with a JVM size of 27m</p>
<p>In comparison, converting to List affects performance dramatically:</p>
<pre><code>import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit._
object LargeLinkedList extends App {
def chrono[A](f: =&gt; A, timeUnit: TimeUnit = MILLISECONDS): (A,Long) = {
val start = System.nanoTime()
val result: A = f
val end = System.nanoTime()
(result, timeUnit.convert(end-start, NANOSECONDS))
}
val results = chrono((0 to 10000000).toList.filter(_ % 1000000 == 0))
results._1.foreach(x =&gt; println (""x: "" + x))
println(""Time: "" + results._2)
}
</code></pre>
<p>It takes 8514-10896 ms with 460-455 m</p>
<p>In contrast, this Java implementation uses an array of primitives</p>
<pre><code>import static java.util.concurrent.TimeUnit.*;
public class LargePrimitiveArray {
public static void main(String[] args){
long start = System.nanoTime();
int[] elements = new int[10000000];
for(int i = 0; i &lt; 10000000; i++){
elements[i] = i;
}
for(int i = 0; i &lt; 10000000; i++){
if(elements[i] % 1000000 == 0) {
System.out.println(""x: "" + elements[i]);
}
}
long end = System.nanoTime();
System.out.println(""Time: "" + MILLISECONDS.convert(end-start, NANOSECONDS));
}
}
</code></pre>
<p>It takes 116ms with JVM size of 59m</p>
<p>Java List of Integers</p>
<pre><code>import java.util.List;
import java.util.ArrayList;
import static java.util.concurrent.TimeUnit.*;
public class LargeArrayList {
public static void main(String[] args){
long start = System.nanoTime();
List&lt;Integer&gt; elements = new ArrayList&lt;Integer&gt;();
for(int i = 0; i &lt; 10000000; i++){
elements.add(i);
}
for(Integer x: elements){
if(x % 1000000 == 0) {
System.out.println(""x: "" + x);
}
}
long end = System.nanoTime();
System.out.println(""Time: "" + MILLISECONDS.convert(end-start, NANOSECONDS));
}
</code></pre>
<p>}</p>
<p>It takes 3993 ms with JVM size of 283m</p>
<p>My question is, why is the first example so performant, while the second is so badly affected. I tried creating views, but wasn't successful at reproducing the performance benefits of the range.</p>
<p>All tests running on Mac OS X Snow Leopard,
Java 6u26 64-Bit Server
Scala 2.9.1.final </p>
<p>EDIT:</p>
<p>for completion, here's the actual implementation using a LinkedList (which is a more fair comparison in terms of space than ArrayList, since as rightly pointed out, scala's List are linked)</p>
<pre><code>import java.util.List;
import java.util.LinkedList;
import static java.util.concurrent.TimeUnit.*;
public class LargeLinkedList {
public static void main(String[] args){
LargeLinkedList test = new LargeLinkedList();
long start = System.nanoTime();
List&lt;Integer&gt; elements = test.createElements();
test.findElementsToPrint(elements);
long end = System.nanoTime();
System.out.println(""Time: "" + MILLISECONDS.convert(end-start, NANOSECONDS));
}
private List&lt;Integer&gt; createElements(){
List&lt;Integer&gt; elements = new LinkedList&lt;Integer&gt;();
for(int i = 0; i &lt; 10000000; i++){
elements.add(i);
}
return elements;
}
private void findElementsToPrint(List&lt;Integer&gt; elements){
for(Integer x: elements){
if(x % 1000000 == 0) {
System.out.println(""x: "" + x);
}
}
}
}
</code></pre>
<p>Takes 3621-6749 ms with 480-460 mbs. That's much more in line with the performance of the second scala example. </p>
<p>finally, a LargeArrayBuffer</p>
<pre><code>import collection.mutable.ArrayBuffer
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit._
object LargeArrayBuffer extends App {
def chrono[A](f: =&gt; A, timeUnit: TimeUnit = MILLISECONDS): (A,Long) = {
val start = System.nanoTime()
val result: A = f
val end = System.nanoTime()
(result, timeUnit.convert(end-start, NANOSECONDS))
}
def millions(): List[Int] = {
val size = 10000000
var items = new ArrayBuffer[Int](size)
(0 to size).foreach (items += _)
items.filter(_ % 1000000 == 0).toList
}
val results = chrono(millions())
results._1.foreach(x =&gt; println (""x: "" + x))
println(""Time: "" + results._2);
}
</code></pre>
<p>Taking about 2145 ms and 375 mb</p>
<p>Thanks a lot for the answers.</p>
","58","5920","<java><performance><scala><collections><range>","2011-11-06 14:46:35","TRUE","FALSE","8029430","2011-11-06 23:27:40","11","<p>Oh So Many Things going on here!!!</p>
<p>Let's start with Java <code>int[]</code>. Arrays in Java are the only collection that is not type erased. The run time representation of an <code>int[]</code> is different from the run time representation of <code>Object[]</code>, in that it actually uses <code>int</code> directly. Because of that, there's no boxing involved in using it.</p>
<p>In memory terms, you have 40.000.000 consecutive bytes in memory, that are read and written 4 at a time whenever an element is read or written to.</p>
<p>In contrast, an <code>ArrayList&lt;Integer&gt;</code> -- as well as pretty much any other generic collection -- is composed of 40.000.000 or 80.000.00 consecutive bytes (on 32 and 64 bits JVM respectively), PLUS 80.000.000 bytes spread all around memory in groups of 8 bytes. Every read an write to an element has to go through two memory spaces, and the sheer time spent handling all that memory is significant when the actual task you are doing is so fast.</p>
<p>So, back to Scala, for the second example where you manipulate a <code>List</code>. Now, Scala's <code>List</code> is much more like Java's <code>LinkedList</code> than the grossly misnamed <code>ArrayList</code>. Each element of a <code>List</code> is composed of an object called <code>Cons</code>, which has 16 bytes, with a pointer to the element and a pointer to another list. So, a <code>List</code> of 10.000.000 elements is composed of 160.000.000 elements spread all around memory in groups of 16 bytes, plus 80.000.000 bytes spread all around memory in groups of 8 bytes. So what was true for <code>ArrayList</code> is even more so for <code>List</code></p>
<p>Finally, <code>Range</code>. A <code>Range</code> is a sequence of integers with a lower and an upper boundary, plus a step. A <code>Range</code> of 10.000.000 elements is 40 bytes: three ints (not generic) for lower and upper bounds and step, plus a few pre-computed values (<code>last</code>, <code>numRangeElements</code>) and two other ints used for <code>lazy val</code> thread safety. Just to make clear, that's <em>NOT</em> 40 times 10.000.000: that's 40 bytes TOTAL. The size of the range is completely irrelevant, because <em>IT DOESN'T STORE THE INDIVIDUAL ELEMENTS</em>. Just the lower bound, upper bound and step.</p>
<p>Now, because a <code>Range</code> is a <code>Seq[Int]</code>, it still has to go through boxing for most uses: an <code>int</code> will be converted into an <code>Integer</code> and then back into an <code>int</code> again, which is sadly wasteful.</p>
<p><strong>Cons Size Calculation</strong></p>
<p>So, here's a tentative calculation of Cons. First of all, read <a href=""http://www.javamex.com/tutorials/memory/object_memory_usage.shtml"">this article</a> about some general guidelines on how much memory an object takes. The important points are:</p>
<ol>
<li>Java uses 8 bytes for normal objects, and 12 for object arrays, for ""housekeeping"" information (what's the class of this object, etc).</li>
<li>Objects are allocated in 8 bytes chunks. If your object is smaller than that, it will be padded to complement it.</li>
</ol>
<p>I actually thought it was 16 bytes, not 8. Anyway, Cons is also smaller than I thought. Its fields are:</p>
<pre><code>public static final long serialVersionUID; // static, doesn't count
private java.lang.Object scala$collection$immutable$$colon$colon$$hd;
private scala.collection.immutable.List tl;
</code></pre>
<p>References are <em>at least</em> 4 bytes (could be more on 64 bits JVM). So we have:</p>
<pre><code>8 bytes Java header
4 bytes hd
4 bytes tl
</code></pre>
<p>Which makes it only 16 bytes long. Pretty good, actually. In the example, <code>hd</code> will point to an <code>Integer</code> object, which I assume is 8 bytes long. As for <code>tl</code>, it points to another cons, which we are already counting.</p>
<p>I'm going to revise the estimates, with actual data where possible.</p>
","3972","13","2","4","2011-11-06 18:44:52","238","TRUE","163946","0"
"http://stackoverflow.com/users/68653","http://stackoverflow.com/questions/577575","http://stackoverflow.com/questions/577575/#577582","2014-07-26 11:30:49","17","24762","5","11","Using the keyword ""this"" in java","<p>I'm trying to get an understanding of what the the java keyword <code>this</code> actually does.
I've been reading Sun's documentation but I'm still fuzzy on what <code>this</code> actually does.</p>
","32","203","<java><keyword>","2009-02-23 13:11:57","FALSE","FALSE","577582","2009-02-23 13:25:07","26","<p>The <code>this</code> keyword is a reference to the current object.</p>
<pre><code>class Foo
{
private int bar;
public Foo(int bar)
{
// the ""this"" keyword allows you to specify that
// you mean ""this type"" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// ""bar"" and the parameter ""bar"" passed into the
// constructor
this.bar = bar;
}
}
</code></pre>
<p>Another way to think about it is that the <code>this</code> keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses <code>Me</code> and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use <code>self</code>.</p>
<p>If you were to reference objects that are intrinsically yours you would say something like this:</p>
<blockquote>
<p><em>My</em> arm or <em>my</em> leg</p>
</blockquote>
<p>Think of <code>this</code> as just a way for a type to say ""my"". So a psuedocode representation would look like this:</p>
<pre><code>class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
</code></pre>
","1291","5","2","7","2009-02-23 13:14:09","3","TRUE","162715","0"
"http://stackoverflow.com/users/103604","http://stackoverflow.com/questions/1133083","http://stackoverflow.com/questions/1133083/#1133100","2013-12-13 16:23:41","9","3665","2","4","Prevent Java from loading library more than once","<p>I have several classes that use the same JNI library, called ""jni"". In each of those classes, I have a System.loadLibrary() call in the class's static initializer:</p>
<pre><code>Class class1 {
static{
System.loadLibrary(""jni"");
}
...
}
Class class2 {
static{
System.loadLibrary(""jni"");
}
...
}
</code></pre>
<p>The only problem is, I only want System.loadLibrary() to be called once, since it can take a while. Is there an easy and clean way to prevent multiple loadings of the same library?</p>
","48","543","<java><jni>","2009-07-15 18:26:15","TRUE","FALSE","1133100","2013-12-13 16:23:41","18","<p>If the library has already be loaded any subsequent calls to load the same library will be ignored.</p>
<p><a href=""http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#loadLibrary%28java.lang.String%29""><code>System.loadLibrary</code></a>:</p>
<blockquote>
<p>Loads the system library specified by
the libname argument. The manner in
which a library name is mapped to the
actual system library is system
dependent.</p>
<p>The call System.loadLibrary(name) is
effectively equivalent to the call</p>
<pre><code> Runtime.getRuntime().loadLibrary(name)
</code></pre>
</blockquote>
<p><a href=""http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#loadLibrary%28java.lang.String%29""><code>Runtime.loadLibrary</code></a>:</p>
<blockquote>
<p>Loads the dynamic library with the
specified library name. A file
containing native code is loaded from
the local file system from a place
where library files are conventionally
obtained. The details of this process
are implementation-dependent. The
mapping from a library name to a
specific filename is done in a
system-specific manner.</p>
<p>First, if there is a security manager,
its checkLink method is called with
the libname as its argument. This may
result in a security exception.</p>
<p>The method System.loadLibrary(String)
is the conventional and convenient
means of invoking this method. If
native methods are to be used in the
implementation of a class, a standard
strategy is to put the native code in
a library file (call it LibFile) and
then to put a static initializer:</p>
<pre><code> static { System.loadLibrary(""LibFile""); }
</code></pre>
<p>within the class declaration. When the
class is loaded and initialized, the
necessary native code implementation
for the native methods will then be
loaded as well.</p>
<p><strong><em>If this method is called more than
once with the same library name, the
second and subsequent calls are
ignored.</em></strong></p>
</blockquote>
","2048","10","2","2","2009-07-15 18:28:47","2","TRUE","162715","0"
"http://stackoverflow.com/users/275674","http://stackoverflow.com/questions/2677979","http://stackoverflow.com/questions/2677979/#2677983","2010-04-20 19:57:25","3","2356","2","2","Java reference type","<p>How does Java deal with passing reference data type arguments?? Can somebody give a clear picture?</p>
","19","106","<java>","2010-04-20 19:20:12","FALSE","FALSE","2677983","2010-04-20 19:28:07","10","<p>Java passes a copy of the reference to the method. The reference still points to the same instance.</p>
<p>Imagine if I had a slip of paper with a restaurant's address on it. You also want to go to the same restaurant so I get a new slip of paper and copy the address of the restaurant on to that paper and give it to you. Both slips of paper point to the same restaurant but they are separate <em>references</em> to the instance.</p>
<p>The restaurant itself is not duplicated, only the reference to it is duplicated.</p>
<p>Jon Skeet <a href=""http://www.yoda.arachsys.com/java/passing.html"">provides a similar analogy</a>:</p>
<blockquote>
<p><strong>The balloon analogy</strong> </p>
<p>I imagine every
object as a helium balloon, every
reference as a piece of string, and
every variable as something which can
hold onto a piece of string. If the
reference is a null reference, that's
like having a piece of string without
anything attached to the end. If it's
a reference to a genuine object, it's
a piece of string tied onto the
balloon representing that object. When
a reference is copied (either for
variable assignment or as part of a
method call) it's as if another piece
of string is created attached to
whatever the first piece of string is
attached to. The actual piece of
string the variable (if any) is
holding onto doesn't go anywhere -
it's only copied.</p>
</blockquote>
<p>Here is an example:</p>
<pre><code>// Here I have one instance and one reference pointing to it
Object o = new Object();
// At this moment a copy of ""o"" is made and passed to ""foo""
foo(o);
void foo(Object obj) {
// In here I have obj which is a copy of whatever
// reference was passed to me
}
</code></pre>
","1767","7","1","7","2010-04-20 19:21:26","1","TRUE","162715","0"
"http://stackoverflow.com/users/292","http://stackoverflow.com/questions/623845","http://stackoverflow.com/questions/623845/#623856","2009-03-09 17:23:06","2","1816","0","8","Why doesn't Java have a way of specifying unescaped String literals?","<p>In C#, if you want a String to be taken literally, i.e. ignore escape characters, you can use:</p>
<pre><code>string myString = @""sadasd/asdaljsdl"";
</code></pre>
<p>However there is no equivalent in Java. Is there any reason Java has not included something similar?</p>
<p>Edit:</p>
<p>After reviewing some answers and thinking about it, what I'm really asking is:<br />
Is there any compelling argument against adding this syntax to Java? Some negative to it, that I'm just not seeing?</p>
","68","501","<c#><java><language-comparisons>","2009-03-08 16:41:55","TRUE","FALSE","623856","2009-03-08 16:52:41","4","<p>Java has always struck me as a minimalist language - I would imagine that since verbatim strings are not a necessity (like properties for instance) they were not included.</p>
<p>For instance in C# there are many quick ways to do thing like properties:</p>
<pre><code>public int Foo { get; set; }
</code></pre>
<p>and verbatim strings:</p>
<pre><code>String bar = @""some
string"";
</code></pre>
<p>Java tends to avoid as much syntax-sugar as possible. If you want getters and setters for a field you must do this:</p>
<pre><code>private int foo;
public int getFoo() { return this.foo; }
public int setFoo(int foo) { this.foo = foo; }
</code></pre>
<p>and strings must be escaped:</p>
<pre><code>String bar = ""some\nstring"";
</code></pre>
<p>I think it is because in a lot of ways C# and Java have different design goals. C# is rapidly developed with many features being constantly added but most of which tend to be syntax sugar. Java on the other hand is about simplicity and ease of understanding. A lot of the reasons that Java was created in the first place were reactions against C++'s complexity of syntax.</p>
","1134","6","4","6","2009-03-08 16:45:22","4","TRUE","162715","0"
"http://stackoverflow.com/users/1977903","http://stackoverflow.com/questions/2675666","http://stackoverflow.com/questions/2675666/#2675701","2010-04-20 14:07:47","1","222","0","2","Help needed in formatting date in Java","<p>Hi I have the following date as String format.</p>
<p>Input</p>
<pre><code>2010-04-20 05:34:58.0
</code></pre>
<p>Output I want the string like</p>
<pre><code>20, Apr 2010
</code></pre>
<p>Can someone tell me how to do it ?</p>
","38","236","<java><date><date-format>","2010-04-20 13:59:01","TRUE","FALSE","2675701","2010-04-20 14:07:47","5","<p>Try this:</p>
<pre><code>DateFormat inputFormat = new SimpleDateFormat(""yyyy-MM-dd HH:mm:ss.S"");
DateFormat outputFormat = new SimpleDateFormat(""dd, MMM yyyy"");
Date yourDate = inputFormat.parse(""2010-04-20 05:34:58.0"");
String formattedDate = outputFormat.format(yourDate);
</code></pre>
","296","1","1","2","2010-04-20 14:02:29","3","TRUE","162715","0"
"http://stackoverflow.com/users/160189","http://stackoverflow.com/questions/1429860","http://stackoverflow.com/questions/1429860/#1429869","2014-05-13 14:51:41","176","96759","26","6","Easiest way to convert a List to a Set? - Java","<p>Easiest way to convert a List to a Set? - In Java</p>
","46","57","<java><collections>","2009-09-15 22:02:35","FALSE","FALSE","1429869","2014-05-13 14:51:41","294","<pre><code>Set&lt;Foo&gt; foo = new HashSet&lt;Foo&gt;(myList);
</code></pre>
","78","0","1","1","2009-09-15 22:05:38","3","TRUE","162294","0"
"http://stackoverflow.com/users/468625","http://stackoverflow.com/questions/3953244","http://stackoverflow.com/questions/3953244/#3953257","2012-02-08 12:10:03","28","5752","8","13","Example of O(n!)?","<p>What is an example (in code) of a O(n!) function? It should take appropriate number of operations to run in reference to n; that is, I'm asking about time complexity.</p>
","17","175","<java><algorithm><big-o><factorial><asymptotic-complexity>","2010-10-17 12:37:47","FALSE","FALSE","3953257","2010-10-17 13:04:56","35","<p>There you go. This is probably the most trivial example of a function that runs in <code>O(n!)</code> time (where <code>n</code> is the argument to the function):</p>
<pre><code>void nFac(int n) {
for(int i=0; i&lt;n; i++) {
nFac(n-1);
}
}
</code></pre>
","266","1","1","9","2010-10-17 12:42:17","5","TRUE","162294","0"
"http://stackoverflow.com/users/23368","http://stackoverflow.com/questions/1461286","http://stackoverflow.com/questions/1461286/#1461346","2012-10-20 06:43:46","3","1449","5","3","Advanced Java-like enums in Ruby","<p>First of all, this is not a duplicate of <a href=""http://stackoverflow.com/questions/75759/enums-in-ruby"">Enums in Ruby</a> :)</p>
<p>The accepted answer of that question suggests this as a good way to represent enums in Ruby:</p>
<pre><code>class Foo
BAR = 1
BAZ = 2
BIZ = 4
end
</code></pre>
<p>In Java it is possible to attach multiple values and methods to an enum value. I want to achive the same or something similar in Ruby.</p>
<p>What would be the most Ruby-like way to represent this Java enum:</p>
<pre><code>public enum Enum
VALUE_1(""Value 1""),
VALUE_2(""Value 2""),
VALUE_3(""Value 3"");
Enum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
private String value;
}
</code></pre>
<p><strong>EDIT:</strong> </p>
<p>I also want to keep the implicit features of Java enums:</p>
<ul>
<li>... retrieve the ordinal value</li>
<li>... call methods on the enum values (or something equivalent)</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code>Enum.VALUE_1.getValue(); // ""Value 1""
Enum.VALUE_2.name(); // ""VALUE_2""
Enum.VALUE_3.ordinal(); // 2
</code></pre>
","32","1174","<java><ruby><enums>","2009-09-22 16:59:28","TRUE","FALSE","1461346","2009-09-22 19:41:46","11","<pre><code>class MyEnum
attr_accessor :value
def initialize(value)
@value = value
end
VALUE1 = new(""Value 1"")
VALUE2 = new(""Value 2"")
class &lt;&lt; self
private :new
end
end
MyEnum::VALUE2 # Enum with value ""Value 2""
MyEnum.new # Error
</code></pre>
<p>A more elaborate solution that allows you to define arbitrary ""enum classes"" and also gives you <code>ordinal()</code>:</p>
<pre><code>def enum(*values, &amp;class_body)
Class.new( Class.new(&amp;class_body) ) do
attr_reader :ordinal
def initialize(ordinal, *args, &amp;blk)
super(*args, &amp;blk)
@ordinal = ordinal
end
values.each_with_index do |(name, *parameters), i|
const_set(name, new(i, *parameters))
end
class &lt;&lt;self
private :new
end
end
end
# Usage:
MyEnum = enum([:VALUE1, ""Value 1""], [:VALUE2, ""Value 2""]) do
attr_reader :str
def initialize(str)
@str = str
end
end
MyEnum::VALUE1.str #=&gt; ""Value 1""
MyEnum::VALUE2.ordinal #=&gt; 1
</code></pre>
","1017","1","2","8","2009-09-22 17:08:24","9","TRUE","162294","0"
"http://stackoverflow.com/users/118610","http://stackoverflow.com/questions/3173497","http://stackoverflow.com/questions/3173497/#3173518","2010-07-04 03:32:28","2","2300","1","1","Sorting ArrayList of String[]","<p>I have an arraylist of String[]:</p>
<blockquote>
<p><em>ArrayList&lt; String [] > mystuff = new ArrayList &lt; String [] > ();</em></p>
</blockquote>
<p>I want to sort them in largest-array-size ascending order. Example:</p>
<blockquote>
<p>mystuff = {[""this"", ""is"", ""item"",
""one""], [""this"", ""is"", ""item"", ""two""],
[""item""], [""item"", ""three""]}</p>
</blockquote>
<p>Should become:</p>
<blockquote>
<p>mystuff = {[""item""], [""item"",
""three""], [""this"", ""is"", ""item"",
""one""], [""this"", ""is"", ""item"", ""two""]}</p>
</blockquote>
<p>For arrays of equal length, the order doesn't matter.</p>
<p><strong>Edit:</strong></p>
<blockquote>
<p>Java compiler version: javac 1.6.0_20</p>
<p>Error that I am facing by using
@sepp2k's code:
<a href=""http://pastie.org/private/ienpdtj0ft6czw6nboeva"" rel=""nofollow"">http://pastie.org/private/ienpdtj0ft6czw6nboeva</a></p>
</blockquote>
","29","899","<java><sorting><arraylist>","2010-07-04 02:15:30","FALSE","FALSE","3173518","2010-07-04 03:15:58","10","<p>Use <code>Collections.sort</code> with a <code>Comparator</code> that compares the length.</p>
<pre><code>Collections.sort(mystuff, new Comparator&lt;String[]&gt;() {
public int compare(String[] x, String[] y) {
if(x.length &lt; y.length) {
return -1;
} else if(x.length == y.length) {
return 0;
} else {
return 1;
}
}
});
</code></pre>
<p>Edit: Here's a complete class that compiles and runs without error (and shows the correct result):</p>
<pre><code>import java.util.*;
public class Bla {
public static void main(String[] args) {
// Create list
List&lt;String[]&gt; mystuff = new ArrayList&lt;String[]&gt;();
mystuff.add(new String[] {""lilu"", ""lolo""});
mystuff.add(new String[] {""lala""});
mystuff.add(new String[] {""lila"", ""blabla"", ""pfirsichkuchen""});
// Sort list
Collections.sort(mystuff, new Comparator&lt;String[]&gt;() {
public int compare(String[] x, String[] y) {
if(x.length &lt; y.length) {
return -1;
} else if(x.length == y.length) {
return 0;
} else {
return 1;
}
}
});
// Output list
for(String[] strs : mystuff) {
System.out.println(Arrays.toString(strs));
}
}
}
</code></pre>
","1465","2","2","6","2010-07-04 02:23:43","8","TRUE","162294","0"
"http://stackoverflow.com/users/147601","http://stackoverflow.com/questions/1548830","http://stackoverflow.com/questions/1548830/#1548846","2009-10-10 21:11:09","1","3209","1","2","Java: str.replaceAll() not working","<p>I'm trying to cleanse one String from another.</p>
<pre><code>before = before.replaceAll(Constants.GENE_START_SEQUENCE, """");
</code></pre>
<p>And yet, the following assertion sometimes fails:</p>
<pre><code>assert before.indexOf(Constants.GENE_START_SEQUENCE) == -1 : before;
</code></pre>
<p>This is what the assert spits out:</p>
<pre><code>IIAOOOCOAAAOCCIOOOACAIAOACICOOIAIOOICIIOIIOICOICCCOOAOICOCOOIIOOAOAACIIOCCICIOIII
</code></pre>
","34","447","<java><string><replaceall>","2009-10-10 19:17:41","TRUE","FALSE","1548846","2009-10-10 21:11:09","11","<p><code>replaceAll</code> only replaces occurences of the pattern in the original string. If the pattern reoccurs as a result of the replacement, this new occurence won't be replaced. Example:</p>
<pre><code>""XXYY"".replaceAll(""XY"", """");
</code></pre>
<p>This will find one occurence of ""XY"" (at index 1) and then replace that with """". The result will be ""XY"". If you want to prevent this from happening, you have to rexecute replaceAll, until <code>replaceAll</code> stops finding a match.</p>
<pre><code>String string = ""XXYY"";
String oldString;
do {
oldString = string;
string = string.replaceAll(""XY"", """");
} while(!string.equals(oldString));
// string will now be """"
</code></pre>
","693","2","2","1","2009-10-10 19:26:31","9","TRUE","162294","0"
"http://stackoverflow.com/users/106615","http://stackoverflow.com/questions/1235346","http://stackoverflow.com/questions/1235346/#1235364","2009-08-05 20:08:23","0","144","0","2","What does this code do (ever seen an object without a reference variable? how about invoking the object later without the reference variable?)?","<pre><code>EventQueue.invokeLater(new Runnable()
{
public void run()
{
ZipTestFrame frame = new ZipTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
</code></pre>
","143","268","<java><events><object>","2009-08-05 19:45:38","TRUE","FALSE","1235364","2009-08-05 20:00:36","9","<p>That code creates an instance of an anonymous class implementing runnable. That object is passed as an argument to EventQueue.invokeLater, which will invoke it later (meaning it will call the run method on that object at some later point in time).</p>
<p>You don't need a variable to point to the object because you only use that object in that one instance. The method invokeLater does have a local variable pointing to the object (given that the object is passed as an argument and arguments are local variables), which it uses to store the object in the event queue, which now also references the object, until the object is invoked and removed from the queue, at which point it's elligible for garbage collection.</p>
<p>Addendum:</p>
<p>A primitive example of what a simple event queue could look like:</p>
<pre><code>class MyEventQueue {
Queue&lt;Runnable&gt; queue = new LinkedList&lt;Runnable&gt;();
public void invokeLater(Runnable r) {
queue.add(r);
}
public boolean hasNext() {
return !queue.isEmpty();
}
public void processNext() {
queue.poll.run();
}
}
</code></pre>
","1139","4","1","2","2009-08-05 19:48:53","3","TRUE","162294","0"
"http://stackoverflow.com/users/404615","http://stackoverflow.com/questions/3758606","http://stackoverflow.com/questions/3758606/#3758880","2014-08-04 23:09:17","180","52473","105","8","How to convert byte size into human readable format in java?","<p>How to convert byte size into human-readable format in Java? Like 1024 should become ""1 Kb"" and 1024*1024 should become ""1 Mb"".</p>
<p>I am kind of sick of writing this utility method for each project. Are there any static methods in Apache Commons for this?</p>
","60","267","<java><formatting><apache-commons>","2010-09-21 08:42:59","FALSE","FALSE","3758880","2012-05-17 18:59:28","507","<p>Here is my go at it (no loops and handles both SI units and binary units):</p>
<pre><code>public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes &lt; unit) return bytes + "" B"";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? ""kMGTPE"" : ""KMGTPE"").charAt(exp-1) + (si ? """" : ""i"");
return String.format(""%.1f %sB"", bytes / Math.pow(unit, exp), pre);
}
</code></pre>
<p>Example output:</p>
<pre><code> SI BINARY
0: 0 B 0 B
27: 27 B 27 B
999: 999 B 999 B
1000: 1.0 kB 1000 B
1023: 1.0 kB 1023 B
1024: 1.0 kB 1.0 KiB
1728: 1.7 kB 1.7 KiB
110592: 110.6 kB 108.0 KiB
7077888: 7.1 MB 6.8 MiB
452984832: 453.0 MB 432.0 MiB
28991029248: 29.0 GB 27.0 GiB
1855425871872: 1.9 TB 1.7 TiB
9223372036854775807: 9.2 EB 8.0 EiB (Long.MAX_VALUE)
</code></pre>
","1150","2","2","18","2010-09-21 09:22:21","40","TRUE","161643","0"
"http://stackoverflow.com/users/251173","http://stackoverflow.com/questions/7202616","http://stackoverflow.com/questions/7202616/#7202659","2014-09-11 20:32:26","89","36621","29","8","Java abstract interface","<p>Consider an example (which compiles in java)</p>
<pre><code>public abstract interface Interface {
public void interfacing();
public abstract boolean interfacing(boolean really);
}
</code></pre>
<p>Why is it necessary for an interface to be ""declared"" abstract? Is there other rules that applies with an abstract interface?</p>
<hr>
<p>Finally: If <code>abstract</code> is obsolete, why is it included in Java? Is there a history for abstract interface?</p>
","23","472","<java><interface><abstract>","2011-08-26 09:23:38","TRUE","FALSE","7202659","2013-02-05 20:57:43","222","<blockquote>
<p><em><strong>Why is it necessary for an interface to be ""declared"" abstract?</em></strong></p>
</blockquote>
<p>It's not.</p>
<pre><code>public abstract interface Interface {
\___.__/
|
'----&gt; Neither this...
public void interfacing();
public abstract boolean interfacing(boolean really);
\___.__/
|
'----&gt; nor this, are necessary.
}
</code></pre>
<p>Interfaces and their methods are implicitly <code>abstract</code> and adding that modifier makes no difference.</p>
<blockquote>
<p><em><strong>Is there other rules that applies with an abstract interface?</em></strong></p>
</blockquote>
<p>No, same rules applies. The method must be implemented by any (concrete) implementing class.</p>
<blockquote>
<p><em><strong>If abstract is obsolete, why is it included in Java? Is there a history for abstract interface?</em></strong></p>
</blockquote>
<p>Interesting question. I dug up the <em>first</em> edition of JLS, and even there it says <a href=""http://web.archive.org/web/20091123225637/http://java.sun.com/docs/books/jls/first_edition/html/9.doc.html#30820""><em>""This modifier is obsolete and should not be used in new Java programs""</em></a>.</p>
<p>Okay, <strong>digging even further</strong>... After hitting numerous broken links, I managed to find a copy of the original <a href=""http://en.wikipedia.org/wiki/Oak_%28programming_language%29"">Oak 0.2</a> <a href=""http://www.aoeu.se/so/OakSpec0.2.zip"">Specification</a> (or ""manual""). Quite interesting read I must say, and only 38 pages in total! :-)</p>
<p>Under Section 5, Interfaces, it provides the following example:</p>
<pre><code>public interface Storing {
void freezeDry(Stream s) = 0;
void reconstitute(Stream s) = 0;
}
</code></pre>
<p>And in the margin it says</p>
<blockquote>
<p><em>In the future, the "" =0"" part of declaring methods in interfaces may go away.</em></p>
</blockquote>
<p>Assuming <code>=0</code> got replaced by the <code>abstract</code> keyword, I suspect that <code>abstract</code> was at some point mandatory for interface methods!</p>
","2153","12","2","11","2011-08-26 09:26:58","3","TRUE","161643","0"
"http://stackoverflow.com/users/407418","http://stackoverflow.com/questions/3958955","http://stackoverflow.com/questions/3958955/#3958979","2013-07-21 01:52:42","61","61333","27","6","How to remove duplicate white spaces in string using Java?","<p>How to remove duplicate white spaces (including tabs, newlines, spaces, etc...) in a string using Java?</p>
","58","111","<java><string><whitespace>","2010-10-18 12:09:38","FALSE","FALSE","3958979","2011-10-19 14:05:16","180","<p>Like this:</p>
<pre><code>yourString = yourString.replaceAll(""\\s+"", "" "");
</code></pre>
<p>For example</p>
<pre><code>System.out.println(""lorem ipsum dolor \n sit."".replaceAll(""\\s+"", "" ""));
</code></pre>
<p>outputs</p>
<pre><code>lorem ipsum dolor sit.
</code></pre>
<hr>
<p><strong>What does that <code>\s+</code> mean?</strong></p>
<p><code>\s+</code> is a regular expression. <code>\s</code> matches a space, tab, new line, carriage return, form feed or vertical tab, and <code>+</code> says ""one or more of those"". Thus the above code will collapse all ""whitespace substrings"" longer than one character, with a single space character.</p>
","659","5","3","11","2010-10-18 12:13:02","4","TRUE","161643","0"
"http://stackoverflow.com/users/95122","http://stackoverflow.com/questions/2062020","http://stackoverflow.com/questions/2062020/#2062036","2014-08-08 10:48:20","233","242655","51","8","How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?","<p>How can I tell if the JVM my application runs in is 32 bit or 64-bit? Specifically, what function or preference do I access to detect this within the program?</p>
","82","168","<java><jvm><jni><64bit><32-bit>","2010-01-14 03:38:29","FALSE","FALSE","2062036","2011-09-09 23:12:17","158","<p>Sun has a Java System property to determine the bitness of the JVM: 32 or 64:</p>
<pre><code>sun.arch.data.model=32 // 32 bit JVM
sun.arch.data.model=64 // 64 bit JVM
</code></pre>
<p>You can use</p>
<pre><code>System.getProperty(""sun.arch.data.model"")
</code></pre>
<p>to determine if its 32/64 from the program.</p>
<p>From the <a href=""http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#64bit_detection"">sun.docs</a>:</p>
<blockquote>
<p>When writing Java code, how do I
distinguish between 32 and 64-bit
operation?</p>
<p>There's no public API that allows you
to distinguish between 32 and 64-bit
operation. Think of 64-bit as just
another platform in the write once,
run anywhere tradition. However, if
you'd like to write code which is
platform specific (shame on you), the
system property sun.arch.data.model
has the value ""32"", ""64"", or
""unknown"".</p>
</blockquote>
<p>The only good reason is if your java
code is dependent upon native libraries
and your code needs to determine which
version (32 or 64bit) to load on startup.</p>
","1093","7","2","8","2010-01-14 03:44:31","6","TRUE","160665","8"
"http://stackoverflow.com/users/75863","http://stackoverflow.com/questions/2663115","http://stackoverflow.com/questions/2663115/#2663147","2014-08-05 08:05:46","170","44143","126","19","How to detect a loop in a linked list?","<p>Say you have a linked list structure in Java. It's made up of Nodes:</p>
<pre><code>class Node {
Node next;
// some user data
}
</code></pre>
<p>and each Node points to the next node, except for the last Node, which has null for next. Say there is a possibility that the list can contain a loop - i.e. the final Node, instead of having a null, has a reference to one of the nodes in the list which came before it.</p>
<p>What's the best way of writing</p>
<pre><code>boolean hasLoop(Node first)
</code></pre>
<p>which would return <code>true</code> if the given Node is the first of a list with a loop, and <code>false</code> otherwise? How could you write so that it takes a constant amount of space and a reasonable amount of time?</p>
<p>Here's a picture of what a list with a loop looks like:</p>
<p><img src=""http://i.stack.imgur.com/irw1S.jpg"" alt=""alt text""></p>
","38","891","<java><algorithm><data-structures><linked-list>","2010-04-18 17:08:53","TRUE","FALSE","2663147","2013-07-21 12:12:22","231","<p>You can make use of <a href=""http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare""><strong>Floyd's cycle-finding algorithm</strong></a>, also know as <em>tortoise and hare algorithm</em>.<br><br>
The idea is to have two references to the list and move them at <strong>different speeds</strong>. Move one forward by <code>1</code> node and the other by <code>2</code> nodes. </p>
<ul>
<li>If the linked list has a loop they
will <em>definitely</em> meet.</li>
<li>Else either of
the two references(or their <code>next</code>)
will become <code>null</code>.</li>
</ul>
<p>Java function implementing the algorithm:</p>
<pre><code>boolean hasLoop(Node first) {
if(first == null) // list does not exist..so no loop either.
return false;
Node slow, fast; // create two references.
slow = fast = first; // make both refer to the start of the list.
while(true) {
slow = slow.next; // 1 hop.
if(fast.next != null)
fast = fast.next.next; // 2 hops.
else
return false; // next node null =&gt; no loop.
if(slow == null || fast == null) // if either hits null..no loop.
return false;
if(slow == fast) // if the two ever meet...we must have a loop.
return true;
}
}
</code></pre>
","1325","2","1","15","2010-04-18 17:18:24","10","TRUE","160665","45"
"http://stackoverflow.com/users/488469","http://stackoverflow.com/questions/4030928","http://stackoverflow.com/questions/4030928/#4030936","2013-09-24 16:43:55","45","45240","12","6","Extract digits from a string in Java","<p>I have a Java <code>String</code> object. I need to extract only digits from it. I'll give an example:</p>
<p><code>""123-456-789""</code> I want <code>""123456789""</code></p>
<p>Is there a library function that extracts only digits?</p>
<p>Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?</p>
","36","354","<java><string>","2010-10-27 07:41:35","FALSE","FALSE","4030936","2013-09-24 16:43:55","127","<p>You can use regex and delete non-digits.</p>
<pre><code>str = str.replaceAll(""\\D+"","""");
</code></pre>
<p><a href=""http://www.ideone.com/757Vh""><strong>Working link</strong></a></p>
","187","2","1","9","2010-10-27 07:43:08","2","TRUE","160665","0"
"http://stackoverflow.com/users/506703","http://stackoverflow.com/questions/4172580","http://stackoverflow.com/questions/4172580/#4172612","2014-06-06 18:53:18","37","6296","31","12","Interview question - Search in sorted array X for index i such that X[i] = i","<p>I was asked the following question in my interview yesterday:</p>
<p>Consider a Java or C++ array say <code>X</code> which is sorted and no two elements in it are same. How best can you find an index say <code>i</code> such that element at that index is also <code>i</code>. That is <code>X[i] = i</code>.</p>
<p>As clarification she also gave me an example:</p>
<pre><code> Array X : -3 -1 0 3 5 7
index : 0 1 2 3 4 5
Answer is 3 as X[3] = 3.
</code></pre>
<p>The best I could think was a linear search. After the interview I though a lot on this problem but could not find any better solution. My argument is: the element with the required property can be anywhere in the array. So it could also be at the very end of the array so we need to check every element.</p>
<p>I just wanted to confirm from the community here that I'm right. Please tell me I'm right :)</p>
<p>Thanks</p>
","76","915","<java><c++><arrays><algorithm>","2010-11-13 12:52:10","TRUE","FALSE","4172612","2010-11-14 16:13:49","84","<p>This can be done in <code>O(logN)</code> time and <code>O(1)</code> space by using a slightly modified <a href=""http://en.wikipedia.org/wiki/Binary_search_algorithm"">binary search</a>.</p>
<p>Consider a new array <code>Y</code> such that <code>Y[i] = X[i] - i</code></p>
<pre><code>Array X : -3 -1 0 3 5 7
index : 0 1 2 3 4 5
Array Y : -3 -2 -2 0 1 2
</code></pre>
<p>Since the elements in <code>X</code> are in <em>increasing</em> order, the elements in the
new array <code>Y</code> will be in <em>non-decreasing</em> order. So a <strong>binary
search</strong> for <code>0</code> in <code>Y</code> will give the answer.</p>
<p>But creating <code>Y</code> will take <code>O(N)</code> space and <code>O(N)</code> time. So instead of
creating the new array you just modify the binary search such that a
reference to <code>Y[i]</code> is replaced by <code>X[i] - i</code>.</p>
<p>Algorithm:</p>
<pre><code>function (array X)
low = 0
high = (num of elements in X) - 1
while(low &lt;= high)
mid = (low + high) / 2
// change X[mid] to X[mid] - mid
if(X[mid] - mid == 0)
return mid
// change here too
else if(X[mid] - mid &lt; 0)
low = mid + 1;
else
high = mid - 1;
end while
return -1 // no such index exists...return an invalid index.
end function
</code></pre>
<p><a href=""http://www.ideone.com/ET7jq""><strong>Java implementation</strong></a><br><br>
<a href=""http://www.ideone.com/cadWQ""><strong>C++ implementation</strong></a></p>
","1660","6","2","15","2010-11-13 12:57:32","5","TRUE","160665","0"
"http://stackoverflow.com/users/44522","http://stackoverflow.com/questions/2357315","http://stackoverflow.com/questions/2357315/#2357351","2011-02-12 19:50:44","25","1697","10","3","Does Java's toLowerCase() preserve original string length?","<p>Assume two Java String objects:</p>
<pre><code>String str = ""&lt;my string&gt;"";
String strLower = str.toLowerCase();
</code></pre>
<p>Is it then true that for every value of <code>&lt;my string&gt;</code> the expression</p>
<pre><code>str.length() == strLower.length()
</code></pre>
<p>evaluates to <code>true</code>?</p>
<p>So, does <code>String.toLowerCase()</code> preserve original string length for any value of String?</p>
","58","438","<java><string><string-length>","2010-03-01 16:32:44","TRUE","FALSE","2357351","2010-04-14 16:58:33","36","<p>Surprisingly it does <strong>not</strong> !!</p>
<p>From Java docs of <a href=""http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#toLowerCase%28%29"">toLowerCase</a></p>
<blockquote>
<p>Converts all of the characters in this String to lower case using the rules of the given Locale. Case mappings rely heavily on the Unicode specification's character data. <strong>Since case mappings are not always 1:1 char mappings, the resulting String may be a different length than the original String.</strong> </p>
</blockquote>
<p><strong>Example:</strong> </p>
<pre><code>package com.stackoverflow.q2357315;
import java.util.Locale;
public class Test {
public static void main(String[] args) throws Exception {
Locale.setDefault(new Locale(""lt""));
String s = ""\u00cc"";
System.out.println(s + "" ("" + s.length() + "")""); // Ì (1)
s = s.toLowerCase();
System.out.println(s + "" ("" + s.length() + "")""); // i̇̀ (3)
}
}
</code></pre>
","989","4","1","4","2010-03-01 16:38:25","6","TRUE","160665","0"
"http://stackoverflow.com/users/293299","http://stackoverflow.com/questions/2441524","http://stackoverflow.com/questions/2441524/#2442640","2010-03-21 12:25:37","9","5753","5","4","Closest Ruby representation of a 'private static final' and 'public static final' class variable in Java?","<p>Given the Java code below, what's the closest you could represent these two <code>static final</code> variables in a Ruby class? And, is it possible in Ruby to distinguish between <code>private static</code> and <code>public static</code> variables as there is in Java?</p>
<pre><code>public class DeviceController
{
...
private static final Device myPrivateDevice = Device.getDevice(""mydevice"");
public static final Device myPublicDevice = Device.getDevice(""mydevice"");
...
public static void main(String args[])
{
...
}
}
</code></pre>
","105","559","<java><ruby><static><private><public>","2010-03-14 07:44:00","TRUE","FALSE","2442640","2010-03-21 12:25:37","29","<p>There really is no equivalent construct in Ruby.</p>
<p>However, it looks like you are making one of the classic porting mistakes: you have a <em>solution</em> in language A and try to translate that into language B, when what you really should do is figure out the <em>problem</em> and then figure out how to solve it in language B.</p>
<p>I can't really be sure what the problem is you are trying to solve from that small codesnippet, but here is <em>one</em> possible idea for how to implement it in Ruby:</p>
<pre><code>class DeviceController
class &lt;&lt; self
def my_public_device; @my_public_device ||= Device['mydevice'] end
private
def my_private_device; @my_private_device ||= Device['mydevice'] end
end
end
</code></pre>
<p>Here's another:</p>
<pre><code>class DeviceController
@my_public_device ||= Device['mydevice']
@my_private_device ||= Device['mydevice']
class &lt;&lt; self
attr_reader :my_public_device, :my_private_device
private :my_private_device
end
end
</code></pre>
<p>(The difference is that the first example is lazy, it only initializes the instance variable when the corresponding attribute reader is first called. The second one initializes them as soon as the class body is executed, even if they are never needed, just like the Java version does.)</p>
<p>Let's go over some of the concepts here.</p>
<p>In Ruby, as in every other ""proper"" (for various definitions of ""proper"") object-oriented language, state (instance variables, fields, properties, slots, attributes, whatever you want to call them) is <em>always</em> private. There is <em>no way</em> to access them from the outside. The only way to communicate with an object is by sending it messages.</p>
<p>[Note: Whenever I write something like ""no way"", ""always"", ""the only way"" etc., it actually no means ""no way, except for reflection"". In this particular case, there is <code>Object#instance_variable_set</code>, for example.]</p>
<p>In other words: in Ruby, variables are always private, the only way to access them is via a getter and/or setter method, or, as they are called in Ruby, an attribute reader and/or writer.</p>
<p>Now, I keep writing about <em>instance variables</em>, but in the Java example we have <em>static fields</em>, i.e. <em>class</em> variables. Well, in Ruby, unlike Java, classes are objects, too. They are instances of the <code>Class</code> class and so, just like any other object, they can have instance variables. So, in Ruby, the equivalent to a class variable is really just a standard instance variable which belongs to an object which just happens to be a class.</p>
<p>(There are also class hierarchy variables, denoted with a double at sign <code>@@sigil</code>. Those are really weird, and you should probably just ignore them. Class hierarchy variables are shared across the entire class hierarchy, i.e. the class they belong to, all its subclasses and their subclasses and their subclasses ... and also all instances of all of those classes. Actually, they are more like global variables than class variables. They should really be called <code>$$var</code> instead of <code>@@var</code>, since they are much more closely related to global variables than instance variables. They are not entirely useless but only very rarely useful.)</p>
<p>So, we have covered the ""field"" part (Java field == Ruby instance variable), we have covered the ""public"" and ""private"" parts (in Ruby, instance variables are always private, if you want to make them public, use a public getter/setter method) and we have covered the ""static"" part (Java static field == Ruby class instance variable). What about the ""final"" part?</p>
<p>In Java, ""final"" is just a funny way of spelling ""const"", which the designers avoided because the <code>const</code> keyword in languages like C and C++ is subtly broken and they didn't want to confuse people. Ruby <em>does</em> have constants (denoted by starting with a capital letter). Unfortunately, they are not really constant, because trying to modify them, while generating a warning, actually works. So, they are more of a convention than a compiler-enforced rule. However, the more important restriction of constants is that they are always public.</p>
<p>So, constants are almost perfect: they cannot be modified (well, they <em>shouldn't</em> be modified), i.e. they are <code>final</code>, they belong to a class (or module), i.e. they are <code>static</code>. But they are always <code>public</code>, so unfortunately they cannot be used to model <code>private static final</code> fields.</p>
<p>And this is exactly the point where thinking about problems instead of solutions comes in. What is it that you want? You want state that </p>
<ol>
<li>belongs to a class, </li>
<li>can only be read not written, </li>
<li>is only initialized once and </li>
<li>can be either private or public.</li>
</ol>
<p>You can achieve all of that, but in a completely different way than in Java:</p>
<ol>
<li>class instance variable</li>
<li>don't provide a setter method, only a getter</li>
<li>use Ruby's <code>||=</code> compound assignment to assign only once</li>
<li>getter method</li>
</ol>
<p>The only thing you have to worry about, is that you don't assign to <code>@my_public_device</code> anywhere, or better yet, don't access it at all. Always use the getter method.</p>
<p>Yes, this <em>is</em> a hole in the implementation. Ruby is often called a ""grown-up's language"" or a ""consenting adults language"", which means that instead of having the compiler enforce certain things, you just put them in the documentation and simply trust that your fellow developers have learned that touching other people's privates is rude ...</p>
<hr>
<p>A totally <em>different</em> approach to privacy is the one used in functional languages: use closures. Closures are blocks of code that close over their lexical environment, even after that lexical environment has gone out of scope. This method of implementing private state is very popular in Scheme, but has recently also been popularized by Douglas Crockford et al. for JavaScript. Here's an example in Ruby:</p>
<pre><code>class DeviceController
class &lt;&lt; self
my_public_device, my_private_device = Device['mydevice'], Device['mydevice']
define_method :my_public_device do my_public_device end
define_method :my_private_device do my_private_device end
private :my_private_device
end # &lt;- here the variables fall out of scope and can never be accessed again
end
</code></pre>
<p>Note the subtle but important difference to the versions at the top of my answer: the lack of the <code>@</code> sigil. Here, we are creating <em>local</em> variables, not <em>instance</em> variables. As soon as the class body ends, those local variables fall out of scope and can never be accessed ever again. <em>Only</em> the two blocks which define the two getter methods still have access to them, because they close over the class body. Now, they are <em>really</em> private <em>and</em> they are <code>final</code>, because the only thing in the entire program which still has access to them is a pure <em>getter</em> method.</p>
<p>This is probably not idiomatic Ruby, but for anyone with a Lisp or JavaScript background it should be clear enough. It is also very elegant.</p>
","7362","21","3","2","2010-03-14 15:32:41","468","TRUE","159575","0"
"http://stackoverflow.com/users/704336","http://stackoverflow.com/questions/5637410","http://stackoverflow.com/questions/5637410/#5637823","2011-04-12 15:35:00","2","96","0","2","Retrieving Java list from ruby","<p>My service(written in Java) returns me an output in the format:</p>
<pre><code> ""serviceMetricList"":
[
{""MetricDataList"":
{""metricDataList"":
[
{""metricDate"": ""2011-04-05T14:50:00.000Z"",
""metricValue"": ""427448.0""},
{""metricDate"": ""2011-04-12T14:30:00.000Z"",
""metricValue"": ""430089.0""}
]
},
""urlSerialNo"": ""1""}
}
]
</code></pre>
<p>I need to retrieve the values metricDate and metricValue from my Ruby client. Am not sure about how this can be done. Any help in this regard will be great.</p>
","30","591","<java><ruby><list>","2011-04-12 15:06:14","TRUE","FALSE","5637823","2011-04-12 15:35:00","4","<p>If you want to parse this data format, you first need to know what data format it is. It doesn't appear to be any well-known data format and it's not any format I know. It's obviously not JSON, nor is it YAML and definitely not XML.</p>
<p>So, you'll probably have to write your own parser. Or a preprocessor which converts the data into a more well-known format, for wich a parser already exists.</p>
<p>For example, if you were to convert the example to YAML, it would look something like this:</p>
<pre><code>""serviceMetricList"":
[
{""MetricDataList"":
{""metricDataList"":
[
{""metricDate"": ""2011-04-05T14:50:00.000Z"",
""metricValue"": ""427448.0""},
{""metricDate"": ""2011-04-12T14:30:00.000Z"",
""metricValue"": ""430089.0""}
]
},
""urlSerialNo"": ""1""
}
]
</code></pre>
<p>And you could parse it like this:</p>
<pre><code>require 'yaml'
h = YAML.load(your_java_data)
Date.parse(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricDate'])
# =&gt; #&lt;Date: 2011-04-05 (4911313/2,0,2299161)&gt;
Float(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricValue'])
# =&gt; 427448.0
# or maybe, if you don't like to lose precision:
require 'bigdecimal'
BigDecimal(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricValue'])
# =&gt; #&lt;BigDecimal:eb8240,'0.427448E6',8(12)&gt;
</code></pre>
","1442","4","2","1","2011-04-12 15:35:00","29","TRUE","159575","0"
"http://stackoverflow.com/users/934913","http://stackoverflow.com/questions/16457370","http://stackoverflow.com/questions/16457370/#16464640","2013-05-09 14:48:09","2","1853","3","4","Is Ruby pass-by-value or pass-by-reference?","<p>I am basically a java developer. I am working in ruby for about an year. Unlike java, Ruby is a pure object oriented programming language. Here comes a doubt. Is it pass-by-value or pass-by-reference? Java works as pass-by-value: ""When passing primitives, I see that the value is duplicated and passed to the method. But incase of Objects, the reference is duplicated and passed to the method. The reference contains the location of the object in the heap. During the method call, only the location of the object is passed. So no duplicate objects are created. The same object is modified."" </p>
<p>But when I tried the below ruby code snippet, I got the same results as I got in Java: ""The numbers work like a primitive (like in java) during a method call whereas the array works as perfect references like in java"". Now, I am confused. If everything in ruby are objects, then why the number objects are duplicated during the method call?</p>
<pre><code>class A
def meth1(a)
a = a+5
puts ""a inside meth1---#{a}""
end
def meth2(array)
array.pop
puts ""array inside meth2---#{array}""
end
end
obj1 = A.new
aa=5
obj1.meth1(aa)
puts ""aa-----#{aa}""
arr = [3,4,5]
obj1.meth2(arr)
puts ""arr---#{arr}""
</code></pre>
<p>Results:</p>
<p>a inside meth1---10</p>
<p>aa-----5</p>
<p>array inside meth2---34</p>
<p>arr---34</p>
","43","1326","<java><ruby><oop><pass-by-reference><pass-by-value>","2013-05-09 08:16:55","TRUE","FALSE","16464640","2013-05-09 14:48:09","11","<p>Ruby uses pass-by-value, or more precisely, a special case of pass-by-value where the value being passed is <em>always</em> a pointer. This special case is also sometimes known as call-by-sharing, call-by-object-sharing or call-by-object.</p>
<p>It's the same convention that is used by Java (for objects), C# (by default for reference types), Smalltalk, Python, ECMAScript/JavaScript and more or less every object-oriented language ever created.</p>
<p>Note: on all existing Ruby implementations <code>Symbol</code>s, <code>Fixnum</code>s and <code>Float</code>s are actually passed <em>directly</em> by value and <em>not</em> with an intermediary pointer. However, since those three are immutable, there is no observable behavioral difference between pass-by-value and call-by-object-sharing in this case, so you can greatly simplify your mental model by simply treating <em>everything</em> as call-by-object-sharing. Just interpret these three special cases as internal compiler optimizations that you don't need to worry about.</p>
<p>Here's a simple example you can run to determine the argument passing convention of Ruby (or any other language, after you translate it):</p>
<pre><code>def is_ruby_pass_by_value?(foo)
foo.replace('More precisely, it is call-by-object-sharing!')
foo = 'No, Ruby is pass-by-reference.'
return nil
end
bar = 'Yes, of course, Ruby *is* pass-by-value!'
is_ruby_pass_by_value?(bar)
p bar
# 'More precisely, it is call-by-object-sharing!'
</code></pre>
","1502","4","1","1","2013-05-09 14:48:09","392","TRUE","159575","0"
"http://stackoverflow.com/users/1022209","http://stackoverflow.com/questions/14988918","http://stackoverflow.com/questions/14988918/#14990639","2013-02-20 22:52:35","1","235","1","3","How to loop elements in 2d array to construct an string in ""Ruby functional Style""","<p>Ruby use the functions from ""functional concept"" heavily, such as <strong>map, each</strong>. They really depend on a <strong>self-contained function</strong> which is so called <strong>block</strong> in Ruby.</p>
<p>It is very common to loop though a 2d array, make an string about the elements.</p>
<p>In java, it may looks like</p>
<pre><code> public String toString(){
String output = ""["";
for (int i =0; i&lt;array.length; i++) {
output+= ""Row ""+(i+1)+"" : "";
for (int j=0; j&lt;array[0].length;j++ ) {
output += array[i][j]+"", "";
}
output += ""\n"";
}
return output += ""]"";
}
</code></pre>
<p>I tried to rewrite such a thing in ""Ruby functional Style"", but I think there are still some improvements. Eg. I want to remove the mutable variable <strong>output</strong> </p>
<pre><code> def to_s
output = ""[\n""
@data.each_with_index do |row,i|
output &lt;&lt; ""Row #{i+1} : ""
row.each { |num| output &lt;&lt; ""#{num},"" }
output &lt;&lt; ""\n""
end
output+""]""
end
</code></pre>
","82","1162","<java><ruby><functional-programming><ruby-1.9.3>","2013-02-20 20:06:02","TRUE","FALSE","14990639","2013-02-20 22:52:35","3","<p>Whenever you see the pattern:</p>
<ol>
<li>initialize an accumulator (in your case <code>output</code>)</li>
<li>on each iteration of some collection modify the accumulator (in your case append to it)</li>
<li>return the accumulator</li>
</ol>
<p>that's a <code>fold</code>, or in Ruby terms an <code>inject</code>.</p>
<p>Actually, that's a bit of a tautology. A <code>fold</code> is a universal method of iteration: <em>everything</em> that can be expressed by iterating over the elements of a collection can also be expressed as a <code>fold</code> over the collection. In other words: <em>all</em> methods on <code>Enumerable</code> (including <code>each</code>!) could also be defined in terms of <code>inject</code> as the primitive method instead of <code>each</code>.</p>
<p>Think about it this way: a collection can either be empty or there can be a current element. There's no third option, if you cover those two cases, then you have covered everything. Well, <code>fold</code> takes two arguments: one which tells it what to do when the collection is empty, and one which tells it what to do with the current element. Or, put yet another way: you can see a collection as a series of instructions and <code>fold</code> is an interpreter for those instructions. There are only two kinds of instructions: the <code>END</code> instruction and a <code>VALUE(el)</code> instruction. And you can supply the interpreter code for both those instructions to the <code>fold</code>.</p>
<p>In Ruby, the second argument is not part of the argument list, it is the block.</p>
<p>So, what's it look like as a <code>fold</code>?</p>
<pre><code>def to_s
@data.each_with_index.inject(""[\n"") do |acc, (row, i)|
acc + ""Row #{i+1} : #{row.join(',')}\n""
end + ']'
end
</code></pre>
<p>If you're curious about whether or not the <code>each_with_index</code> may infect your code with some non-functional impurity, rest assured that you can just as easily get rid of it by including the index in the accumulator:</p>
<pre><code>def to_s
@data.inject([""[\n"", 1]) do |(s, i), row|
[s + ""Row #{i} : #{row.join(',')}\n"", i+1]
end.first + ']'
end
</code></pre>
<p>Also note that in the first case, <em>with</em> the <code>each_with_index</code>, we're not actually doing anything ""interesting"" with the accumulator, unlike the second case, where we are using it to keep count of the index. In fact, the first case is actually a restricted form of <code>fold</code>, it doesn't use all of its power. It really is just a <code>map</code>:</p>
<pre><code>def to_s
""[\n"" + @data.map.with_index(1) do |row, i|
""Row #{i} : #{row.join(',')}\n""
end.join + ']'
end
</code></pre>
<p>In my personal opinion, it would actually be perfectly okay to use (mutable) string appending here instead of string concatenation:</p>
<pre><code>def to_s
""[\n"" &lt;&lt; @data.map.with_index(1) do |row, i|
""Row #{i} : #{row.join(',')}\n""
end.join &lt;&lt; ']'
end
</code></pre>
<p>This saves us from creating a couple of unnecessary string objects, but more importantly: it is more idiomatic. The real problem is <em>shared</em> mutable state, but we're not sharing our mutable string here: when <code>to_s</code> returns its caller <em>does</em> get access to the string, but <code>to_s</code> itself has returned and thus no longer has access to it.</p>
<p>If you want to get real fancy, you could even use string interpolation:</p>
<pre><code>def to_s
%Q&lt;[\n#{@data.map.with_index(1) do |row, i|
""Row #{i} : #{row.join(',')}\n""
end.join}]&gt;
end
</code></pre>
<p>Unfortunately, this not only breaks IRb's syntax highlighting, but also my brain's ;-)</p>
","3679","12","5","4","2013-02-20 21:52:51","106","TRUE","159575","0"
"http://stackoverflow.com/users/123603","http://stackoverflow.com/questions/1157235","http://stackoverflow.com/questions/1157235/#1157244","2010-04-04 15:39:56","8","736","1","9","Is this a good practice? ""/*/something/*/something//*/""","<pre><code>/*/ comment here
do some thing.
/*/
do some thing.
//*/
</code></pre>
<p>Why people write code like that? Is this a good practice?</p>
","55","147","<java><c++><c><coding-style><comments>","2009-07-21 03:56:52","TRUE","FALSE","1157244","2010-04-04 15:39:56","23","<p>It's usually only used when testing something out for the moment. That is, you should never commit code like that to version control, because it can be confusing.</p>
<p>For example, if you are testing two different computation methods, you can use this to switch between them. Personally I have rarely done this, if at all.</p>
<p><hr /></p>
<p>For those that don't know, you can toggle between the two code sections by adding one forward slash:</p>
<pre><code>/*/ comment here
do some thing.
/*/
do some thing else.
//*/
//*/ comment here
do some thing.
/*/
do some thing else.
//*/
</code></pre>
","607","4","1","6","2009-07-21 04:03:09","7","TRUE","159428","0"
"http://stackoverflow.com/users/751637","http://stackoverflow.com/questions/14094157","http://stackoverflow.com/questions/14094157/#14094181","2012-12-30 20:33:48","4","469","0","4","avoid multiple if conditions","<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href=""http://stackoverflow.com/questions/519422/what-is-the-best-way-to-replace-or-substitute-if-else-if-else-trees-in-program"">What is the best way to replace or substitute if..else if..else trees in programs?</a> </p>
</blockquote>
<p>How can I avoid multiple if conditions? For example:</p>
<pre><code>Public void search(String a,b,c,d,e)
String aTerm;
</code></pre>
<p>Now which of the single and multiple combinations of passed arguments contain ""aTerm""? For example the output could be following:</p>
<pre><code>1 - aTerm appears in ""a"" only
2 - aTerm appears in ""a,c"", and ""e""
3 - aTerm appears in ""d"" and ""e""
</code></pre>
<p>For each single or possible combination I want to call a specific function. I wrote so many if conditions but it looks bad. For example:</p>
<pre><code>If(aTerm. equalsIgnoreCase(a)){ call function a();}
If(aTerm. equalsIgnoreCase(b)){ call function b();}
If(aTerm. equalsIgnoreCase(b) and aTerm. equalsIgnoreCase(b)){ call function ab();}
…………………… and so on………………………….
</code></pre>
<p>Is there any cleaner way to do it? Solution could be in PHP or Java.</p>
","28","1168","<java><php>","2012-12-30 20:01:17","TRUE","FALSE","14094181","2012-12-30 20:33:48","1","<p>Build a string and call the method by the string's name:</p>
<pre><code>// Psuedo-code
str = """";
If( aTerm.equalsIgnoreCase(a)) str += ""a"";
If( aTerm.equalsIgnoreCase(b)) str += ""b"";
If( aTerm.equalsIgnoreCase(c)) str += ""c"";
If( aTerm.equalsIgnoreCase(d)) str += ""d"";
If( aTerm.equalsIgnoreCase(e)) str += ""e"";
call function named by str
</code></pre>
","357","1","1","4","2012-12-30 20:05:35","4","TRUE","158065","0"
"http://stackoverflow.com/users/2859840","http://stackoverflow.com/questions/19746680","http://stackoverflow.com/questions/19746680/#19746717","2013-11-03 02:13:32","0","84","1","2","Boolean value not working, need a fix? (Fixed)","<p>What i want is to output A or Z.</p>
<p>Everything else between A and Z works except A and Z, i tried to add an ""else if""
with equals and &amp;&amp; but it's not working.</p>
<p>The ""System.out.println(ConvertLetterToDigit(num2));""
takes the input and transfers it into a switch that'll give back an ""int"" value.</p>
<p>If you need more infos, please comment below ._.</p>
<pre><code> char num1;
char num2;
String num3;
String equality;
System.out.println(""\nThis game consists of inputting a digit and we will output the character linked to that digit."");
do
{
System.out.println(""Please input a letter."");
equality= ""^[a-zA-Z](1)"";
num3 = console.next();
if (num3.length() &lt; 2);
{
if (num3.matches(equality))
{
num2 = (char)num3.charAt(0);
System.out.println(ConvertLetterToDigit(num2));
}
else if (num3.length() &gt; 1)
{
System.out.println(""We said 1 letter."");
}
else
{
System.out.println(""What do you think you're doing."");
}
}
} while (!num3.matches(equality));
break;
</code></pre>
","46","1055","<java><boolean>","2013-11-02 20:46:41","TRUE","FALSE","19746717","2013-11-03 02:13:32","3","<p>If I understand correctly, you want to check that your input is indeed a letter between <code>a</code> and <code>z</code>.</p>
<p>In that case, your <code>if</code> should be:</p>
<pre><code>if( num2 &gt;= 'a' &amp;&amp; num2 &lt;= 'z') {
// okay, do something
}
else {
// show error message
}
</code></pre>
","321","2","1","4","2013-11-02 20:50:11","4","TRUE","158065","0"
"http://stackoverflow.com/users/1222197","http://stackoverflow.com/questions/17602804","http://stackoverflow.com/questions/17602804/#17602886","2013-07-11 20:57:15","0","92","0","1","Regular Expression negative lookahead for Vowels","<p>I would like a Java regular expression string that finds all vowels in a string unless they:</p>
<ol>
<li>are the first character or </li>
<li>the next character following an underscore</li>
</ol>
<p>AREA_ID becomes<br>
AR_ID</p>
<p>LONG_NAME becomes<br>
LNG_NM</p>
<p>HOME_ALONE becomes<br>
HM_ALN</p>
<p>I have played around with <a href=""http://gskinner.com/RegExr"" rel=""nofollow"">http://gskinner.com/RegExr</a> and
I currently have the following regex that replaces all vowels except if it is the starting character</p>
<pre><code>(?!^[AEIOU])[AEIOU]
</code></pre>
<p>I can't figure out how to get the second part (ignore vowel immediately following an underscore).</p>
","48","684","<java><regex>","2013-07-11 20:24:48","TRUE","FALSE","17602886","2013-07-11 20:57:15","1","<p>I'm guessing you're using JavaScript, in which case this will do:</p>
<pre><code>(?!(?:^|_))_?[AEIOU]
</code></pre>
<p>However, if you're using a regex flavour that supports lookbehinds, try this:</p>
<pre><code>(?&lt;!^)(?&lt;!_)[AEIOU]
</code></pre>
<p>Note that two lookbehinds are needed because a lookbehind must have a fixed length, which ""either the start of the string or an underscore"" does not.</p>
","416","3","2","1","2013-07-11 20:30:21","6","TRUE","158065","0"
"http://stackoverflow.com/users/358438","http://stackoverflow.com/questions/7443235","http://stackoverflow.com/questions/7443235/#7443373","2011-09-16 10:31:38","3","2562","0","1","Getting Java to accept all certs over HTTPS","<p>I'm trying to get Java to accept all certs over HTTPS. This is for testing purposes. Before I was getting a cert not found error. However, after adding the following code before my code I get a <code>HTTPS hostname wrong: should be &lt;sub.domain.com&gt;</code> error. The problem is my url <strong>IS</strong> that url. How do I get around this issue? The below is the code I've added to attempt to fix the problem..</p>
<pre><code> // Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance(""SSL"");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
</code></pre>
","43","1325","<java><ssl><https>","2011-09-16 10:17:33","TRUE","FALSE","7443373","2011-09-16 10:31:38","4","<p>You need to set the a HostNameVarifier also
Ex:</p>
<pre><code>import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class TrustAllHostNameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
</code></pre>
<p>Then</p>
<pre><code> httpsConnection.setHostnameVerifier(new TrustAllHostNameVerifier ());
</code></pre>
","428","2","2","2","2011-09-16 10:31:38","14","TRUE","157584","0"
"http://stackoverflow.com/users/979051","http://stackoverflow.com/questions/14432115","http://stackoverflow.com/questions/14432115/#14432157","2013-01-21 13:30:01","3","646","0","1","Spring Hello World Web App","<p>I am trying out Spring Framework for a web app and can't seem to have it work with a simple hello world MVC web app. Using Spring 3.2, Tomcat 6 (context set as ""/spring""). Maybe the annotated Controller class is not found?</p>
<p>I am hitting <code>http://localhost:8080/spring/hello</code></p>
<p>web.xml</p>
<pre><code>&lt;?xml version=""1.0"" encoding=""ISO-8859-1""?&gt;
&lt;web-app version=""2.4""
xmlns=""http://java.sun.com/xml/ns/j2ee""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xsi:schemaLocation=""http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"" &gt;
&lt;display-name&gt;
Spring
&lt;/display-name&gt;
&lt;description&gt;
Spring Test
&lt;/description&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;springapp&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;springapp&lt;/servlet-name&gt;
&lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;/web-app&gt;
</code></pre>
<p>springapp-servlet.xml</p>
<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;beans xmlns=""http://www.springframework.org/schema/beans""
xmlns:context=""http://www.springframework.org/schema/context""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xsi:schemaLocation="" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd""&gt;
&lt;context:component-scan base-package=""com.test.web"" /&gt;
&lt;bean
class=""org.springframework.web.servlet.view.InternalResourceViewResolver""&gt;
&lt;property name=""prefix"" value=""/WEB-INF/jsp/"" /&gt;
&lt;property name=""suffix"" value="".jsp"" /&gt;
&lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<p>My Controller</p>
<pre><code>package com.test.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(""/hello"")
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute(""name"", ""Test"");
return ""hello"";
}
}
</code></pre>
<p>Tomcat Output (springapp-servlet.xml is found and loaded)</p>
<pre><code>INFO: Deploying configuration descriptor spring.xml
Jan 20, 2013 10:22:27 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springapp'
Jan 20, 2013 10:22:27 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'springapp': initialization started
Jan 20, 2013 10:22:27 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'springapp-servlet': startup date [Sun Jan 20 22:22:27 EST 2013]; root of context hierarchy
Jan 20, 2013 10:22:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/springapp-servlet.xml]
Jan 20, 2013 10:22:27 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7897aaa6: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Jan 20, 2013 10:22:27 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'springapp': initialization completed in 321 ms
Jan 20, 2013 10:22:29 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spring/hello] in DispatcherServlet with name 'springapp'
</code></pre>
","26","4578","<java><spring><tomcat><spring-mvc>","2013-01-21 03:27:50","TRUE","FALSE","14432157","2013-01-21 13:30:01","4","<p>You have not enabled the <a href=""http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-config"" rel=""nofollow"">annotated MVC configuration</a></p>
<pre><code>&lt;mvc:annotation-driven /&gt;
</code></pre>
<p>Ex:</p>
<pre><code>&lt;beans xmlns=""http://www.springframework.org/schema/beans""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:context=""http://www.springframework.org/schema/context""
xmlns:mvc=""http://www.springframework.org/schema/mvc""
xsi:schemaLocation=""http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd""&gt;
&lt;context:component-scan base-package=""..."" /&gt;
&lt;mvc:annotation-driven /&gt;
</code></pre>
<p>EDIT:<br />
it was a problem with the classpath of the application as it turned out in the below comments</p>
","1173","3","2","11","2013-01-21 03:32:59","5","TRUE","157584","0"
"http://stackoverflow.com/users/203175","http://stackoverflow.com/questions/4467460","http://stackoverflow.com/questions/4467460/#4467547","2010-12-17 05:54:20","1","199","0","2","A question on how to solve the string problem in Java","<p>I've created a simple xml file here:</p>
<p><a href=""http://roberthan.host56.com/productsNew.xml"" rel=""nofollow"">http://roberthan.host56.com/productsNew.xml</a></p>
<p>which is quite simple, the root node is [products] while all other element nodes are [product]. Under each [product] node, there are two child nodes, [code] and [name], so it basically looks like:</p>
<pre><code>[product]
[code]ddd[/code]
[name]ssss[/name]
[/product]
</code></pre>
<p>I've also written up the following Java code to parse this XML file and take out the text content of the [product] node, and add it to a JComboBox.</p>
<pre><code>docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse(""http://roberthan.host56.com/productsNew.xml"");
NodeList productNodes = doc.getElementsByTagName(""product"");
productlist.clear();
for (i = 0; i &lt; productNodes.getLength(); i++)
{
Node childNode = productNodes.item(i);
if (childNode.hasChildNodes()) {
NodeList nl = childNode.getChildNodes();
Node nameNode = nl.item(2);
productlist.add(nameNode.getTextContent());
}
}
final JComboBox productComboB = new JComboBox();
Iterator iterator = productlist.iterator();
while(iterator.hasNext())
{
productComboB.addItem(iterator.next().toString());
}
</code></pre>
<p>The code is quite straightforward, I firstly parse the xml and get all the product nodes and put them into a nodelist, and the productList is an arrayList. I loop through the all the [product] nodes, for each of them, if it has child nodes, then I take the second child node (which is the [name] node) and put the text content of it in the array list, and finally, I loop through the arrayList and add each item to the combo box.</p>
<p>The problem I got is, if I select the [code] child node, which means ""Node nameNode = nl.item(1)"", it will work perfectly; however, if I change that item(1) to item(2) to extract all the [name] nodes, the combo box will have a drop down list, but all the items are blank, like I have inserted 10 empty strings.</p>
<p>Also, if I try to add a ""Hello World"" string into the combo box after the above code, the ""Hello World"" item will appear after the 10 empty items.</p>
<p>I have spent the whole afternoon debugging this but still no breakthrough, the XML is actually quite simple and the Java is straightforward too. Could anyone share some thoughts with me on this please. Thanks a lot! </p>
","53","2536","<java><xml><xpath>","2010-12-17 03:41:27","TRUE","FALSE","4467547","2010-12-17 05:11:44","4","<p>It is because the node list contains text nodes also.</p>
<p>If you add the following snippet to your code you will find that</p>
<pre><code>for(int j = 0;j&lt;nl.getLength();j++){
System.out.println(nl.item(j).getNodeName());
}
</code></pre>
<p>It will give the following output for each iteration of the product</p>
<pre><code>#text
code
#text
name
#text
</code></pre>
<p>This means you have to get the 3rd element to get the <code>name</code> node.</p>
<pre><code>Node nameNode = nl.item(3);
</code></pre>
<p>But I'll suggest you to use XPath to solve this problem.</p>
<pre><code>NodeList nodelist = XPathAPI.selectNodeList(doc, ""//products/product/name"");
for (int i = 0; i &lt; nodelist.getLength(); i++) {
productlist.add(nodelist.item(i).getTextContent());
}
</code></pre>
","800","5","4","3","2010-12-17 03:56:55","15","TRUE","157584","0"
"http://stackoverflow.com/users/616249","http://stackoverflow.com/questions/18376443","http://stackoverflow.com/questions/18376443/#18376510","2013-08-22 09:42:06","1","1035","0","5","Get Data from JSON String","<p>I'm unable to successfully get data from the JSON string below. Using JavaScript, I'm able to alert the full string [ alert(data); ] but I'm unable to get only the first name.</p>
<p>Can someone please help?</p>
<pre><code>var data = {
""name"": [
""Enid Norgard"",
""Cassie Durrett"",
""Josephine Ervin""
],
""email"": [
""TheWoozyGamer@gmail.com"",
""TheHabitualGamer@gmail.com"",
""TheUptightGamer@gmail.com""
],
""role"": [
""Gamer"",
""Team Leader"",
""Player""
],
""emp_id"": [
""50"",
""408"",
""520""
],
""id"": [
""234"",
""444"",
""235""
]
}
</code></pre>
","25","691","<java><javascript><jquery><json>","2013-08-22 09:23:37","TRUE","FALSE","18376510","2013-08-22 09:31:00","4","<p>Looks like you have a string(because when you use alert the complete text is shown, if it was a object then <code>[Object object]</code> would have shown), first you need to parse it using <a href=""https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse"" rel=""nofollow"">JSON.parse()</a></p>
<pre><code>var t = JSON.parse(data)
alert(t.name[0])
</code></pre>
<p>Note: Old browsers like IE8 which does not have native support for JSON you have to add a library like <a href=""https://github.com/douglascrockford/JSON-js"" rel=""nofollow"">json2</a> to add JSON support</p>
","608","2","1","2","2013-08-22 09:26:21","3","TRUE","157584","0"
"http://stackoverflow.com/users/1759084","http://stackoverflow.com/questions/16610832","http://stackoverflow.com/questions/16610832/#16610901","2013-05-17 14:11:51","1","4291","1","1","Spring + Hibernate + Sql Server connection failing","<p>I am getting the following error when I am using a combination of Spring, Hibernate and SQL Server.</p>
<pre><code>19:17:09,137 ERROR [org.hibernate.tool.hbm2ddl.SchemaValidator] (MSC service thread 1-8) HHH000319: Could not get database metadata: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host falmumapp20/testdb, port 1433 has failed. Error: ""null. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall."".
</code></pre>
<p>It could not be just a TCP IP problem, because if I work without Spring, I am able to connect to SQL Server using hibernate.</p>
<p>Below is my applicationContext.xml</p>
<p>
</p>
<pre><code>&lt;!-- Resource Definition --&gt;
&lt;!-- Data Source Connection Pool --&gt;
&lt;bean id=""myDataSource"" class=""org.springframework.jdbc.datasource.DriverManagerDataSource"" destroy-method=""close""&gt;
&lt;property name=""driverClassName"" value=""com.microsoft.sqlserver.jdbc.SQLServerDriver"" /&gt;
&lt;property name=""url"" value=""jdbc:microsoft:sqlserver://falmumapp20:1433"" /&gt;
&lt;property name=""username"" value=""tima""/&gt;
&lt;property name=""password"" value=""chalk@""/&gt;
&lt;/bean&gt;
&lt;!-- Hibernate SessionFactory --&gt;
&lt;bean id=""mySessionFactory"" class=""org.springframework.orm.hibernate4.LocalSessionFactoryBean""&gt;
&lt;property name=""dataSource"" ref=""myDataSource"" /&gt;
&lt;property name=""mappingDirectoryLocations""&gt;
&lt;list&gt;
&lt;value&gt;classpath:/com/trun/hbm&lt;/value&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;property name=""configLocation""&gt;
&lt;value&gt;classpath:hibernate.cfg.xml&lt;/value&gt;
&lt;/property&gt;
&lt;property name=""hibernateProperties""&gt;
&lt;props&gt;
&lt;prop key=""hibernate.hbm2ddl.auto""&gt;validate&lt;/prop&gt;
&lt;prop key=""hibernate.dialect""&gt;org.hibernate.dialect.SQLServerDialect&lt;/prop&gt;
&lt;prop key=""hibernate.show_sql""&gt;true&lt;/prop&gt;
&lt;/props&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;!--Definition of Transaction Manager--&gt;
&lt;bean id=""myTransactionManager"" class=""org.springframework.orm.hibernate4.HibernateTransactionManager""&gt;
&lt;property name=""sessionFactory"" ref=""mySessionFactory"" /&gt;
&lt;/bean&gt;
</code></pre>
<p>
</p>
<pre><code>&lt;bean id=""IDataService"" class=""com.trun.service.DataServiceImpl""&gt;
&lt;/bean&gt;
&lt;bean id=""EventServlet"" class=""com.trun.servelet.LoginServelet""&gt;
&lt;property name=""IDataDAO"" ref=""IDataDAO"" /&gt;
&lt;/bean&gt;
</code></pre>
<p></p>
<p>And here is my Hibernate Configuration file -</p>
<pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
""-//Hibernate/Hibernate Configuration DTD//EN""
""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd""&gt;
&lt;hibernate-configuration&gt;
&lt;session-factory&gt;
&lt;property name=""hibernate.connection.driver_class""&gt;com.microsoft.sqlserver.jdbc.SQLServerDriver&lt;/property&gt;
&lt;property name=""hibernate.connection.url""&gt;jdbc:sqlserver://falmumapp20:1433;databaseName=testdb; user=tima;password=chalk@;&lt;/property&gt;
&lt;property name=""hibernate.connection.username""&gt;tima&lt;/property&gt;
&lt;property name=""hibernate.connection.password""&gt;chalk@&lt;/property&gt;
&lt;property name=""hibernate.connection.pool_size""&gt;10&lt;/property&gt;
&lt;property name=""show_sql""&gt;true&lt;/property&gt;
&lt;property name=""dialect""&gt;org.hibernate.dialect.SQLServer2008Dialect&lt;/property&gt;
&lt;property name=""hibernate.current_session_context_class""&gt;thread&lt;/property&gt;
&lt;property name=""hibernate.cache.provider_class""&gt;org.hibernate.cache.internal.NoCacheProvider&lt;/property&gt;
&lt;property name=""hibernate.hbm2ddl.auto""&gt;validate&lt;/property&gt;
&lt;!-- Mapping files --&gt;
&lt;/session-factory&gt;
</code></pre>
","50","4107","<java><spring><hibernate>","2013-05-17 13:55:04","TRUE","FALSE","16610901","2013-05-17 14:11:51","4","<p>You are not passing database name to the connection url</p>
<pre><code>&lt;property name=""url"" value=""jdbc:sqlserver://falmumapp20:1433;databaseName=testdb"" /&gt;
</code></pre>
<p>or</p>
<pre><code>&lt;property name=""url"" value=""jdbc:sqlserver://falmumapp20:1433/testdb"" /&gt;
</code></pre>
","297","2","2","3","2013-05-17 13:58:35","3","TRUE","157584","0"
"http://stackoverflow.com/users/1385652","http://stackoverflow.com/questions/15406213","http://stackoverflow.com/questions/15406213/#15406340","2013-03-14 10:11:11","1","1917","0","1","Send Byte array as file in using http client in java","<p>We have byte array of file and we want to upload it as file.
<code>FileBody</code> only gets <code>File</code> as parameter but we have a array of bytes.</p>
<p>One solution is to save byte array into file and then send it
but it is not appropriate for me.</p>
<pre><code>byte b[]= new byte[1000];
//fill b
MultipartEntity form = new MultipartEntity();
form.addPart(""file"", new FileBody(/* b? */));
</code></pre>
<p>thanks.</p>
","52","434","<java><bytearray><httpclient>","2013-03-14 10:05:30","TRUE","FALSE","15406340","2013-03-14 10:11:11","4","<p>You can do something like</p>
<pre><code>HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new InputStreamBody(new ByteArrayInputStream(b), ""my-file.txt"");
form.addPart(""file"", cd);
HttpEntityEnclosingRequestBase post = new HttpPost("""");//If a PUT request then `new HttpPut("""");`
post.setEntity(form);
client.execute(post);
</code></pre>
","406","1","1","3","2013-03-14 10:11:11","6","TRUE","157584","0"
"http://stackoverflow.com/users/728241","http://stackoverflow.com/questions/17205162","http://stackoverflow.com/questions/17205162/#17205177","2013-06-20 05:35:23","0","55","0","2","replace generic with actual class","<p>Is there a way to wrap this ugliness if i have a class that is suitable for a generic?</p>
<p>So this</p>
<pre><code>public HasOne aMethod(Class&lt;? extends Model&gt; clazz){
HasOne&lt;Customer&gt; hasOne = injector.getInstance(Key.get(new TypeLiteral&lt;HasOne&lt;Customer&gt;&gt;() {
}));
return hasOne;
}
</code></pre>
<p>would turn into something like this. (this obviously doesn't compile)</p>
<pre><code>public HasOne aMethod(Class&lt;? extends Model&gt; clazz){
HasOne&lt;clazz&gt; hasOne = injector.getInstance(Key.get(new TypeLiteral&lt;HasOne&lt;clazz&gt;&gt;() {
}));
return hasOne;
}
</code></pre>
","33","646","<java>","2013-06-20 04:15:09","TRUE","FALSE","17205177","2013-06-20 05:35:23","4","<p>why not</p>
<pre><code>public &lt;T extends Model&gt; HasOne&lt;T&gt; aMethod(Class&lt;T&gt; clazz){
HasOne&lt;T&gt; hasOne = injector.getInstance(Key.get(new TypeLiteral&lt;HasOne&lt;T&gt;&gt;() {
}));
return hasOne;
}
</code></pre>
","252","1","1","4","2013-06-20 04:17:15","2","TRUE","157584","0"
"http://stackoverflow.com/users/59087","http://stackoverflow.com/questions/10790795","http://stackoverflow.com/questions/10790795/#10791139","2012-06-15 14:39:00","4","358","0","3","Programmatically switch API naming conventions","<h2>Background</h2>
<p>The <a href=""http://nlp.lsi.upc.edu/freeling/"" rel=""nofollow"">FreeLing</a> API defines an interface that does not adhere to standard Java naming conventions. For example:</p>
<pre><code>package freeling;
public class sentence extends ListWord {
public void set_parse_tree(parse_tree arg0) {
</code></pre>
<p>The interface is defined using <a href=""http://www.swig.org/"" rel=""nofollow"">SWIG</a>, which is similar to <a href=""http://en.wikipedia.org/wiki/Interface_description_language"" rel=""nofollow"">IDL</a>:</p>
<pre><code>class sentence : public std::list&lt;word&gt; {
public:
sentence(void);
void set_parse_tree(const parse_tree &amp;);
</code></pre>
<h2>Problem</h2>
<p>Academically speaking, how would you map the interface to conventional Java naming standards (e.g., <code>class Sentence</code> and <code>setParseTree( parseTree arg0 )</code>)?</p>
<h2>Ideas</h2>
<ol>
<li>Convert the 650+ line <a href=""http://pastebin.com/raw.php?i=m4XPJ5sT"" rel=""nofollow"">interface file</a> manually (and send a patch to the developers).</li>
<li>Regex <a href=""http://vim.wikia.com/wiki/Converting_variables_to_or_from_camel_case"" rel=""nofollow"">search and replace</a> voodoo (using vi): <code>:1,$s/_\([a-z]\)/\u\1/g</code></li>
<li>Create wrapper classes from the 53 auto-generated Java source files.</li>
</ol>
<p>Thank you!</p>
","46","1369","<java><c++><vim><naming-conventions><swig>","2012-05-28 21:53:46","TRUE","FALSE","10791139","2012-05-28 22:57:15","4","<p>SWIG provides a <code>%rename</code> directive that allows the names to be different in the client and implementation languages. <strike>But doing this will nearly double the length of the interface file.</strike></p>
<p>Actually, SWIG provides bulk renaming. See <a href=""http://swig.org/Doc2.0/SWIG.html#SWIG_advanced_renaming"" rel=""nofollow"">the documentation</a></p>
<blockquote>
<p>5.4.7.2 Advanced renaming support</p>
<p>While writing %rename for specific declarations is simple enough, sometimes the same renaming rule needs to be applied to many, maybe all, identifiers in the SWIG input. For example, it may be necessary to apply some transformation to all the names in the target language to better follow its naming conventions, like adding a specific prefix to all wrapped functions. Doing it individually for each function is impractical so SWIG supports applying a renaming rule to all declarations if the name of the identifier to be renamed is not specified:</p>
<pre><code>%rename(""myprefix_%s"") """"; // print -&gt; myprefix_print
</code></pre>
<p>This also shows that the argument of %rename doesn't have to be a literal string but can be a printf()-like format string. In the simplest form, ""%s"" is replaced with the name of the original declaration, as shown above. However this is not always enough and SWIG provides extensions to the usual format string syntax to allow applying a (SWIG-defined) function to the argument. For example, to wrap all C functions do_something_long() as more Java-like doSomethingLong() you can use the ""lowercamelcase"" extended format specifier like this:</p>
<pre><code>%rename(""%(lowercamelcase)s"") """"; // foo_bar -&gt; fooBar; FooBar -&gt; fooBar
</code></pre>
<p>Some functions can be parametrized, for example the ""strip"" one strips the provided prefix from its argument. The prefix is specified as part of the format string, following a colon after the function name:</p>
<pre><code>%rename(""%(strip:[wx])s"") """"; // wxHello -&gt; Hello; FooBar -&gt; FooBar
</code></pre>
</blockquote>
<p>My recommendation is just to leave it as-is. You're calling C++ functions, they have C++ names. If anything, this helps you remember that you're calling out to C++ and need to follow C++ rules for object lifetime management, there's a slight JNI performance penalty, etc.</p>
","2351","7","3","2","2012-05-28 22:38:33","45","TRUE","157431","0"
"http://stackoverflow.com/users/371739","http://stackoverflow.com/questions/20696108","http://stackoverflow.com/questions/20696108/#20696793","2013-12-20 05:25:48","2","114","0","1","Why do constructor calls in C++ and Java require explicit type parameters?","<p>C++ and Java have this similarity in how they handle parametric polymorphism: both will infer the type parameters to regular functions or methods, but require the programmer to explicitly give the type parameters when calling a constructor (Though this was changed in Java 7).</p>
<p>What is the technical reason behind this behavior?</p>
<p><strong>edit</strong>: I mistakenly thought this applied to Scala as well.
Here is an example from Java:</p>
<pre><code>class Foo&lt;T&gt; {
Foo(T x) { }
}
&lt;T&gt; void foo(T x) { }
Foo&lt;Integer&gt; f = new Foo(3);
foo(3);
</code></pre>
<p>both of these are legal, but the first one creates a ""raw type"" rather than a <code>Foo&lt;Integer&gt;</code>, and performs an unchecked assignment.</p>
","74","753","<java><c++><parametric-polymorphism>","2013-12-20 04:08:09","TRUE","FALSE","20696793","2013-12-20 05:25:48","3","<p>It's because C++ templates can be specialized.</p>
<p>That means that just because there's a main definition:</p>
<pre><code>template&lt;typename T&gt;
class Foo
{
Foo(T x) { }
};
</code></pre>
<p>and clearly <code>int</code> will be accepted by <code>Foo&lt;int&gt;(int)</code>, it's completely possible that there's also a specialized definition</p>
<pre><code>template&lt;&gt;
class Foo&lt;Foobar&gt;
{
Foo(int x) { }
};
</code></pre>
<p>which also accepts an <code>int</code> parameter.</p>
<p>Add user-defined type conversions to the mix, and you see that it just isn't possible to figure out the class's type parameters from function arguments.</p>
<p>And in fact, inference of type parameters for constructors IS allowed. But not inference of the class template parameters. For example, allowing implicit upcast when constructing a smart pointer:</p>
<pre><code>template&lt;typename T&gt;
class a_smart_ptr
{
template&lt;typename TOther&gt;
a_smart_ptr(TOther* p) { }
};
</code></pre>
","1022","6","3","1","2013-12-20 05:19:19","71","TRUE","157431","0"
"http://stackoverflow.com/users/952747","http://stackoverflow.com/questions/7570484","http://stackoverflow.com/questions/7570484/#7570551","2013-05-29 09:12:59","1","881","0","3","Benchmark C++ vs Java, Unrealistic results","<p>I did a simple test, I know C++ is faster but the results of my test is unrealistic.</p>
<p>C++ code is:</p>
<pre><code>#include &lt;stdio.h&gt;
#include &lt;windows.h&gt;
unsigned long long s(unsigned long long n)
{
unsigned long long s = 0;
for (unsigned long long i = 0; i &lt; n; i++)
s += i;
return s;
}
int main()
{
LARGE_INTEGER freq, start, end;
QueryPerformanceFrequency(&amp;freq);
QueryPerformanceCounter(&amp;start);
printf(""%llu\n"", s(1000000000));
QueryPerformanceCounter(&amp;end);
double d = (double) (end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0;
printf(""Delta: %f\n"", d);
return 0;
}
</code></pre>
<p>Java code is:</p>
<pre><code>public class JavaApplication5 {
public static long s(long n) {
long s = 0;
for (long i = 0; i &lt; n; i++) {
s += i;
}
return s;
}
public static void main(String[] args) {
long start = System.nanoTime();
System.out.println(s(1000000000));
long end = System.nanoTime();
System.out.println((end - start)/1000000);
}
}
</code></pre>
<p><em><sup>C++ compiler: gcc 4.4.0 and Java: jdk 1.6.0</sup></em></p>
<blockquote>
<p><code>Java: 2795 ms</code></p>
<p><code>C++ : 0.013517 ms</code></p>
</blockquote>
<p>It says C++ is 206777 times faster than Java! No way! What is wrong in my test?</p>
","42","1423","<java><c++><gcc><benchmarking>","2011-09-27 14:05:05","TRUE","FALSE","7570551","2011-09-27 14:45:41","4","<p>Show the compiler options you used. And your REAL code (<code>#include &lt;stdio&gt;</code> isn't your real code).</p>
<p>Your C++ compiler is much smarter than your Java compiler (this is true on average and in your case, but not every C++ compiler is smarter than every Java compiler), and it precomputed the result. The only thing you're timing is the <code>printf</code> call.</p>
<p>On most of the tasks Java is used for, it performs about as well as C++.</p>
<p>VM languages (Java, C#) have additional costs related to JIT compilation, but also benefit from more efficient memory allocation and inlining across shared libraries. And C++ is much much faster at accessing OS syscalls. Beyond that, C++ memory layouts can be carefully tuned for cache behavior; you don't get that level of control in managed languages.</p>
<p>Which of these factors has more influence is completely application-specific. Anyone making a blanket statement that ""C++ is faster in general than Java"" or ""Java is faster in general than C++"" is an idiot. Averages don't matter. Performance on YOUR application matters.</p>
<hr>
<p>And here is my proof, that gcc is precomputing the answer.</p>
<p>On this code:</p>
<pre><code>#include &lt;stdio.h&gt;
#include &lt;windows.h&gt;
unsigned long long s(unsigned long long n)
{
unsigned long long s = 0;
for (unsigned long long i = 0; i &lt; n; i++)
s += i;
return s;
}
int main( int argc, char** argv )
{
LARGE_INTEGER freq, start, end;
QueryPerformanceFrequency(&amp;freq);
QueryPerformanceCounter(&amp;start);
printf(""%llu\n"", s(1000000000));
QueryPerformanceCounter(&amp;end);
double d = (double) (end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0;
printf(""Delta: %f\n"", d);
QueryPerformanceCounter(&amp;start);
printf(""%llu\n"", s(atol(argv[1])));
QueryPerformanceCounter(&amp;end);
d = (double) (end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0;
printf(""Delta: %f\n"", d);
return 0;
}
</code></pre>
<p>With gcc-4.3.4, using the command-line <code>./g++-4 -omasoud-gcc.exe -O3 masoud.cpp</code>:</p>
<pre><code>bash-3.2# ./masoud-gcc 1000000000
499999999500000000
Delta: 0.845755
499999999500000000
Delta: 1114.105866
</code></pre>
<p>By comparison, MSVC++ 16.00.40219.01 for x64 (2010 SP1), command-line <code>cl /Ox masoud.cpp</code>:</p>
<pre><code>&gt; masoud 1000000000
499999999500000000
Delta: 229.684364
499999999500000000
Delta: 354.275606
</code></pre>
<p>VC++ isn't precomputing the answer, but 64-bit code does execute the loop more than three times faster. This is the speed that Java ought to approach.</p>
<hr>
<p>More fun facts: gcc precomputes the answer faster than the code it generates to calculate it out. Compile time for gcc:</p>
<pre><code>real 0m0.886s
user 0m0.248s
sys 0m0.185s
</code></pre>
","2882","11","4","1","2011-09-27 14:09:48","4","TRUE","157431","0"
"http://stackoverflow.com/users/484882","http://stackoverflow.com/questions/4664911","http://stackoverflow.com/questions/4664911/#4664994","2011-01-12 03:23:33","1","890","0","3","Behavior of nested finally in Exceptions","<p>Today at work, I had to review a code snippet that looks similar to this mock example.</p>
<p><code>
package test;</p>
<pre><code>import java.io.IOException;
import org.apache.log4j.Logger;
public class ExceptionTester {
public static Logger logger = Logger.getLogger(ExceptionTester.class);
public void test() throws IOException {
new IOException();
}
public static void main(String[] args) {
ExceptionTester comparator = new ExceptionTester();
try {
try {
comparator.test();
} finally {
System.out.println(""Finally 1"");
}
} catch(IOException ex) {
logger.error(""Exception happened"" ex);
// also close opened resources
}
System.out.println(""Exiting out of the program"");
}
</code></pre>
<p>}
</code></p>
<p>It's printing the following output.I expected an compile error since the inner <code>try</code> did not have a <code>catch</code> block.</p>
<pre>
Finally 1
Exiting out of the program
</pre>
<p>I do not understand why <code>IOException</code> is caught by the outer <code>catch</code> block. I would appreciate if anyone can explain this, especially by citing stack unwinding process</p>
","40","1210","<java>","2011-01-12 02:47:01","TRUE","FALSE","4664994","2011-01-12 03:23:33","6","<p>A finally block represents a task that has to be done under both normal and abnormal conditions.</p>
<p>Example: You take an interview candidate to lunch. While at lunch, you find out he's wanted by the police for murder. Exception! Lunch is over, the interview is a total loss, but... you still have to pay for lunch.</p>
<pre><code>try {
meetForLunch(interviewCandidate);
}
finally {
lunchBill.pay();
}
</code></pre>
<p>Note that paying for lunch hasn't taken care of the exception, you've still got to do something about the murderer at your interview. It's just a loose end that has to be taken care of before processing with damage control.</p>
<p>Most finally blocks are used in that way: A file needs to be closed whether you successfully saved the data or not, a database connection needs to be closed whether the transaction was approved or not, etc.</p>
<p>And the exception continues outward on its merry way, looking for a matching catch block in an enclosing scope.</p>
<p>Note that finally blocks will always run <em>unless</em> the process ends while the try block is still executing.</p>
","1125","6","1","6","2011-01-12 03:03:20","16","TRUE","157431","0"
"http://stackoverflow.com/users/807882","http://stackoverflow.com/questions/6555040","http://stackoverflow.com/questions/6555040/#6555051","2013-02-28 09:41:20","24","43582","3","2","Multiple input in JOptionPane.showInputDialog","<p>Is there a way to create multiple input in <code>JOptionPane.showInputDialog</code> instead of just one input?</p>
","45","118","<java><swing><joptionpane>","2011-07-02 04:01:31","FALSE","FALSE","6555051","2011-07-02 04:11:22","57","<p>Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object is a JPanel, in your situation, perhaps a JPanel that has several JTextFields in it. Example to follow...</p>
<p><strong>Edit</strong> </p>
<pre><code>import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel(""x:""));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel(""y:""));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
""Please Enter X and Y Values"", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println(""x value: "" + xField.getText());
System.out.println(""y value: "" + yField.getText());
}
}
}
</code></pre>
","1047","2","1","3","2011-07-02 04:05:32","4","TRUE","157215","0"
"http://stackoverflow.com/users/1024973","http://stackoverflow.com/questions/11093326","http://stackoverflow.com/questions/11093326/#11093360","2014-06-16 10:45:34","13","33470","7","6","Restricting JTextField input to Integers","<p>I know that this question must have been asked and answered a million times, but I just can't find an easy solution. I have a JTextField that is meant to accept only positive integers as input. I need a way to make sure that nothing else gets input here.</p>
<p>I already have a keyListener attached to this control. Removing the other code that this listener is there to handle, I have this:</p>
<pre><code> txtAnswer.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
/* Restrict input to only integers */
if (key &lt; 96 &amp;&amp; key &gt; 105) e.setKeyChar('');
};
});
</code></pre>
<p>As you can see, I'm trying to use the the KeyCode to check whether the key just pressed falls within the range of integers. This seems to work. But what I want to do is to simply disregard the entry if it falls outside of this range. The code <code>e.setKeyChar('')</code> was meant to handle this, but it doesn't work. The code will compile, but it has no visible effect.</p>
<p>Can anybody tell me if I am on the right track? What can I replace <code>e.setKeyChar('')</code> with to make this work? Or am I totally going in the wrong direction?</p>
<p>Thanks.</p>
","40","1293","<java><swing><numbers><jtextfield>","2012-06-19 01:41:44","TRUE","FALSE","11093360","2012-06-19 02:14:53","23","<p>Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.</p>
<p>The solution has been described many times on SO: Use a <a href=""http://docs.oracle.com/javase/7/docs/api/javax/swing/text/DocumentFilter.html"">DocumentFilter</a>. There are several examples of this on this site, some written by me.</p>
<p>For example: <a href=""http://stackoverflow.com/questions/9345750/using-documentfilter-filterbypass/9346426#9346426"">using-documentfilter-filterbypass</a></p>
<p>Also for tutorial help, please look at: <a href=""http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter"">Implementing a DocumentFilter</a>.</p>
<p><strong>Edit</strong> </p>
<p>For instance:</p>
<pre><code>import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
public class DocFilter {
public static void main(String[] args) {
JTextField textField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(textField);
PlainDocument doc = (PlainDocument) textField.getDocument();
doc.setDocumentFilter(new MyIntFilter());
JOptionPane.showMessageDialog(null, panel);
}
}
class MyIntFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
if (test(sb.toString())) {
super.insertString(fb, offset, string, attr);
} else {
// warn the user and don't allow the insert
}
}
private boolean test(String text) {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
if (test(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
} else {
// warn the user and don't allow the insert
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);
if (test(sb.toString())) {
super.remove(fb, offset, length);
} else {
// warn the user and don't allow the insert
}
}
}
</code></pre>
<p>Why is this important?</p>
<ul>
<li>What if the user uses copy and paste to insert data into the text component? A KeyListener can miss this?</li>
<li>You appear to be desiring to check that the data can represent an int. What if they enter numeric data that doesn't fit?</li>
<li>What if you want to allow the user to later enter double data? In scientific notation?</li>
</ul>
","3552","7","1","11","2012-06-19 01:47:03","6","TRUE","157215","11"
"http://stackoverflow.com/users/491243","http://stackoverflow.com/questions/9543320","http://stackoverflow.com/questions/9543320/#9543339","2014-08-05 14:53:02","10","33728","4","5","How to position the form in the center screen?","<p>I'm a .Net developer but somehow I was task to create a simple application in java for some extra reason. I was able to create that application but my problem is how can i center the form in the screen when the application is launched? </p>
<p>Here is my code:</p>
<pre><code>private void formWindowActivated(java.awt.event.WindowEvent evt)
{
// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the new location of the window
int w = this.getSize().width;
int h = this.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
// Move the window
this.setLocation(x, y);
}
</code></pre>
<p>The code above works fine but the problem is I've seen the form moving from the topleft most to center screen. I also tried adding that code in <code>formWindowOpened</code> event and still shows same action. Is there a better way for this? Just like in <code>.NET Application</code> there is a <code>CenterScreen Position</code>. Or if the code above is correct, on what Event will i put it?</p>
<p>Thanks for reading this.</p>
","46","1163","<java><swing><netbeans><layout-manager>","2012-03-03 03:59:58","TRUE","FALSE","9543339","2012-03-03 04:23:11","26","<p>Simply set location relative to null after calling pack on the JFrame, that's it.</p>
<p>e.g.,</p>
<pre><code> JFrame frame = new JFrame(""FooRendererTest"");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel); // or whatever...
frame.pack();
frame.setLocationRelativeTo(null); // *** this will center your app ***
frame.setVisible(true);
</code></pre>
","409","2","1","8","2012-03-03 04:04:08","5","TRUE","157215","0"
"http://stackoverflow.com/users/299803","http://stackoverflow.com/questions/5917017","http://stackoverflow.com/questions/5917017/#5917112","2011-05-06 21:42:41","8","8883","0","2","java.awt.AWTError: BoxLayout can't be shared","<p>I have initialized MotePanel, Command Panel and LEDPanel before setting their Layout, then how so am I getting this exception.</p>
<p>Please help.</p>
<pre><code>Exception in thread ""main"" java.awt.AWTError: BoxLayout can't be shared
at javax.swing.BoxLayout.checkContainer(BoxLayout.java:462)
at javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:246)
at javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:279)
at java.awt.Container.addImpl(Container.java:1107)
at java.awt.Container.add(Container.java:974)
at javax.swing.JFrame.addImpl(JFrame.java:556)
at java.awt.Container.add(Container.java:377)
at Window.&lt;init&gt;(Window.java:54)
</code></pre>
<hr>
<pre><code>public class Window extends JFrame{
private JPanel MotePanel;
private JPanel LEDPanel;
private JPanel CommandPanel;
private JCheckBox motes[];
private JRadioButton Leds[];
public Window(){
this.setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
this.setTitle(""Sensor Networks Lab"");
this.setSize(300, 200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
MotePanel = new JPanel();
LEDPanel = new JPanel();
CommandPanel = new JPanel();
motes = new JCheckBox[10];
Leds = new JRadioButton[3];
MotePanel.setLayout(new BoxLayout(MotePanel, BoxLayout.Y_AXIS));
CommandPanel.setLayout(new BoxLayout(CommandPanel, BoxLayout.Y_AXIS));
LEDPanel.setLayout(new BoxLayout(LEDPanel, BoxLayout.Y_AXIS));
System.out.println(""creating MotePanel"");
for(int i=0; i&lt;10; i++){
motes[i] = new JCheckBox(""Mote ""+i);
MotePanel.add(motes[i]);
}
System.out.println(""creating LEDPanel"");
for(int i=0; i&lt;3; i++)
Leds[i] = new JRadioButton();
Leds[0].setText(""RED"");
LEDPanel.add(Leds[0]);
Leds[1].setText(""GREEN"");
LEDPanel.add(Leds[1]);
Leds[2].setText(""BLUE"");
LEDPanel.add(Leds[2]);
this.add(MotePanel);
this.add(LEDPanel);
this.add(CommandPanel);
}
</code></pre>
","44","2181","<java><swing><layout-manager>","2011-05-06 21:06:52","TRUE","FALSE","5917112","2011-05-06 21:31:57","27","<p>When calling setLayout on a JFrame, you're actually adding the layout to the JFrame's contentPane not the JFrame itself since this method is more of a convenience method that transmits the method call to the contentPane. The BoxLayout constructor must reflect this since you can't add the BoxLayout to one container and then pass in as a parameter a different container. So change this:</p>
<pre><code>this.setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
</code></pre>
<p>to this:</p>
<pre><code>setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
</code></pre>
<p>Also: no need for all the <code>this.</code> business since this. is implied, and also there is no actual need here to extend JFrame.</p>
<p>edit: this code below is all that is needed to demonstrate your error and its solution:</p>
<pre><code>import javax.swing.*;
public class BoxLayoutFoo extends JFrame {
public BoxLayoutFoo() {
// swap the comments below
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); // comment out this line
//setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS)); // uncomment this line
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new BoxLayoutFoo();
}
}
</code></pre>
","1326","4","3","11","2011-05-06 21:17:39","11","TRUE","157215","0"
"http://stackoverflow.com/users/273905","http://stackoverflow.com/questions/7541227","http://stackoverflow.com/questions/7541227/#7541261","2011-09-24 22:24:43","1","446","0","2","Storing Javascript object
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment