Questions Tagged with #Java

Java (not to be confused with JavaScript or JScript or JS) is a general-purpose object-oriented programming language designed to be used in conjunction with the Java Virtual Machine (JVM). "Java platform" is the name for a computing system that has installed tools for developing and running Java programs. Use this tag for questions referring to the Java programming language or Java platform tools.

Scanner method to get a char

What is the Scanner method to get a char returned by the keyboard in Java. like nextLine() for String, nextInt() for int, etc...

Extract string between two strings in java

I try to get string between <%= and %>, here is my implementation: String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>"; Pattern pattern = Pattern.compile("<%=(.*?)%>"); String[] resu..

In which case do you use the JPA @JoinTable annotation?

In which case do you use the JPA @JoinTable annotation?..

- java.lang.NullPointerException - setText on null object reference

This is what I'm trying to do for several hours: I've got a MainActivity.java file (listing below) and a fragment_start.xml file with a start button. Tapping the start-button should display the activi..

How can I read a large text file line by line using Java?

I need to read a large text file of around 5-6 GB line by line using Java. How can I do this quickly?..

Do Java arrays have a maximum size?

Is there a limit to the number of elements a Java array can contain? If so, what is it?..

Is there a date format to display the day of the week in java?

I know of date formats such as "yyyy-mm-dd" -which displays date in format 2011-02-26 "yyyy-MMM-dd"-which displays date in format 2011-FEB-26 to be used in eg: SimpleDateFormat formatter = new Simp..

remove all special characters in java

Possible Duplicate: Replacing all non-alphanumeric characters with empty strings import java.util.Scanner; import java.util.regex.*; public class io{ public static void main(String args[]){..

Maven: How to run a .java file from command line passing arguments

I have the following problem. I would like to run mvn from command line for a Main.java file. Main.java accepts a parameter. How do I do that from command line? I tried finding an example but I was n..

Different names of JSON property during serialization and deserialization

Is it possible: to have one field in class, but different names for it during serialization/deserialization in Jackson library? For example, I have class "Coordiantes". class Coordinates{ int red;..

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I am getting following error Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject at OrderBook.WriteToExcelSheet.CreateOutPutFile(WriteToExcelSheet.java..

How to execute .sql script file using JDBC

Possible Duplicate: Running a .sql script using MySQL with JDBC I have an SQL script file which contains 40-50 SQL statements. Is it possible to run this script file using JDBC?..

Can not deserialize instance of java.lang.String out of START_ARRAY token

I am very new to the Jackson parser. My code was running fine until today. I am not able to figure out the error. Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can n..

Simple export and import of a SQLite database on Android

I am trying to implement a simple SQLite export/import for backup purposes. Export is just a matter of storing a copy of the raw current.db file. What I want to do for import is to just delete the old..

How to make an Android device vibrate? with different frequency?

I wrote an Android application. Now, I want to make the device vibrate when a certain action occurs. How can I do this?..

Sending and receiving UDP packets?

I have made a program to send an UDP packets from a client to a server. Here is the transmitter code: import java.io.IOException; import java.net.*; public class JavaApplication9 { public s..

Android button onClickListener

I am trying to open new Activity by clicking on a button in my OnClickListener method. How does OnClickListener method work and what should be done in it to start a new Activity? ..

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

I'm trying to connect to a database made by MS Access using Java, but I cannot seem to manage. I am using ODBC and I'm getting this exception: java.sql.SQLException: [Microsoft][ODBC Driver Manager] ..

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

I know this will give me the day of the month as a number (11, 21, 23): SimpleDateFormat formatDayOfMonth = new SimpleDateFormat("d"); But how do you format the day of the month to include an ordin..

Current timestamp as filename in Java

I want to name new files created by my Java application with the current timestamp. I need help with this. How do I name the new files created with the current timestamp? Which classes should I inclu..

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

In eclipse when i started my application i got this - Could not discover the dialect to use. java.sql.SQLException: Unable to load authentication plugin 'caching_sha2_password'. at java.sql.SQLExc..

Finding all objects that have a given property inside a collection

I have some complicated object, such as a Cat, which has many properties, such as age, favorite cat food, and so forth. A bunch of Cats are stored in a Java Collection, and I need to find all the C..

Which programming languages can be used to develop in Android?

Possible Duplicate: Which programming languages can I use on Android Dalvik? Mostly, Android applications are written in Java. But i heard that its also possible to use Scala or some other ..

Create session factory in Hibernate 4

I'm having trouble generating a session factory in Hibernate 4. In Hibernate 3 I simple did: org.hibernate.cfg.Configuration conf= HibernateUtil .getLimsInitializedConfiguration(systemConfigurati..

How to use ClassLoader.getResources() correctly?

How can I use ClassLoader.getResources() to find recursivly resources from my classpath? E.g. finding all resources in the META-INF "directory": Imagine something like getClass().getClassLoader(..

Windows error 2 occured while loading the Java VM

I've been trying to install this ARToolkit from Qualcomm: https://ar.qualcomm.at/qdevnet/ (Windows ".exe" version) on a Windows 7 64bits platform, and I keep getting the error: Windows error 2 o..

How to convert a double to long without casting?

What is the best way to convert a double to a long without casting? For example: double d = 394.000; long l = (new Double(d)).longValue(); System.out.println("double=" + d + ", long=" + l); ..

How do I read input character-by-character in Java?

I am used to the c-style getchar(), but it seems like there is nothing comparable for java. I am building a lexical analyzer, and I need to read in the input character by character. I know I can use ..

Get value from hashmap based on key to JSTL

I want to get the value of HashMap based on key. HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); ArrayList<String> arrayList = ne..

Finish all previous activities

My application has the following flow screens : Home->screen 1->screen 2->screen 3->screen 4->screen 5 Now I have a common log out button in each screens (Home/ screen 1 / screen 2..

How should I have explained the difference between an Interface and an Abstract class?

In one of my interviews, I have been asked to explain the difference between an Interface and an Abstract class. Here's my response: Methods of a Java interface are implicitly abstract and can..

Could not commit JPA transaction: Transaction marked as rollbackOnly

I'm using Spring and Hibernate in one of the applications that I'm working on and I've got a problem with handling of transactions. I've got a service class that loads some entities from the database..

Spring JPA and persistence.xml

I'm trying to set up a Spring JPA Hibernate simple example WAR for deployment to Glassfish. I see some examples use a persistence.xml file, and other examples do not. Some examples use a dataSource, a..

what's the correct way to send a file from REST web service to client?

I've just started to develop REST services, but I've come across a difficult situation: sending files from my REST service to my client. So far I've gotten the hang of how to send simple data types (s..

Why is using a wild card with a Java import statement bad?

It is much more convenient and cleaner to use a single statement like import java.awt.*; than to import a bunch of individual classes import java.awt.Panel; import java.awt.Graphics; import java.a..

Java equivalent to #region in C#

I want to use regions for code folding in Eclipse; how can that be done in Java? An example usage in C#: #region name //code #endregion ..

"Non-static method cannot be referenced from a static context" error

I have a class named Media which has a method named setLoanItem: public void setLoanItem(String loan) { this.onloan = loan; } I am trying to call this method from a class named GUI in the follo..

Convert a date format in epoch

I have a string with a date format such as Jun 13 2003 23:11:52.454 UTC containing millisec... which I want to convert in epoch. Is there an utility in Java I can use to do this conversion?..

Create PDF with Java

Possible Duplicate: PDF Generation Library for Java I'm working on an invoice program for a local accounting company. What is a good way to create a PDF file with Java? Any good library? I'..

When would you use the Builder Pattern?

What are some common, real world examples of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?..

What causes a java.lang.StackOverflowError

What can cause a java.lang.StackOverflowError? The stack printout that I get is not very deep at all (only 5 methods)...

The system cannot find the file specified in java

I am making a program that opens and reads a file. This is my code: import java.io.*; public class FileRead{ public static void main(String[] args){ try{ File file = new Fil..

Sorted collection in Java

I'm a beginner in Java. Please suggest which collection(s) can/should be used for maintaining a sorted list in Java. I have tried Map and Set, but they weren't what I was looking for...

How do I copy the contents of one ArrayList into another?

I have some data structures, and I would like to use one as a temporary, and another as not temporary. ArrayList<Object> myObject = new ArrayList<Object>(); ArrayList<Object> myTemp..

Getting hold of the outer class object from the inner class object

I have the following code. I want to get hold of the outer class object using which I created the inner class object inner. How can I do it? public class OuterClass { public class InnerClass { ..

Spring Boot without the web server

I have a simple Spring Boot application that gets messages from a JMS queue and saves some data to a log file, but does not need a web server. Is there any way of starting Spring Boot without the web ..

How do servlets work? Instantiation, sessions, shared variables and multithreading

Suppose, I have a webserver which holds numerous servlets. For information passing among those servlets I am setting session and instance variables. Now, if 2 or more users send request to this serve..

Empty ArrayList equals null

Is an empty Arraylist (with nulls as its items) be considered as null? So, essentially would the below statement be true: if (arrayList != null) thanks..

Convert an array into an ArrayList

I'm having a lot of trouble turning an array into an ArrayList in Java. This is my array right now: Card[] hand = new Card[2]; "hand" holds an array of "Cards". How this would look like as an Array..

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

On Windows 7 I downloaded the 'netbeans-8.0.1-javaee-windows.exe' installer from this site https://netbeans.org/downloads/. The installer installs GlassFish 4.1, Java 1.8.0_20 and NetBeans 8.01. After..

Converting a Date object to a calendar object

So I get a date attribute from an incoming object in the form: Tue May 24 05:05:16 EDT 2011 I am writing a simple helper method to convert it to a calendar method, I was using the following code: ..

Java error: Implicit super constructor is undefined for default constructor

I have a some simple Java code that looks similar to this in its structure: abstract public class BaseClass { String someString; public BaseClass(String someString) { this.someString ..

How to download videos from youtube on java?

how to download videos from youtube on Java? need class(or piece of code) which describes how to do that. Thank you...

java: How can I do dynamic casting of a variable from one type to another?

I would like to do dynamic casting for a Java variable, the casting type is stored in a different variable. This is the regular casting: String a = (String) 5; This is what I want: String theTy..

Technically what is the main difference between Oracle JDK and OpenJDK?

I have been using OpenJDK for ages, initially for small projects where it has no problems. But since I started to play with it for big toys, I started to notice random/unknown fatal error and crashes ..

What is the difference between JVM, JDK, JRE & OpenJDK?

What is the difference between JVM, JDK, JRE & OpenJDK? I was programming in Java and I encountered these phrases, what are the differences among them?..

Gradle task - pass arguments to Java application

I have a Java application that runs with a custom gradle task and the application requires some arguments upon being invoked. These are: programName ( string | -f filename | -d key | -h) Options: ..

how to fetch data from database in Hibernate

This is my class to fetch data from database package com.javatpoint.mypackage; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Tra..

How can I get a Unicode character's code?

Let's say I have this: char registered = '®'; or an umlaut, or whatever unicode character. How could I get its code?..

Generate a random double in a range

I have two doubles like the following double min = 100; double max = 101; and with a random generator, I need to create a double value between the range of min and max. Random r = new Random(); r...

Reading multiple Scanner inputs

What I am trying to do is have multiple inputs that all have different variables. Each variable will be part of different equations. I am looking for a way to do this and, I think I have an idea. I ju..

Basic calculator in Java

I'm trying to create a basic calculator in Java. I'm quite new to programming so I'm trying to get used to it. import java.util.Scanner; import javax.swing.JOptionPane; public class javaCalculator ..

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values. Whats the best way to do that? I was thinking instead iterating the keySet and ..

Correct set of dependencies for using Jackson mapper

I am new to Jackson and I was writing some code for practice. I found out the the new version of Jackson library can be found on Fasterxml: Jackson, so I added the below dependencies to my Maven pom f..

Ways to save enums in database

What is the best way to save enums into a database? I know Java provides name() and valueOf() methods to convert enum values into a String and back. But are there any other (flexible) options to stor..

How to check whether a int is not null or empty?

I really dont know if this is possible or not. But I am strucking in a place where I want to check an int value is null or not, to call different methods. Is there any way to do it? Actually, variab..

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

I am working on a SSL client server program and I have to reuse the following method. private boolean postMessage(String message){ try{ String serverURLS = getRecipientURL(message); ..

adding comment in .properties files

By using following block of code in build.xml file <propertyfile file="default.properties" comment="Default properties"> <entry key="source.dir" value="1" /> <entry key="dir.publ..

Double array initialization in Java

I was reading a book on Java and came across an example in which an array of type double was initialized in a way that I haven't seen before. What type of initialization is it and where else can it be..

Is it possible to get only the first character of a String?

I have a for loop in Java. for (Legform ld : data) { System.out.println(ld.getSymbol()); } The output of the above for loop is Pad CaD CaD CaD Now my question is it ..

JOptionPane YES/No Options Confirm Dialog Box Issue

I've created a JOptionPane and it only has two buttons YES_NO_OPTION . After JOptionPane.showConfirmDialog pops out , I want to click YES BUTTON to continue opening the JFileChooser and if I clicked ..

What is the difference between i++ & ++i in a for loop?

I've just started learning Java and now I'm into for loop statements. I don't understand how ++i and i++ works in a for-loop. How do they work in mathematics operations like addition and subtraction?..

Finding an element in an array in Java

Does Java have a built-function to allow me to linearly search for an element in an array or do I have to just use a for loop?..

HQL Hibernate INNER JOIN

How can I write this SQL query in Hibernate? I would like to use Hibernate to create queries, not create the database. SELECT * FROM Employee e INNER JOIN Team t ON e.Id_team=t.Id_team I created en..

How to use ArrayList.addAll()?

I want to fill an ArrayList with these characters +,-,*,^ etc. How can I do this without having to add every character with arrayList.add()? ..

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

I have a Java 7 application using JVM ARGS: -Xms1024m -Xmx2048m, and it runs pretty well. After I upgrade to Java 8, it runs in error state with Exception: Exception in thread "main" java.lang.OutOf..

Something like 'contains any' for Java set?

I have two sets, A and B, of the same type. I have to find if A contains any element from the set B. What would be the best way to do that without iterating over the sets? The Set library has contai..

How to iterate through range of Dates in Java?

In my script I need to perform a set of actions through range of dates, given a start and end date. Please provide me guidance to achieve this using Java. for ( currentDate = starDate; currentDate &l..

Use string in switch case in java

I need to change the following if's to a switch-case while checking for a String, to improve the cyclomatic complexity. String value = some methodx; if ("apple".equals(value)) { method1; } if ("..

casting Object array to Integer array error

What's wrong with the following code? Object[] a = new Object[1]; Integer b=1; a[0]=b; Integer[] c = (Integer[]) a; The code has the following error at the last line : Exception in thread "main..

Direct download from Google Drive using Google Drive API

My desktop application, written in java, tries to download public files from Google Drive. As i found out, it can be implemented by using file's webContentLink (it's for ability to download public fil..

String.format() to format double in java

How can I use String.format(format String,X) to format a double like follows??? 2354548.235 -> 2,354,548.23 Thanks!..

Better way to represent array in java properties file

I'm currently making a .properties file that needs to be loaded and transformed into an array. But there is a possibility of anywhere from 0-25 of each of the property keys to exist. I tried a few i..

how to achieve transfer file between client and server using java socket

I have implement the simple TCP server and TCP client classes which can send the message from client to server and the message will be converted to upper case on the server side, but how can I achieve..

How to initialize HashSet values by construction?

I need to create a Set with initial values. Set<String> h = new HashSet<String>(); h.add("a"); h.add("b"); Is there a way to do this in one line of code? For instance, it's useful for a..

Eclipse does not highlight matching variables

Eclipse does not highlight matching variables for me: I've already tried to change "Mark occurrences" via Window -> Preferences -> Java -> Editor -> Mark Occurrences but it didn't wo..

What is the difference between Hibernate and Spring Data JPA

What are the main differences between Hibernate and Spring Data JPA? When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Dat..

How to check if array element is null to avoid NullPointerException in Java

I have a partially nfilled array of objects, and when I iterate through them I tried to check to see whether the selected object is null before I do other stuff with it. However, even the act of check..

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

I deployed my project on the production server and getting the below error. It's a live project so , after getting error i replaced this with previous version that was running fine but now that is al..

Why are static variables considered evil?

I am a Java programmer who is new to the corporate world. Recently I've developed an application using Groovy and Java. All through the code I wrote used quite a good number of statics. I was asked by..

Java inner class and static nested class

What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?..

How can I start InternetExplorerDriver using Selenium WebDriver

I downloaded the driver and I gave the exact path in my code but when I ran the code it shows me error my code with java is as below: System.out.println("Internet Explorer is selected"); System.setP..

Hibernate: best practice to pull all lazy collections

What I have: @Entity public class MyEntity { @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) @JoinColumn(name = "myentiy_id") private List<Address> add..

How do I "decompile" Java class files?

What program can I use to decompile a class file? Will I actually get Java code, or is it just JVM assembly code? On Java performance questions on this site I often see responses from people who have..

How to perform mouseover function in Selenium WebDriver using Java?

I want to do mouseover function over a drop down menu. When we hover over the menu, it will show the new options. I tried to click the new options using the xpath. But cannot click the menus directly...

Spring Rest POST Json RequestBody Content type not supported

When I try to post new object with post method. RequestBody could not recognize contentType. Spring is already configured and POST could work with others objects, but not this specific one. org.sprin..

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Background I have been using the Authorize.net SDK in an Eclipse project of it's own. Everything was working great. I then needed to add it to my main project. I added the dependencies to the class p..

How do I print a double value without scientific notation using Java?

I want to print a double value in Java without exponential form. double dexp = 12345678; System.out.println("dexp: "+dexp); It shows this E notation: 1.2345678E7. I want it to print it like this: ..

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

I have this problem: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: mvc3.model.Topic.comments, no session or session was closed Here is the model: ..

Android: Creating a Circular TextView?

My current simple XML is below, however i would like the 3 TextViews within it to be circular, rather than rectangular. How can I change my code to do so? <?xml version="1.0" encoding="utf-8"?>..

How can I drop all the tables in a PostgreSQL database?

How can I drop all tables in PostgreSQL, working from the command line? I don't want to drop the database itself, just all tables and all the data in them...

The model backing the <Database> context has changed since the database was created

The error message : "The model backing the 'AddressBook' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an ID..

Case objects vs Enumerations in Scala

Are there any best-practice guidelines on when to use case classes (or case objects) vs extending Enumeration in Scala? They seem to offer some of the same benefits...

Where's javax.servlet?

I have jdk1.6.0_13 installed, but when I try to find a javax.servlet package, or press Ctrl+Space in Eclipse after Servlet I cannot get anything. Where can I download this package, and why isn't it in..

Prevent flex items from overflowing a container

How do I make my flex item (article in this example), which has flex-grow: 1; not to overflow it's flex parent/container (main)? In this example article is just text, though it might contains other ..

android edittext onchange listener

I know a little bit about TextWatcher but that fires on every character you enter. I want a listener that fires whenever the user finishes editing. Is it possible? Also in TextWatcher I get an instanc..

SASS - use variables across multiple files

I would like to keep one central .scss file that stores all SASS variable definitions for a project. // _master.scss $accent: #6D87A7; $error: #811702; $warning: #F9E055; $valid: #038144..

C# Dictionary get item by index

im trying to make a method which return a name of card from my Dictionary randomly. My Dictionary: First definied name of card which is string and second is value of that card, which is int. public ..

Android - android.os.NetworkOnMainThreadException

I have this exception and I was reading a thread on this, and it seemed confusing: How to fix android.os.NetworkOnMainThreadException? I already added this line to my manifest: <uses-permission ..

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

I have a strange error. Usually (I did my googling), in this case of errors Angular specifies in square brackets which exactly module/service/provider/etc caused the problem. However here, it says onl..

Detecting request type in PHP (GET, POST, PUT or DELETE)

How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?..

How to style a select tag's option element?

I'm trying to set the style of an option in a select dropdown menu in Google Chrome. It works in all browsers except IE9 and Chrome. _x000D_ _x000D_ option.red {_x000D_ background-color: #cc0000;..

How can I set a custom baud rate on Linux?

I want to communicate over my serial port on Linux to a device with a non-standard-baud rate that is not defined in termios.h. I tried the "baud rate aliasing"-method from this post, but when I execu..

Difference between JPanel, JFrame, JComponent, and JApplet

I'm making a physics simulator for fun and I was looking up graphics tutorials when I tried to figure out the difference between all these J's. Can somebody elaborate on them or perhaps provide a lin..

How to add color to Github's README.md file

I have a README.md file for my project underscore-cli, a pretty sweet tool for hacking JSON and JS on the command-line, and I want to document the --color flag. Currently, the ONLY way to do this is w..

Switch with if, else if, else, and loops inside case

For the purpose of my question I've only included case 1, but the other cases are the same. Let's say value is currently 1, we go to case 1 and our for loop goes through the array to see if each eleme..

S3 - Access-Control-Allow-Origin Header

Did anyone manage to add Access-Control-Allow-Origin to the response headers? What I need is something like this: <img src="http://360assets.s3.amazonaws.com/tours/8b16734d-336c-48c7-95c4-3a93fa0..

Delete column from pandas DataFrame

When deleting a column in a DataFrame I use: del df['column_name'] And this works great. Why can't I use the following? del df.column_name Since it is possible to access the column/Series as df...

Eclipse change project files location

I have an Eclipse project (Flex Builder) of which the actual files have changed location on the drive. When I start Eclipse I can see the project listed but there are no actual files listed. Right cli..

How can I plot with 2 different y-axes?

I would like superimpose two scatter plots in R so that each set of points has its own (different) y-axis (i.e., in positions 2 and 4 on the figure) but the points appear superimposed on the same figu..

Send string to stdin

Is there a way to effectively do this in bash: /my/bash/script < echo 'This string will be sent to stdin.' I'm aware that I could pipe the output from the echo such as this: echo 'This string w..

Should a function have only one return statement?

Are there good reasons why it's a better practice to have only one return statement in a function? Or is it okay to return from a function as soon as it is logically correct to do so, meaning there ..

PowerShell Script to Find and Replace for all Files with a Specific Extension

I have several configuration files on Windows Server 2008 nested like such: C:\Projects\Project_1\project1.config C:\Projects\Project_2\project2.config In my configuration I need to do a string re..

How to convert An NSInteger to an int?

For example when passing a value message to an NSInteger instance like so [a value] it causes an EXC_BAD_ACCESS. So how to convert an NSInteger to int? If it's relevant only small numbers < 32 a..

vagrant primary box defined but commands still run against all boxes

I am trying to set my "dev" VM as primary so most commands such as vagrant up, vagrant halt, etc operate on the "dev" VM and ignore the "stage" VM unless the "stage" VM name is explicitly listed on th..

System.Net.WebException: The remote name could not be resolved:

I am testing an endpoint that I am experiencing some issues with. I am simply using HttpClient in a loop that performs a request each hour. var httpClient = new HttpClient(); var message = httpClien..

Source file not compiled Dev C++

I just installed Dev C++ and I am learning C programming. the code i used was #include <stdio.h> int main() { printf("Hello world"); getch(); } I saved it as a .c file. When I compil..

Make an Android button change background on click through XML

Is there a way to specify an alternative background image/color for a Button in the XML file that is going to be applied onClick, or do I have to do a Button.setBackground() in the onClickListener?..

How to set the text color of TextView in code?

In XML, we can set a text color by the textColor attribute, like android:textColor="#FF0000". But how do I change it by coding? I tried something like: holder.text.setTextColor(R.color.Red); Where..

How can I concatenate two arrays in Java?

I need to concatenate two String arrays in Java. void f(String[] first, String[] second) { String[] both = ??? } What is the easiest way to do this?..

Why doesn't JavaScript have a last method?

Its kinda weird that the JavaScript Array class does not offer a last method to retrieve the last element of an array. I know the solution is simple (Ar[Ar.length-1] ), but, still, this is too frequen..

No module named 'openpyxl' - Python 3.4 - Ubuntu

I installed openpyxl with $ pip install openpyxl when I try the command from openpyxl import Workbook I get Traceback (most recent call last): File "<pyshell#0>", line 1, in <module&g..

Convert JSON array to an HTML table in jQuery

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?..

How do you run a command as an administrator from the Windows command line?

I have a small script that performs the build and install process on Windows for a Bazaar repository I'm managing. I'm trying to run the script with elevated, administrative privileges from within the..

Making a Sass mixin with optional arguments

I am writing a mixin like this: @mixin box-shadow($top, $left, $blur, $color, $inset:"") { -webkit-box-shadow: $top $left $blur $color $inset; -moz-box-shadow: $top $left $blur $color $inset;..

commands not found on zsh

I am using the z Shell (zsh) instead of the default bash, and something wrong happen so that all commands who used to work are no longer recognized: ls zsh: command not found: ls open -e .zshrc zsh:..

How to call a function within class?

I have this code which calculates the distance between two coordinates. The two functions are both within the same class. However how do I call the function distToPoint in the function isNear? class..

How to read a file into vector in C++?

I need to read from a .data or .txt file containing a new float number on each line into a vector. I have searched far and wide and applied numerous different methods but every time I get the same r..

align right in a table cell with CSS

I have the old classic code like this <td align="right"> which does what it says: it right aligns the content in the cell. So if I put 2 buttons in this cell, they will appear at the right si..

Using C++ base class constructors?

While working with templates I ran into a need to make a base class constructors accessible from inherited classes for object creation to decrease copy/paste operations. I was thinking to do this thro..

How do I prevent 'git diff' from using a pager?

Is there a command line switch to pass to git diff and other commands that use the less pager by default? I know I can pipe it to cat, but that removes all the syntax highlighting. I know I can set ..

How do I remove the space between inline/inline-block elements?

Given this HTML and CSS: _x000D_ _x000D_ span {_x000D_ display:inline-block;_x000D_ width:100px;_x000D_ background-color:palevioletred;_x000D_ }_x000D_ <p>_x000D_ <span> F..

Are dictionaries ordered in Python 3.6+?

Dictionaries are ordered in Python 3.6 (under the CPython implementation at least) unlike in previous incarnations. This seems like a substantial change, but it's only a short paragraph in the documen..

adding text to an existing text element in javascript via DOM

I am trying to figure how to add text to a p tag or h1 tag that already has a text node. For example: _x000D_ _x000D_ var t = document.getElementById("p").textContent;_x000D_ var y = document.creat..

Could not load file or assembly 'System.Data.SQLite'

I've installed ELMAH 1.1 .Net 3.5 x64 in my ASP.NET project and now I'm getting this error (whenever I try to see any page): Could not load file or assembly 'System.Data.SQLite, Version=1.0.61.0..

Is try-catch like error handling possible in ASP Classic?

What options are there in ASP Classic for error handling? For example: I'm using the Mail.SendMail function but when switching on the testing server it doesn't work, which is normal. I want to test ..

Read XML file into XmlDocument

I am very new to C#. I have XML file (text.xml). I want to read that in XmlDocument and store the stream in string variable...

Where does npm install packages?

Can someone tell me where can I find the Node.js modules, which I installed using npm?..

How to close off a Git Branch?

I'm starting out using Git + GitHub. In our distributed team, each member is creating their own branch for each issue/requirement they are allocated. git branch Issue#1 <-- create this branch ..

What are -moz- and -webkit-?

-webkit-column-count: 3; -webkit-column-gap: 10px; -webkit-column-fill: auto; -moz-column-count: 3; -moz-column-gap: 10px; -moz-column-fill: auto; I am a beginner at CSS and when I was looking at so..

Send multipart/form-data files with angular using $http

I know there are a lot of questions about this, but I can't get this to work: I want to upload a file from input to a server in multipart/form-data I've tried two approaches. First: headers: { 'C..

Change the spacing of tick marks on the axis of a plot?

How can I change the spacing of tick marks on the axis of a plot? What parameters should I use with base plot or with rgl?..

How to make PDF file downloadable in HTML link?

I am giving link of a pdf file on my web page for download, like below <a href="myfile.pdf">Download Brochure</a> The problem is when user clicks on this link then If the user have in..

automatically execute an Excel macro on a cell change

How can I automatically execute an Excel macro each time a value in a particular cell changes? Right now, my working code is: Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect..

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I have a .key file, when I do openssl rsa -text -in file.key I get unable to load Private Key 140000419358368:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: ANY PRI..

Creating lowpass filter in SciPy - understanding methods and units

I am trying to filter a noisy heart rate signal with python. Because heart rates should never be above about 220 beats per minute, I want to filter out all noise above 220 bpm. I converted 220/minute ..

What is the difference between java and core java?

When looking at job openings on-line, I noticed that some openings required knowledge of "core Java". What is core java and how is different from java?..

Get current cursor position in a textbox

I need a code to find current position of cursor in a textbox/textarea. It should work with chrome and firefox. Following is the code which I am using: <!DOCTYPE html> <html> <head&g..

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I've generated key pairs using PuTTYgen and been logging in using Pageant, so that I have to enter my pass-phrase only once when my system boots. How do I achieve this in Linux? I've heard of keycha..

How to make code wait while calling asynchronous calls like Ajax

I am looking for something like this function someFunc() { callAjaxfunc(); //may have multiple ajax calls in this function someWait(); // some code which waits until async calls complete console.log..

TypeError: 'str' object is not callable (Python)

Code: import urllib2 as u import os as o inn = 'dword.txt' w = open(inn) z = w.readline() b = w.readline() c = w.readline() x = w.readline() m = w.readline() def Dict(Let, Mod): global str in..

Difference between <? super T> and <? extends T> in Java

What is the difference between List<? super T> and List<? extends T> ? I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List&..

How to pass anonymous types as parameters?

How can I pass anonymous types as parameters to other functions? Consider this example: var query = from employee in employees select new { Name = employee.Name, Id = employee.Id }; LogEmployees(quer..

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table: ID COMPANY_ID EMPLOYEE 1 1 Anna 2 1 Bill 3 2 ..

How to make graphics with transparent background in R using ggplot2?

I need to output ggplot2 graphics from R to PNG files with transparent background. Everything is ok with basic R graphics, but no transparency with ggplot2: d <- rnorm(100) #generating random data..

What is the proper way to check if a string is empty in Perl?

I've just been using this code to check if a string is empty: if ($str == "") { // ... } And also the same with the not equals operator... if ($str != "") { // ... } This seems to work (I th..

Jquery get form field value

I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this <div id ="DynamicValueAssignedHere"> <div class="something">Hello..

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

So I'm now desperate in finding a fix for this. I'm compiling a shared library .so in Ubuntu 32 bit (Have tried doing it under Debian and Ubuntu 64 bit, but none worked either) I keep getting: /usr/l..

How to print the current Stack Trace in .NET without any exception?

I have a regular C# code. I have no exceptions. I want to programmatically log the current stack trace for debugging purpose. Example: public void executeMethod() { logStackTrace(); method()..

How to install ADB driver for any android device?

I am an android developer. I have a new HTC Inspire 4g phone but I don't know how to install usb driver for it. This is my android_winusb.inf file: ; ; Android WinUsb driver installation. ; [Version]..

Does a TCP socket connection have a "keep alive"?

I have heard of HTTP keep-alive but for now I want to open a socket connection with a remote server. Now will this socket connection remain open forever or is there a timeout limit associated with it ..

Go to "next" iteration in JavaScript forEach loop

How do I go to the next iteration of a JavaScript Array.forEach() loop? For example: var myArr = [1, 2, 3, 4]; myArr.forEach(function(elem){ if (elem === 3) { // Go to "next" iteration. Or "c..

Standard Android menu icons, for example refresh

The Android SDK offers the standard menu icons via android.R.drawable.X. However, some standard icons, such as ic_menu_refresh (the refresh icon), are missing from android.R. Is there any way to get ..

ssh script returns 255 error

In my code I have the following to run a remote script. ssh [email protected] "sh /home/user/backup_mysql.sh" For some reason it keeps 255'ing on me. Any ideas? I can SSH into the box just fine..

Find file in directory from command line

In editors/ides such as eclipse and textmate, there are shortcuts to quickly find a particular file in a project directory. Is there a similar tool to do full path completion on filenames within a di..

Serializing PHP object to JSON

So I was wandering around php.net for information about serializing PHP objects to JSON, when I stumbled across the new JsonSerializable Interface. It's only PHP >= 5.4 though, and I'm running in a 5...

When do I need to use a semicolon vs a slash in Oracle SQL?

We have been having some debate this week at my company as to how we should write our SQL scripts. Background: Our database is Oracle 10g (upgrading to 11 soon). Our DBA team uses SQLPlus in order..

Can an html element have multiple ids?

I understand that an id must be unique within an HTML/XHTML page. My question is, for a given element, can I assign multiple ids to it? <div id="nested_element_123 task_123"></div> I r..

Where to place JavaScript in an HTML file?

Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via <script src="...">, not pasted into the HTML its..

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

I am trying to store a .Net TimeSpan in SQL server 2008 R2. EF Code First seems to be suggesting it should be stored as a Time(7) in SQL. However TimeSpan in .Net can handle longer periods than 24..

Python set to list

How can I convert a set to a list in Python? Using a = set(["Blah", "Hello"]) a = list(a) doesn't work. It gives me: TypeError: 'set' object is not callable ..

How to convert JSON object to JavaScript array?

I need to convert JSON object string to a JavaScript array. This my JSON object: {"2013-01-21":1,"2013-01-22":7} And I want to have: var data = new google.visualization.DataTable(); data.addColum..

Choosing the default value of an Enum type without having to change values

In C#, is it possible to decorate an Enum type with an attribute or do something else to specify what the default value should be, without having the change the values? The numbers required might be s..

.gitignore file for java eclipse project

I have java project that uses the Eclipse IDE. The Eclipse workspace is pointing to this directory: /home/srvimgprd/BUSPROJ/code_development/dime/executables/clientcode/java_axis/Eclipse I have pl..

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

I want to make a shape with with left-top rounded corner and left-bottom rounded corner: <?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/andr..

How to find where javaw.exe is installed?

So, for a project I am working on, I need to find out where a javaw.exe is located on a user's machine. How do I do that? Assuming that user is on Windows machine The method that I used is limited ..

Why use argparse rather than optparse?

I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to getopt and optparse we now have argparse. Why has yet another command-line parsing module..

iOS 7 - Failing to instantiate default view controller

I am using Xcode 5 in a newly created app and when I just create it I go for the run button e click on it, then the project gets built but it does not show in the iOS Simulator and I get the following..

npm install doesn't create node_modules directory

I am trying to do a homework for a mongodb uni course. They gave us some files, instructions are: run npm install mongodb then node app.js for some reason npm install does not create a node_modules ..

How to find column names for all tables in all databases in SQL Server

I want to find all column names in all tables in all databases. Is there a query that can do that for me? The database is Microsoft SQL Server 2000...

The remote server returned an error: (407) Proxy Authentication Required

I'm getting this error when I call a web service: "The remote server returned an error: (407) Proxy Authentication Required". I get the general idea and I can get the code to work by adding myProxy..

ERROR: permission denied for sequence cities_id_seq using Postgres

I'm new at postgres (and at database info systems all in all). I ran following sql script on my database: create table cities ( id serial primary key, name text not null ); create table reports ( id..

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

I have an application which works fine on Xcode6-Beta1 and Xcode6-Beta2 with both iOS7 and iOS8. But with Xcode6-Beta3, Beta4, Beta5 I'm facing network issues with iOS8 but everything works fine on iO..

javascript find and remove object in array based on key value

I have been trying several approaches on how to find an object in an array, where ID = var, and if found, remove the object from the array and return the new array of objects. Data: [ {"id":"88"..

Convert a space delimited string to list

i have a string like this : states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado" and I want to split it into a list like this states = {Alaska, Alabama, Arkansas, American..

Spring Boot - inject map from application.yml

I have a Spring Boot application with the following application.yml - taken basically from here: info: build: artifact: ${project.artifactId} name: ${project.name} description: $..

Automate scp file transfer using a shell script

I have some n number of files in a directory on my unix system. Is there a way to write a shellscript that will transfer all those files via scp to a specified remote system. I'll specify the password..

Convert data.frame columns from factors to characters

I have a data frame. Let's call him bob: > head(bob) phenotype exclusion GSM399350 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119- GSM399351 3- 4- 8- 25..

How to add an Access-Control-Allow-Origin header

I am designing a website (e.g. mywebsite.com) and this site loads font-face fonts from another site (say anothersite.com). I was having problems with the font face font loading in Firefox and I read o..

How to select the comparison of two columns as one column in Oracle

I cannot figure out how to add a column to my SELECT query indicating whether two columns contain the same data in Oracle. I would like to write a query like: select column1, column2, column1=column..

MVC 4 Edit modal form using Bootstrap

I'm using MVC 4 and Entity Framework to develop an intranet web application. I have a list of persons which can be modify by an edit action. I wanted to make my app more dynamic by using modal forms. ..

How to force a checkbox and text on the same line?

How can I force a checkbox and following text to appear on the same line? In the following HTML, I'd only want the line to break between label and input, not between input and label. <p><fie..

How to add row of data to Jtable from values received from jtextfield and comboboxes

I have a JFrame Form which has JTextFields, JCombobox etc. and I am able to receive those values to variables and now I want to add the received data to JTable in new row when user clicks Add or somet..

How to convert answer into two decimal point

This is my code and I want the output which is txtA.Text and txtB.Text to be in two decimal places. Public Class Form1 Private Sub btncalc_Click(ByVal sender As System.Object, ..

How to convert array to SimpleXML

How can I convert an array to a SimpleXML object in PHP?..

How to get html table td cell value by JavaScript?

I have an HTML table created with dynamic data and cannot predict the number of rows in it. What I want to do is to get the value of a cell when a row is clicked. I know to use td onclick but I do not..

how to kill the tty in unix

This is the result of the finger command (Today(Monday) when I (Vidya) logged in) sekic1083 [6:14am] [/home/vidya] -> finger Name Tty Idle Login Time Where Felix pts/0 -..

Set value for particular cell in pandas DataFrame using index

I've created a Pandas DataFrame df = DataFrame(index=['A','B','C'], columns=['x','y']) and got this x y A NaN NaN B NaN NaN C NaN NaN Then I want to assign value to particular cel..

Converting list to *args when calling function

In Python, how do I convert a list to *args? I need to know because the function scikits.timeseries.lib.reportlib.Report.__init__(*args) wants several time_series objects passed as *args, whereas ..

How to uninstall a package installed with pip install --user

There is a --user option for pip which can install a Python package per user: pip install --user [python-package-name] I used this option to install a package on a server for which I do not have ro..

Use of Java's Collections.singletonList()?

What is the use of Collections.singletonList() in Java? I understand that it returns a list with one element. Why would I want to have a separate method to do that? How does immutability play a role h..

How to remove text before | character in notepad++

I have a document like this, so i wan't to remove text before | character on any line. Work in notepad++. So what i can do? ..

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I have searched on the web for over two days now, and probably have looked through most of the online documented scenarios and workarounds, but nothing worked for me so far. I am on AWS SDK for PHP V..

Binary search (bisection) in Python

Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not? I found the functions bisect_left/right in th..

What is meant by Ems? (Android TextView)

What is meant by Ems (related to a TextView)? For example in android:ems setEms(int) Makes the TextView be exactly this many ems wide...

Word count from a txt file program

I am counting word of a txt file with the following code: #!/usr/bin/python file=open("D:\\zzzz\\names2.txt","r+") wordcount={} for word in file.read().split(): if word not in wordcount: ..

rbenv not changing ruby version

I installed rbenv according to the github directions. I am running OSX but I have tried this on a Ubuntu 12.04 VM and got the same results. The following is what i get in my terminal when I try to cha..

CSS container div not getting height

I want my container div to get the height of max of its children's height. without knowing what height the child divs are going to have. I was trying out on JSFiddle. The container div is on red. whic..

Logcat not displaying my log calls

I'm a total noob at Android programming, and wanted to learn how to debug my apps. I can't seem to have my Log.i|d|v calls displayed in the LogCat. Here's the code that I'm using. As you can see ..

jQuery posting JSON

update: I would like to pass the var value to the server hello, same old, same old ... :) I have a form called <form id="testForm" action="javascript:test()"> and a code area called <code i..

C++ vector of char array

I am trying to write a program that has a vector of char arrays and am have some problems. char test [] = { 'a', 'b', 'c', 'd', 'e' }; vector<char[]> v; v.push_back(test); Sorry this has to..

Calculate the mean by group

I have a large data frame that looks similar to this: df <- data.frame(dive = factor(sample(c("dive1","dive2"), 10, replace=TRUE)), speed = runif(10) ..

Renaming files in a folder to sequential numbers

I want to rename the files in a directory to sequential numbers. Based on creation date of the files. For Example sadf.jpg to 0001.jpg, wrjr3.jpg to 0002.jpg and so on, the number of leading zeroes d..

Print a list in reverse order with range()?

How can you produce the following list with range() in Python? [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ..

making matplotlib scatter plots from dataframes in Python's pandas

What is the best way to make a series of scatter plots using matplotlib from a pandas dataframe in Python? For example, if I have a dataframe df that has some columns of interest, I find myself typi..

How do you search an amazon s3 bucket?

I have a bucket with thousands of files in it. How can I search the bucket? Is there a tool you can recommend? ..

Chrome desktop notification example

How does one use Chrome desktop notifications? I'd like that use that in my own code. Update: Here's a blog post explaining webkit notifications with an example...

Maven Run Project

Is there a Maven "phase" or "goal" to simply execute the main method of a Java class? I have a project that I'd like to test manually by simply doing something like "mvn run"...

Annotation-specified bean name conflicts with existing, non-compatible bean def

I'm having a problem with some Spring bean definitions. I have a couple of context xml files that are being loaded by my main() method, and both of them contain almost exclusively a tag. When my main..

How to add an item to an ArrayList in Kotlin?

How to add an item to an ArrayList in Kotlin?..

Change text color with Javascript?

I want to change the color of a title when a button is clicked. This is my code, but it's not working and I can't figure out why not... <div id="about">About Snakelane</div> <..

JavaScript equivalent of PHP's in_array()

Is there a way in JavaScript to compare values from one array and see if it is in another array? Similar to PHP's in_array function?..

OSError: [Errno 8] Exec format error

I am having hard time parsing the arguments to subprocess.Popen. I am trying to execute a script on my Unix server. The script syntax when running on shell prompt is as follows: /usr/local/bin/script..

Changing background color of selected item in recyclerview

How to change the background color of only selected view in my recycle view example?only the background color of clicked itemview needs to be changed. Only one selected item must be displayed with bac..

How to clear or stop timeInterval in angularjs?

I am making a demo in which I am fetching data from the server after regular intervals of time using $interval Now I need to stop/cancel this. How I can achieve this? If I need to restart the process..

How to check if an object is defined?

I would like to check if an object is defined or exists using C#. Something like this: if (defined(Object)){ } ..

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I'm currently developing a responsive site using Twitter Bootstrap. The site has a full screen background image across mobile/tablet/desktop. These images rotate and fade through each, using two divs..

How to write UPDATE SQL with Table alias in SQL Server 2008?

I have a very basic UPDATE SQL - UPDATE HOLD_TABLE Q SET Q.TITLE = 'TEST' WHERE Q.ID = 101; This query runs fine in Oracle, Derby, MySQL - but it fails in SQL server 2008 with following error: ..

Get SSID when WIFI is connected

I'm trying to get the SSID of the WIFI network when my android device is connected to WIFI. I've registered a BroadcastReceiver listening for android.net.wifi.supplicant.CONNECTION_CHANGE . I get the..

VBA collection: list of keys

After I add some values to the VBA collection, is there any way to retain the list of all keys? For example Dim coll as new Collection Dim str1, str2, str3 str1="first string" str2="second string" ..

Some projects cannot be imported because they already exist in the workspace error in Eclipse

I am trying to import a project that me and my co-worker have been working on.. and keep getting this error after I select-- "import" then "import existing project" then click archive file, and then I..

Quick and easy file dialog in Python?

I have a simple script which parses a file and loads it's contents to a database. I don't need a UI, but right now I'm prompting the user for the file to parse using raw_input which is most unfriendly..

C# Foreach statement does not contain public definition for GetEnumerator

I'm having a problem with a Windows Form application I'm building in C#. The error is stating "foreach statement cannot operate on variables of type 'CarBootSale.CarBootSaleList' because 'CarBootSale...

How to rollback just one step using rake db:migrate

After adding migration files in the db/migrate folder and running rake db:migrate, I want get back to the previous step, I think using VERSION=n is the right way to do that, but I don't know the corre..

Clear an input field with Reactjs?

I am using a variable below. var newInput = { title: this.inputTitle.value, entry: this.inputEntry.value }; This is used by my input fields. <input type="text" id="inputname" classNa..

How do I generate a stream from a string?

I need to write a unit test for a method that takes a stream which comes from a text file. I would like to do do something like this: Stream s = GenerateStreamFromString("a,b \n c,d"); ..

error: Your local changes to the following files would be overwritten by checkout

This question is similar to this one, but more specific. I have a project with two branches: staging and beta. I develop on staging, and use the master branch to fix bugs. So if I'm working on staging..

JavaScript validation for empty input field

I have this input field <input name="question"/> I want to call IsEmpty function when submit clicking submit button. I tried the code below but did not work. any advice? _x000D_ _x000D_ <h..

PHP Regex to check date is in YYYY-MM-DD format

I'm trying to check that dates entered by end users are in the YYYY-MM-DD. Regex has never been my strong point, I keep getting a false return value for the preg_match() I have setup. So I'm assuming..

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

When I try to execute this statement in Oracle SQL Developer 2.1 a dialog box "Enter Substitution Variable" pops up asking for a replacement value for TOBAGO, update t set country = 'Trinidad and Tob..

Draw line in UIView

I need to draw a horizontal line in a UIView. What is the easiest way to do it. For example, I want to draw a black horizontal line at y-coord=200. I am NOT using Interface Builder. ..

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

I'm learning to use matplotlib by studying examples, and a lot of examples seem to include a line like the following before creating a single plot... fig, ax = plt.subplots() Here are some examples..

FIND_IN_SET() vs IN()

I have 2 tables in my database. One is for orders, and one is for companies. Orders has this structure: OrderID | attachedCompanyIDs ------------------------------------ 1 ..

How to get am pm from the date time string using moment js

I have a string as Mon 03-Jul-2017, 11:00 AM/PM and I have to convert this into a string like 11:00 AM/PM using moment js. The problem here is that I am unable to get AM or PM from the date time stri..

Optimal number of threads per core

Let's say I have a 4-core CPU, and I want to run some process in the minimum amount of time. The process is ideally parallelizable, so I can run chunks of it on an infinite number of threads and each ..

Is there a command to list all Unix group names?

I know there is the /etc/group file that lists all users groups. I would like to know if there is a simple command to list all user group names in spite of parsing the world readable /etc/group file...

How to get the Facebook user id using the access token

I have a Facebook desktop application and am using the Graph API. I am able to get the access token, but after that is done - I don't know how to get the user's ID. My flow is like this: I send t..

MySQL "WITH" clause

I'm trying to use MySQL to create a view with the "WITH" clause WITH authorRating(aname, rating) AS SELECT aname, AVG(quantity) FROM book GROUP BY aname But it doesn't seem like MySQL supp..

How to validate phone number in laravel 5.2?

I want to validate user input phone number where number should be exactly 11 and started with 01 and value field should be number only. How do I do it using Laravel validation? Here is my controller:..

jQuery attr() change img src

I'm making some Rocket launching effect by jQuery. When I click on Rocket, it'll swap with another rocket image, and then launch up. When I click "Reset" link, Rocket must reset starting location and ..

Django: Model Form "object has no attribute 'cleaned_data'"

I am trying to make a search form for one of my classes. The model of the form is: from django import forms from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField from books.m..

Check if a number is int or float

Here's how I did it: inNumber = somenumber inNumberint = int(inNumber) if inNumber == inNumberint: print "this number is an int" else: print "this number is a float" Something like that. Ar..

Print raw string from variable? (not getting the answers)

I'm trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like 'C:\\Windows\Users\alexb\', I know I..

Pad a number with leading zeros in JavaScript

In JavaScript, I need to have padding. For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits. One way..

Using cut command to remove multiple columns

given input echo 1,2,3,4,5,6,7,8,9,...100 If I want to cut columns 5 I can do cut -d, -f-4,6- what if I want to cut multiple non consecutive columns like 5, 7,etc is there a one liner?..

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Hello I'm a new programmer at an high school level as a result I do not know much about programming and am getting quite a few errors which have been resolved while others I completely do not understa..

Submit form using a button outside the <form> tag

Say I have: <form method="get" action="something.php"> <input type="text" name="name" /> </form> <input type="submit" /> How do I go about submitting that form with tha..

When or Why to use a "SET DEFINE OFF" in Oracle Database

I'm watching a Script in Oracle and I see something I don't recognize REM INSERTING into database1."Users" SET DEFINE OFF; Insert into database1."Users" ("id","right") values ('1','R'); I'm lookin..

Python: BeautifulSoup - get an attribute value based on the name attribute

I want to print an attribute value based on its name, take for example <META NAME="City" content="Austin"> I want to do something like this soup = BeautifulSoup(f) //f is some HTML containin..

Giving my function access to outside variable

I have an array outside: $myArr = array(); I would like to give my function access to the array outside it so it can add values to it function someFuntion(){ $myVal = //some processing here t..

Best way to read a large file into a byte array in C#?

I have a web server which will read large binary files (several megabytes) into byte arrays. The server could be reading several files at the same time (different page requests), so I am looking for t..

Difference between final and effectively final

I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know that when I use variables inside anonymous c..

How to create json by JavaScript for loop?

I have array of select tag. <select id='uniqueID' name="status"> <option value="1">Present</option> <option value="2">Absent</option> </select> and ..

Change the Arrow buttons in Slick slider

I want to change the arrows in my slick slider but it does not change. I want the next and previous button as an image. I have tried putting it in a <style> but it still not working. Where can I..

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I am getting below stack trace when I am deploying my application in a multi-server Apache Tomcat 8 environment. I am getting this error frequently, and it seems it is blocking the tomcat thread: INFO..

Show all current locks from get_lock

Is there any way to select / show all current locks that have been taken out using the GET_LOCK function? Note that GET_LOCK locks are different from table locks, like those acquired with LOCK TABLES..

How to connect PHP with Microsoft Access database

I am currently faced with a new challenge to develop a site using Microsoft Access as the primary database instead of mysql. I have not used MS Access before and I would like guidiance on how to go ab..

Send form data using ajax

I want to send all input in a form with ajax .I have a form like this. <form action="target.php" method="post" > <input type="text" name="lname" /> <input type="text" name="fn..

Where to find htdocs in XAMPP Mac

I cannot find the htdocs directory anywhere on XAMPP for Mac. Many videos on YouTube show people just clicking a button that says "Go to application folder" but on my user interface, it reads: "Go to..

Sorting HashMap by values

I need to sort my HashMap according to the values stored in it. The HashMap contains the contacts name stored in phone. Also I need that the keys get automatically sorted as soon as I sort the values..

How to export a Hive table into a CSV file?

I used this Hive query to export a table into a CSV file. INSERT OVERWRITE DIRECTORY '/user/data/output/test' select column1, column2 from table1; The file generated '000000_0' does not have comma ..

Windows service with timer

I have created a windows service with timer in c#.net. it works fine while i debug/build the project in visual studio but it does not perform its operation after installation. What might be the reaso..

MySQL: is a SELECT statement case sensitive?

Can anyone tell me if a MySQL SELECT query is case sensitive or case insensitive by default? And if not, what query would I have to send so that I can do something like: SELECT * FROM `table` WHERE `..

Convert YYYYMMDD to DATE

I have a bunch of dates in varchar like this: 20080107 20090101 20100405 ... How do I convert them to a date format like this: 2008-01-07 2009-01-01 2010-04-05 I've tried using this: SELECT [FI..

PHP how to get local IP of system

I need to get local IP of computer like 192.*.... Is this possible with PHP? I need IP address of system running the script, but I do not need the external IP, I need his local network card address...

How can I convert an image into Base64 string using JavaScript?

I need to convert my image to a Base64 string so that I can send my image to a server. Is there any JavaScript file for this? Else, how can I convert it?..

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

I'm having a problem executing some SQL from within Python, despite similar SQL working fine from the mysql command-line. The table looks like this: mysql> SELECT * FROM foo; +-------+-----+ | fo..

How to create <input type=“text”/> dynamically

I want to create an input type text in my web form dynamically. More specifically, I have a textfield where the user enters the number of desired text fields; I want the text fields to be generated dy..

Colorplot of 2D array matplotlib

So, I thought this was going to be really simple, but I've been having a lot of difficult finding exactly what I'm looking for in a comprehensible example. Basically I want to make phase plots, so as..

Get key by value in dictionary

I made a function which will look up ages in a Dictionary and show the matching name: dictionary = {'george' : 16, 'amber' : 19} search_age = raw_input("Provide age") for age in dictionary.values(): ..

How to set a parameter in a HttpServletRequest?

I am using a javax.servlet.http.HttpServletRequest to implement a web application. I have no problem to get the parameter of a request using the getParameter method. However I don't know how to set a..

Get the current script file name

If I have PHP script, how can I get the filename from inside that script? Also, given the name of a script of the form jquery.js.php, how can I extract just the "jquery.js" part?..

Laravel 5.2 not reading env file

After upgrading to Laravel 5.2, none of my .env file values are being read. I followed the upgrade instructions; none of my config files were changed except auth.php. They were all working fine in pre..

How do I align spans or divs horizontally?

My only problem is making them line up three-across and have equal spacing. Apparently, spans can not have width and divs (and spans with display:block) don't appear horizontally next to each other. S..

How do I do pagination in ASP.NET MVC?

What is the most preferred and easiest way to do pagination in ASP.NET MVC? I.e. what is the easiest way to break up a list into several browsable pages. As an example lets say I get a list of eleme..

using jquery $.ajax to call a PHP function

This may be a simple answer, but I'm using jQuery's $.ajax to call a PHP script. What I want to do is basically put that PHP script inside a function and call the PHP function from javascript. <?..

When are static variables initialized?

I am wondering when static variables are initialized to their default values. Is it correct that when a class is loaded, static vars are created (allocated), then static initializers and initializatio..

How to write string literals in python without having to escape them?

Is there a way to declare a string variable in python such that everything inside of it is automatically escaped, or has its literal character value? I'm not asking how to escape the quotes with sla..

PadLeft function in T-SQL

I have the following table A: id ---- 1 2 12 123 1234 I need to left-pad the id values with zero's: id ---- 0001 0002 0012 0123 1234 How can I achieve this?..

SQL - Update multiple records in one query

I have table - config. Schema: config_name | config_value And I would like to update multiple records in one query. I try like that: UPDATE config SET t1.config_value = 'value' , t2.config_value..