Programs & Examples On #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.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();

Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?

Parsing JSON from URL

I use java 1.8 with com.fasterxml.jackson.databind.ObjectMapper

ObjectMapper mapper = new ObjectMapper();
Integer      value = mapper.readValue(new URL("your url here"), Integer.class);

Integer.class can be also a complex type. Just for example used.

Initializing multiple variables to the same value in Java

String one, two, three;
one = two = three = "";

This should work with immutable objects. It doesn't make any sense for mutable objects for example:

Person firstPerson, secondPerson, thirdPerson;
firstPerson = secondPerson = thirdPerson = new Person();

All the variables would be pointing to the same instance. Probably what you would need in that case is:

Person firstPerson = new Person();
Person secondPerson = new Person();
Person thirdPerson = new Person();

Or better yet use an array or a Collection.

Avoid synchronized(this) in Java?

A good example for use synchronized(this).

// add listener
public final synchronized void addListener(IListener l) {listeners.add(l);}
// remove listener
public final synchronized void removeListener(IListener l) {listeners.remove(l);}
// routine that raise events
public void run() {
   // some code here...
   Set ls;
   synchronized(this) {
      ls = listeners.clone();
   }
   for (IListener l : ls) { l.processEvent(event); }
   // some code here...
}

As you can see here, we use synchronize on this to easy cooperate of lengthly (possibly infinite loop of run method) with some synchronized methods there.

Of course it can be very easily rewritten with using synchronized on private field. But sometimes, when we already have some design with synchronized methods (i.e. legacy class, we derive from, synchronized(this) can be the only solution).

Android: how to hide ActionBar on certain activities

Replace AndroidManifest.xml

android:theme="@style/FullscreenTheme"

to

android:theme="@style/Theme.Design.NoActionBar"

Java string split with "." (dot)

This is because . is a reserved character in regular expression, representing any character. Instead, we should use the following statement:

String extensionRemoved = filename.split("\\.")[0];

Java: Insert multiple rows into MySQL with PreparedStatement

If you can create your sql statement dynamically you can do following workaround:

String myArray[][] = { { "1-1", "1-2" }, { "2-1", "2-2" }, { "3-1", "3-2" } };

StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");

for (int i = 0; i < myArray.length - 1; i++) {
    mySql.append(", (?, ?)");
}

myStatement = myConnection.prepareStatement(mySql.toString());

for (int i = 0; i < myArray.length; i++) {
    myStatement.setString(i, myArray[i][1]);
    myStatement.setString(i, myArray[i][2]);
}
myStatement.executeUpdate();

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

I had the same problem for one of the activities in my app , one of the causes of this problem is that Theme in the theme editor might be different than the theme defined in the 'styles.xml'.change the Theme in the theme editor to your 'Apptheme' or your custom defined theme(if you have defined). Doing this fixed my issue.

No Persistence provider for EntityManager named

You need the following jar files in the classpath:

  1. antlr-2.7.6.jar
  2. commons-collections-3.1.jar
  3. dom4j-1.6.1.jar
  4. hibernate-commons-annotations-4.0.1.Final.jar
  5. hibernate-core-4.0.1.Final.jar
  6. hibernate-entitymanager.jar
  7. hibernate-jpa-2.0-api-1.0.0.Final.jar
  8. javassist-3.9.0.jar
  9. jboss-logging-3.1.1.GA.jar
  10. jta-1.1.jar
  11. slf4j-api-1.5.8.jar
  12. xxx-jdbc-driver.jar

Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:

<properties>
    <javac.src.version>1.8</javac.src.version>
    <javac.target.version>1.8</javac.target.version>
</properties>

It should be the same thing of maven.compiler.source/maven.compiler.target but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

Changing java platform on which netbeans runs

For anyone on Mac OS X, you can find netbeans.conf here:

/Applications/NetBeans/NetBeans <version>.app/Contents/Resources/NetBeans/etc/netbeans.conf

In case anyone needs to know :)

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

How to access nested elements of json object using getJSONArray method

Try this code using Gson library and get the things done.

Gson gson = new GsonBuilder().create();

JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");

String str = entry.toString();

System.out.println(str);

In Java, how do I check if a string contains a substring (ignoring case)?

I also favor the RegEx solution. The code will be much cleaner. I would hesitate to use toLowerCase() in situations where I knew the strings were going to be large, since strings are immutable and would have to be copied. Also, the matches() solution might be confusing because it takes a regular expression as an argument (searching for "Need$le" cold be problematic).

Building on some of the above examples:

public boolean containsIgnoreCase( String haystack, String needle ) {
  if(needle.equals(""))
    return true;
  if(haystack == null || needle == null || haystack .equals(""))
    return false; 

  Pattern p = Pattern.compile(needle,Pattern.CASE_INSENSITIVE+Pattern.LITERAL);
  Matcher m = p.matcher(haystack);
  return m.find();
}

example call: 

String needle = "Need$le";
String haystack = "This is a haystack that might have a need$le in it.";
if( containsIgnoreCase( haystack, needle) ) {
  System.out.println( "Found " + needle + " within " + haystack + "." );
}

(Note: you might want to handle NULL and empty strings differently depending on your needs. I think they way I have it is closer to the Java spec for strings.)

Speed critical solutions could include iterating through the haystack character by character looking for the first character of the needle. When the first character is matched (case insenstively), begin iterating through the needle character by character, looking for the corresponding character in the haystack and returning "true" if all characters get matched. If a non-matched character is encountered, resume iteration through the haystack at the next character, returning "false" if a position > haystack.length() - needle.length() is reached.

Difference between "on-heap" and "off-heap"

from http://code.google.com/p/fast-serialization/wiki/QuickStartHeapOff

What is Heap-Offloading ?

Usually all non-temporary objects you allocate are managed by java's garbage collector. Although the VM does a decent job doing garbage collection, at a certain point the VM has to do a so called 'Full GC'. A full GC involves scanning the complete allocated Heap, which means GC pauses/slowdowns are proportional to an applications heap size. So don't trust any person telling you 'Memory is Cheap'. In java memory consumtion hurts performance. Additionally you may get notable pauses using heap sizes > 1 Gb. This can be nasty if you have any near-real-time stuff going on, in a cluster or grid a java process might get unresponsive and get dropped from the cluster.

However todays server applications (frequently built on top of bloaty frameworks ;-) ) easily require heaps far beyond 4Gb.

One solution to these memory requirements, is to 'offload' parts of the objects to the non-java heap (directly allocated from the OS). Fortunately java.nio provides classes to directly allocate/read and write 'unmanaged' chunks of memory (even memory mapped files).

So one can allocate large amounts of 'unmanaged' memory and use this to save objects there. In order to save arbitrary objects into unmanaged memory, the most viable solution is the use of Serialization. This means the application serializes objects into the offheap memory, later on the object can be read using deserialization.

The heap size managed by the java VM can be kept small, so GC pauses are in the millis, everybody is happy, job done.

It is clear, that the performance of such an off heap buffer depends mostly on the performance of the serialization implementation. Good news: for some reason FST-serialization is pretty fast :-).

Sample usage scenarios:

  • Session cache in a server application. Use a memory mapped file to store gigabytes of (inactive) user sessions. Once the user logs into your application, you can quickly access user-related data without having to deal with a database.
  • Caching of computational results (queries, html pages, ..) (only applicable if computation is slower than deserializing the result object ofc).
  • very simple and fast persistance using memory mapped files

Edit: For some scenarios one might choose more sophisticated Garbage Collection algorithms such as ConcurrentMarkAndSweep or G1 to support larger heaps (but this also has its limits beyond 16GB heaps). There is also a commercial JVM with improved 'pauseless' GC (Azul) available.

Is a Java hashmap search really O(1)?

Of course the performance of the hashmap will depend based on the quality of the hashCode() function for the given object. However, if the function is implemented such that the possibility of collisions is very low, it will have a very good performance (this is not strictly O(1) in every possible case but it is in most cases).

For example the default implementation in the Oracle JRE is to use a random number (which is stored in the object instance so that it doesn't change - but it also disables biased locking, but that's an other discussion) so the chance of collisions is very low.

How to execute logic on Optional if not present?

With Java 8 Optional it can be done with:

    Optional<Obj> obj = dao.find();

    obj.map(obj.setAvailable(true)).orElseGet(() -> {
        logger.fatal("Object not available");
        return null;
    });

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If your jar file already has an absolute pathname as shown, it is particularly easy:

cd /where/you/want/it; jar xf /path/to/jarfile.jar

That is, you have the shell executed by Python change directory for you and then run the extraction.

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 jar can find it after the change of directory.

The only issues left to worry about are things like blanks in the path names.

How to convert BigDecimal to Double in Java?

You can convert BigDecimal to double using .doubleValue(). But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal objects directly. Precision loss in these calculations are big time problems in currency related calculations.

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

I see this issue come up a lot. Yes, Tomcat 7 does automatically deregister it, but it that REALLY taking control of your code and a good coding practice? Surely YOU want to know that you have all the correct code in place to close all your objects, shut down database connection pool threads, and get rid of all warnings. I certainly do.

This is how I do it.

Step 1: Register a Listener

web.xml

<listener>
    <listener-class>com.mysite.MySpecialListener</listener-class>
</listener>

Step 2: Implement the Listener

com.mysite.MySpecialListener.java

public class MySpecialListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // On Application Startup, please…

        // Usually I'll make a singleton in here, set up my pool, etc.
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // On Application Shutdown, please…

        // 1. Go fetch that DataSource
        Context initContext = new InitialContext();
        Context envContext  = (Context)initContext.lookup("java:/comp/env");
        DataSource datasource = (DataSource)envContext.lookup("jdbc/database");

        // 2. Deregister Driver
        try {
            java.sql.Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/");
            DriverManager.deregisterDriver(mySqlDriver);
        } catch (SQLException ex) {
            logger.info("Could not deregister driver:".concat(ex.getMessage()));
        } 

        // 3. For added safety, remove the reference to dataSource for GC to enjoy.
        dataSource = null;
    }

}

Please feel free to comment and/or add...

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

What is the use of static synchronized method in java?

static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.lang.class class object is there. That object's lock is needed for.static synchronized methods. So when you have a static field which should be restricted to be accessed by multiple threads at once you can set those fields private and create public static synchronized setters or getters to access those fields.

Mocking Logger and LoggerFactory with PowerMock and Mockito

I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Should use Entity class name for em.createQuery method or Should use em.createNativeQuery method for native query without entity class

With Entity class:

em.createQuery("select first_name from CUSTOMERV")

Without Entity class or Native query:

em.createNativeQuery("select c.first_name from CUSTOMERV c")

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

This code will work like charm and use the restTemple object for rest of the code.

  RestTemplate restTemplate = new RestTemplate();   
  TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
                return true;
            }

        };

        SSLContext sslContext = null;
        try {
            sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        restTemplate.setRequestFactory(requestFactory);
}

How to update PATH variable permanently from Windows command line?

In a corporate network, where the user has only limited access and uses portable apps, there are these command line tricks:

  1. Query the user env variables: reg query "HKEY_CURRENT_USER\Environment". Use "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" for LOCAL_MACHINE.
  2. Add new user env variable: reg add "HKEY_CURRENT_USER\Environment" /v shared_dir /d "c:\shared" /t REG_SZ. Use REG_EXPAND_SZ for paths containing other %% variables.
  3. Delete existing env variable: reg delete "HKEY_CURRENT_USER\Environment" /v shared_dir.

Spring Boot application can't resolve the org.springframework.boot package

Right button on project -> Maven -> Update Project

then check "Force update of Snapshots/Releases"

Java 8 NullPointerException in Collectors.toMap

Retaining all questions ids with small tweak

Map<Integer, Boolean> answerMap = 
  answerList.stream()
            .collect(Collectors.toMap(Answer::getId, a -> 
                       Boolean.TRUE.equals(a.getAnswer())));

How to call a method after a delay in Android

Using Kotlin, we can achieve by doing the following

Handler().postDelayed({
    // do something after 1000ms 
}, 1000)

Simple way to sort strings in the (case sensitive) alphabetical order

I recently answered a similar question here. Applying the same approach to your problem would yield following solution:

list.sort(
  p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
    public P2<String, String> f(String s) {
      return p(s.toLowerCase(), s);
    }
  })
);

IntelliJ - Convert a Java project/module into a Maven project/module

  1. Open 'Maven projects' (tab on the right side).
  2. Use 'Add Maven Projects'
  3. Find your pom.xml

How to read a configuration file in Java

Create a configuration file and put your entries there.

SERVER_PORT=10000     
THREAD_POOL_COUNT=3     
ROOT_DIR=/home/   

You can load this file using Properties.load(fileName) and retrieved values you get(key);

How Best to Compare Two Collections in Java and Act on Them?

For a set that small is generally not worth it to convert from an Array to a HashMap/set. In fact, you're probably best off keeping them in an array and then sorting them by key and iterating over both lists simultaneously to do the comparison.

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Most of the answers for this question can not helped me in 2020.

This notification from download site of Oracle may be the reason:

Important Oracle JDK License Update

The Oracle JDK License has changed for releases starting April 16, 2019.

I try to google a little bit and those tutorials below helped me a lot.

  1. Remove completely the previous version of JVM installed on your PC.

    sudo update-alternatives --remove-all java
    sudo update-alternatives --remove-all javac
    sudo update-alternatives --remove-all javaws
    
    # /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
    sudo rm -rf /usr/lib/jvm/jdk1.7.0 
    

    Check to see whether java is uninstalled or not

    java -version
    
  2. Install Java 8 JDK.

    • Download Java 8 from Oracle's website. The version being used is 1.8.0_251. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.
    • Extract the compressed file to the place where you want to install.

    cd /usr/lib/jvm
    sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
    
    • Edit environment file

    sudo gedit /etc/environment
    
    • Edit the PATH's value by appending the string below to the current value

    :/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
    
    • Append those strings to the environment file

    J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
    J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
    JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
    
    • Complete the installation by running commands below

    sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
    sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
    sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
    sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
    
    update-alternatives --list java
    update-alternatives --list javac
    

Maven dependency for Servlet 3.0 API?

I'd prefer to only add the Servlet API as dependency,

To be honest, I'm not sure to understand why but never mind...

Brabster separate dependencies have been replaced by Java EE 6 Profiles. Is there a source that confirms this assumption?

The maven repository from Java.net indeed offers the following artifact for the WebProfile:

<repositories>
  <repository>
    <id>java.net2</id>
    <name>Repository hosting the jee6 artifacts</name>
    <url>http://download.java.net/maven/2</url>
  </repository>
</repositories>        
<dependencies>
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>

This jar includes Servlet 3.0, EJB Lite 3.1, JPA 2.0, JSP 2.2, EL 1.2, JSTL 1.2, JSF 2.0, JTA 1.1, JSR-45, JSR-250.

But to my knowledge, nothing allows to say that these APIs won't be distributed separately (in java.net repository or somewhere else). For example (ok, it may a particular case), the JSF 2.0 API is available separately (in the java.net repository):

<dependency>
   <groupId>com.sun.faces</groupId>
   <artifactId>jsf-api</artifactId>
   <version>2.0.0-b10</version>
   <scope>provided</scope>
</dependency>

And actually, you could get javax.servlet-3.0.jar from there and install it in your own repository.

Swing vs JavaFx for desktop applications

I don't think there's any one right answer to this question, but my advice would be to stick with SWT unless you are encountering severe limitations that require such a massive overhaul.

Also, SWT is actually newer and more actively maintained than Swing. (It was originally developed as a replacement for Swing using native components).

Long vs Integer, long vs int, what to use and when?

An int is a 32-bit integer; a long is a 64-bit integer. Which one to use depends on how large the numbers are that you expect to work with.

int and long are primitive types, while Integer and Long are objects. Primitive types are more efficient, but sometimes you need to use objects; for example, Java's collection classes can only work with objects, so if you need a list of integers you have to make it a List<Integer>, for example (you can't use int in a List directly).

Spring-boot default profile for integration tests

Another programatically way to do that:

  import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME;

  @BeforeClass
  public static void setupTest() {
    System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "test");
  }

It works great.

How to Ping External IP from Java Android

Run the ping utility in Android's command and parse output (assuming you have root permissions)

See the following Java code snippet:

executeCmd("ping -c 1 -w 1 google.com", false);

public static String executeCmd(String cmd, boolean sudo){
    try {

        Process p;
        if(!sudo)
            p= Runtime.getRuntime().exec(cmd);
        else{
            p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String s;
        String res = "";
        while ((s = stdInput.readLine()) != null) {
            res += s + "\n";
        }
        p.destroy();
        return res;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";

}

How to see JavaDoc in IntelliJ IDEA?

Use View | Quick Documentation or the corresponding keyboard shortcut (by default: Ctrl+Q on Windows/Linux and Ctrl+J on macOS or F1 in the recent IDE versions). See the documentation for more information.

It's also possible to enable automatic JavaDoc popup on explicit (invoked by a shortcut) code completion in Settings | Editor | General | Code completion (Autopopup documentation):

autopopup documentation

Yet another way to see the quick doc is on mouse move:

on mouse move

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

Here is the code for Right click on a webelement.

Actions actions = new Actions(driver);    
Action action=actions.contextClick(WebElement).build(); //pass WebElement as an argument
            action.perform();

Java Programming: call an exe from Java and passing parameters

import java.io.IOException;
import java.lang.ProcessBuilder;

public class handlingexe {
    public static void main(String[] args) throws IOException {
        ProcessBuilder p = new ProcessBuilder();
        System.out.println("Started EXE");
        p.command("C:\\Users\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");   

        p.start();
        System.out.println("Started EXE"); 
    }
}

Checking for a null int value from a Java ResultSet

AFAIK you can simply use

iVal = rs.getInt("ID_PARENT");
if (rs.wasNull()) {
  // do somthing interesting to handle this situation
}

even if it is NULL.

Java 8 lambda get and remove element from list

The direct solution would be to invoke ifPresent(consumer) on the Optional returned by findFirst(). This consumer will be invoked when the optional is not empty. The benefit also is that it won't throw an exception if the find operation returned an empty optional, like your current code would do; instead, nothing will happen.

If you want to return the removed value, you can map the Optional to the result of calling remove:

producersProcedureActive.stream()
                        .filter(producer -> producer.getPod().equals(pod))
                        .findFirst()
                        .map(p -> {
                            producersProcedureActive.remove(p);
                            return p;
                        });

But note that the remove(Object) operation will again traverse the list to find the element to remove. If you have a list with random access, like an ArrayList, it would be better to make a Stream over the indexes of the list and find the first index matching the predicate:

IntStream.range(0, producersProcedureActive.size())
         .filter(i -> producersProcedureActive.get(i).getPod().equals(pod))
         .boxed()
         .findFirst()
         .map(i -> producersProcedureActive.remove((int) i));

With this solution, the remove(int) operation operates directly on the index.

How to randomly pick an element from an array

Since you have java 8, another solution is to use Stream API.

new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));

Where 1 is the lowest int generated (inclusive) and 500 is the highest (exclusive). limit means that your stream will have a length of 500.

 int[] list = new int[] {1,2,3,4,5,6};
 new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p])); 

Random is from java.util package.

replace String with another in java

There is a possibility not to use extra variables

String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);

Masking password input from the console : Java

Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");

How to load a jar file at runtime

Reloading existing classes with existing data is likely to break things.

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

Of course debugging systems can do fancier things, but are more hacky and less reliable.

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

Maven Modules + Building a Single Specific Module

Say Parent pom.xml contains 6 modules and you want to run A, B and F.

<modules>
        <module>A</module>
        <module>B</module>
        <module>C</module>
        <module>D</module>
        <module>E</module>
        <module>F</module>
  </modules>

1- cd into parent project

 mvn --projects A,B,F --also-make clean install

OR

mvn -pl A,B,F -am clean install

OR

mvn -pl A,B,F -amd clean install

Note: When you specify a project with the -am option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.

While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or --also-make-dependents option configures Maven to build a project and any project that depends on that project. When using --also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

I tried this simple thing and it seems to be working.

file.setWritable(true);
file.delete();

It works for me.

If this does not work try to run your Java application with sudo if on linux and as administrator when on windows. Just to make sure Java has rights to change the file properties.

CXF: No message body writer found for class - automatically mapping non-simple resources

In my scenario, i faced similar error, when the rest url without port number is not properly configured for load balancing. I verified the rest url with portnumber and this issue was not occurring. so we had to update the load balancing configuration to resolve this issue.

How to get the caller class in Java

The error message the OP is encountering is just an Eclipse feature. If you are willing to tie your code to a specific maker (and even version) of the JVM, you can effectively use method sun.reflect.Reflection.getCallerClass(). You can then compile the code outside of Eclipse or configure it not to consider this diagnostic an error.

The worse Eclipse configuration is to disable all occurrences of the error by:

Project Properties / Java Compiler / Errors/Warnings / Enable project specific settings set to checked / Deprecated and restrited API / Forbidden reference (access rules) set to Warning or Ignore.

The better Eclipse configuration is to disable a specific occurrence of the error by:

Project Properties / Java Build Path / Libraries / JRE System Library expand / Access rules: select / Edit... / Add... / Resolution: set to Discouraged or Accessible / Rule Pattern set to sun/reflect/Reflection.

Check if element is clickable in Selenium Java

There are instances when element.isDisplayed() && element.isEnabled() will return true but still element will not be clickable, because it is hidden/overlapped by some other element.

In such case, Exception caught is:

org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (781, 704). Other element would receive the click: <div class="footer">...</div>

Use this code instead:

WebElement  element=driver.findElement(By.xpath"");  
JavascriptExecutor ex=(JavascriptExecutor)driver;
ex.executeScript("arguments[0].click()", element);

It will work.

Java client certificates over HTTPS/SSL

I think you have an issue with your server certificate, is not a valid certificate (I think this is what "handshake_failure" means in this case):

Import your server certificate into your trustcacerts keystore on client's JRE. This is easily done with keytool:

keytool
    -import
    -alias <provide_an_alias>
    -file <certificate_file>
    -keystore <your_path_to_jre>/lib/security/cacerts

No String-argument constructor/factory method to deserialize from String value ('')

mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

My code work well just as the answer above. The reason is that the json from jackson is different with the json sent from controller.

String test1= mapper.writeValueAsString(result1);

And the json is like(which can be deserialized normally):

{"code":200,"message":"god","data":[{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"AAAA","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null},{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"BBBB","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null}]}

but the json send from the another service just like:

{"code":200,"message":"????????","data":[{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"csrgzbsjy","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"B-jiegou-all-15","desktop_id":"6360ee29-eb82-416b-aab8-18ded887e8ff","created":"2018-11-12T07:45:15.000Z","ip_address":"192.168.2.215","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""},{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"glory_2147","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"H-pkpm-all-357","desktop_id":"709164e4-d3e6-495d-9c1e-a7b82e30bc83","created":"2018-11-09T09:54:09.000Z","ip_address":"192.168.2.235","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""}]}

You can notice the difference when dealing with the param without initiation. Be careful

Test class with a new() call in it with Mockito

For the future I would recommend Eran Harel's answer (refactoring moving new to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

In your case you should write:

TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);

How to read input with multiple lines in Java

A lot of student exercises use Scanner because it has a variety of methods to parse numbers. I usually just start with an idiomatic line-oriented filter:

import java.io.*;

public class FilterLine {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(
            new InputStreamReader(System.in));
        String s;

        while ((s = in.readLine()) != null) {
            System.out.println(s);
        }
    }
}

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

various option are available such as:

 Double d= 123.12;
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64); // b = 123.1200000
b = b.setScale(2, BigDecimal.ROUND_HALF_UP);  // b = 123.12

BigDecimal b1 =new BigDecimal(collectionFileData.getAmount(), MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_HALF_UP)  // b1= 123.12

 d = (double) Math.round(d * 100) / 100;
BigDecimal b2 = new BigDecimal(d.toString());  // b2= 123.12



Entry point for Java applications: main(), init(), or run()?

This is a peculiar question because it's not supposed to be a matter of choice.

When you launch the JVM, you specify a class to run, and it is the main() of this class where your program starts.

By init(), I assume you mean the JApplet method. When an applet is launched in the browser, the init() method of the specified applet is executed as the first order of business.

By run(), I assume you mean the method of Runnable. This is the method invoked when a new thread is started.

  • main: program start
  • init: applet start
  • run: thread start

If Eclipse is running your run() method even though you have no main(), then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.

Is it possible to use Java 8 for Android development?

I figured I would post an updated answer for those looking at for something a little more current.

Currently Android and Android Studio are supporting a subset of Java 8 features. According to the Android documentation located on their website, Google says:

Support for Java 8 language features requires a new compiler called Jack. Jack is supported only on Android Studio 2.1 and higher. So if you want to use Java 8 language features, you need to use Android Studio 2.1 to build your app.

If you already have Android Studio installed, make sure you update to the latest version by clicking Help > Check for Update (on Mac, Android Studio > Check for Updates). If you don't already have the IDE installed on your workstation, download Android Studio here.

Supported Java 8 Language Features and APIs

Android does not support all Java 8 language features. However, the following features are available when developing apps targeting Android 7.0 (API level 24):

  • Default and static interface methods Lambda expressions (also available on API level 23 and lower)
  • Repeatable annotations
  • Method References (also available on API level 23 and lower)
  • Type Annotations (also available on API level 23 and lower)

Additionally, the following Java 8 language APIs are also available:

Reflection and language-related APIs:

  • java.lang.FunctionalInterface
  • java.lang.annotation.Repeatable
  • java.lang.reflect.Method.isDefault() and Reflection APIs associated with repeatable annotations, such as AnnotatedElement.getAnnotationsByType(Class)

Utility APIs:

  • java.util.function
  • java.util.stream

In order to use the new Java 8 language features, you need to also use the Jack toolchain. This new Android toolchain compiles Java language sources into Android-readable DEX bytecode, has its own .jack library format, and provides most toolchain features as part of a single tool: repackaging, shrinking, obfuscation and multidex.

Here is a comparison of the two toolchains used to build Android DEX files:

Legacy javac toolchain:
    javac (.java ? .class) ? dx (.class ? .dex)
    New Jack toolchain:
    Jack (.java ? .jack ? .dex)

Error - trustAnchors parameter must be non-empty

This fixed the problem for me on Ubuntu:

sudo /var/lib/dpkg/info/ca-certificates-java.postinst configure

(found here: https://bugs.launchpad.net/ubuntu/+source/ca-certificates-java/+bug/1396760)

ca-certificates-java is not a dependency in the Oracle JDK/JRE so this must be explicitly installed.

How do I analyze a .hprof file?

If you want to do a custom analysis of your heapdump then there's:

This library is fast but you will need to write your analysis code in Java.

From the docs:

  • Does not create any temporary files on disk to process heap dump
  • Can work directly GZ compressed heap dumps
  • HeapPath notation

oracle.jdbc.driver.OracleDriver ClassNotFoundException

In Eclipse,

When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.

Store an array in HashMap

Yes, the Map interface will allow you to store Arrays as values. Here's a very simple example:

int[] val = {1, 2, 3};
Map<String, int[]> map = new HashMap<String, int[]>();
map.put("KEY1", val);

Also, depending on your use case you may want to look at the Multimap support offered by guava.

Java JDBC - How to connect to Oracle using Service Name instead of SID

When using dag instead of thin, the syntax below pointing to service name worked for me. The jdbc:thin solutions above did not work.

jdbc:dag:oracle://HOSTNAME:1521;ServiceName=SERVICE_NAME

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

How do I iterate through the files in a directory in Java?

You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

Here's a basic kickoff example:

package com.stackoverflow.q3154488;

import java.io.File;

public class Demo {

    public static void main(String... args) {
        File dir = new File("/path/to/dir");
        showFiles(dir.listFiles());
    }

    public static void showFiles(File[] files) {
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory: " + file.getAbsolutePath());
                showFiles(file.listFiles()); // Calls same method again.
            } else {
                System.out.println("File: " + file.getAbsolutePath());
            }
        }
    }
}

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

    public static void main(String... args) throws Exception {
        Path dir = Paths.get("/path/to/dir");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());
        }
    }
}

tomcat - CATALINA_BASE and CATALINA_HOME variables

That is the parent folder of bin which contains tomcat.exe file:

CATALINA_HOME='C:\Program Files\Apache Software Foundation\Tomcat 6.0'

CATALINA_BASE is the same as CATALINA_HOME.

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

Android Activity without ActionBar

You may also change inheritance from ActionBarActivity to Activity as written here.

UPDATE

A good solution is here:

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);
}

Comparing two java.util.Dates to see if they are in the same day

private boolean isSameDay(Date date1, Date date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);
        boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
        boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
        boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
        return (sameDay && sameMonth && sameYear);
    }

Getting the name of the currently executing method

January 2009:
A full code would be (to use with @Bombe's caveat in mind):

/**
 * Get the method name for a depth in call stack. <br />
 * Utility function
 * @param depth depth in the call stack (0 means current method, 1 means call method, ...)
 * @return method name
 */
public static String getMethodName(final int depth)
{
  final StackTraceElement[] ste = Thread.currentThread().getStackTrace();

  //System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
  // return ste[ste.length - depth].getMethodName();  //Wrong, fails for depth = 0
  return ste[ste.length - 1 - depth].getMethodName(); //Thank you Tom Tresansky
}

More in this question.

Update December 2011:

bluish comments:

I use JRE 6 and gives me incorrect method name.
It works if I write ste[2 + depth].getMethodName().

  • 0 is getStackTrace(),
  • 1 is getMethodName(int depth) and
  • 2 is invoking method.

virgo47's answer (upvoted) actually computes the right index to apply in order to get back the method name.

How to handle Pop-up in Selenium WebDriver using Java

You can use the below code inside your code when you get any web browser pop-up alert message box.

// Accepts (Click on OK) Chrome Alert Browser for RESET button.

Alert alertOK = driver.switchTo().alert();
alertOK.accept();



//Rejects (Click on Cancel) Chrome Browser Alert for RESET button.

Alert alertCancel = driver.switchTo().alert();
alertCancel.dismiss();

How to check how many letters are in a string in java?

1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 

How to add local jar files to a Maven project?

To install third party jar, Please call the command like below

mvn install:install-file -DgroupId= -DartifactId= -Dversion= -Dpackaging=jar -Dfile=path

JDBC connection failed, error: TCP/IP connection to host failed

Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager. enter image description here

If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start. In some cases above state can stop though TCP connection to port 1433 is assigned.

Is it good practice to use the xor operator for boolean checks?

You could always just wrap it in a function to give it a verbose name:

public static boolean XOR(boolean A, boolean B) {
    return A ^ B;
}

But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.

You can also use XOR to swap the values in two variables without using a third temporary variable.

// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;

Here's a Stackoverflow question related to XOR swapping.

Regex Named Groups in Java

Yes but its messy hacking the sun classes. There is a simpler way:

http://code.google.com/p/named-regexp/

named-regexp is a thin wrapper for the standard JDK regular expressions implementation, with the single purpose of handling named capturing groups in the .net style : (?...).

It can be used with Java 5 and 6 (generics are used).

Java 7 will handle named capturing groups , so this project is not meant to last.

How to play .wav files with java

A class that will play a WAV file, blocking until the sound has finished playing:

class Sound implements Playable {

    private final Path wavPath;
    private final CyclicBarrier barrier = new CyclicBarrier(2);

    Sound(final Path wavPath) {

        this.wavPath = wavPath;
    }

    @Override
    public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {

        try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
             final Clip clip = AudioSystem.getClip()) {

            listenForEndOf(clip);
            clip.open(audioIn);
            clip.start();
            waitForSoundEnd();
        }
    }

    private void listenForEndOf(final Clip clip) {

        clip.addLineListener(event -> {
            if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
        });
    }

    private void waitOnBarrier() {

        try {

            barrier.await();
        } catch (final InterruptedException ignored) {
        } catch (final BrokenBarrierException e) {

            throw new RuntimeException(e);
        }
    }

    private void waitForSoundEnd() {

        waitOnBarrier();
    }
}

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

What is a stack trace, and how can I use it to debug my application errors?

I am posting this answer so the topmost answer (when sorted by activity) is not one that is just plain wrong.

What is a Stacktrace?

A stacktrace is a very helpful debugging tool. It shows the call stack (meaning, the stack of functions that were called up to that point) at the time an uncaught exception was thrown (or the time the stacktrace was generated manually). This is very useful because it doesn't only show you where the error happened, but also how the program ended up in that place of the code. This leads over to the next question:

What is an Exception?

An Exception is what the runtime environment uses to tell you that an error occurred. Popular examples are NullPointerException, IndexOutOfBoundsException or ArithmeticException. Each of these are caused when you try to do something that is not possible. For example, a NullPointerException will be thrown when you try to dereference a Null-object:

Object a = null;
a.toString();                 //this line throws a NullPointerException

Object[] b = new Object[5];
System.out.println(b[10]);    //this line throws an IndexOutOfBoundsException,
                              //because b is only 5 elements long
int ia = 5;
int ib = 0;
ia = ia/ib;                   //this line throws an  ArithmeticException with the 
                              //message "/ by 0", because you are trying to
                              //divide by 0, which is not possible.

How should I deal with Stacktraces/Exceptions?

At first, find out what is causing the Exception. Try googleing the name of the exception to find out, what is the cause of that exception. Most of the time it will be caused by incorrect code. In the given examples above, all of the exceptions are caused by incorrect code. So for the NullPointerException example you could make sure that a is never null at that time. You could, for example, initialise a or include a check like this one:

if (a!=null) {
    a.toString();
}

This way, the offending line is not executed if a==null. Same goes for the other examples.

Sometimes you can't make sure that you don't get an exception. For example, if you are using a network connection in your program, you cannot stop the computer from loosing it's internet connection (e.g. you can't stop the user from disconnecting the computer's network connection). In this case the network library will probably throw an exception. Now you should catch the exception and handle it. This means, in the example with the network connection, you should try to reopen the connection or notify the user or something like that. Also, whenever you use catch, always catch only the exception you want to catch, do not use broad catch statements like catch (Exception e) that would catch all exceptions. This is very important, because otherwise you might accidentally catch the wrong exception and react in the wrong way.

try {
    Socket x = new Socket("1.1.1.1", 6789);
    x.getInputStream().read()
} catch (IOException e) {
    System.err.println("Connection could not be established, please try again later!")
}

Why should I not use catch (Exception e)?

Let's use a small example to show why you should not just catch all exceptions:

int mult(Integer a,Integer b) {
    try {
        int result = a/b
        return result;
    } catch (Exception e) {
        System.err.println("Error: Division by zero!");
        return 0;
    }
}

What this code is trying to do is to catch the ArithmeticException caused by a possible division by 0. But it also catches a possible NullPointerException that is thrown if a or b are null. This means, you might get a NullPointerException but you'll treat it as an ArithmeticException and probably do the wrong thing. In the best case you still miss that there was a NullPointerException. Stuff like that makes debugging much harder, so don't do that.

TLDR

  1. Figure out what is the cause of the exception and fix it, so that it doesn't throw the exception at all.
  2. If 1. is not possible, catch the specific exception and handle it.

    • Never just add a try/catch and then just ignore the exception! Don't do that!
    • Never use catch (Exception e), always catch specific Exceptions. That will save you a lot of headaches.

UTF-8 encoding in JSP page

I used encoding filter which has solved my all encoding problem...

 package com.dina.filter;

    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;

    /**
     *
     * @author DINANATH
     */
    public class EncodingFilter implements Filter {

        private String encoding = "utf-8";

        public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
            request.setCharacterEncoding(encoding);
    //                response.setContentType("text/html;charset=UTF-8");
                    response.setCharacterEncoding(encoding);
            filterChain.doFilter(request, response);

        }

        public void init(FilterConfig filterConfig) throws ServletException {
            String encodingParam = filterConfig.getInitParameter("encoding");
            if (encodingParam != null) {
                encoding = encodingParam;
            }
        }

        public void destroy() {
            // nothing todo
        }

    }

in web.xml

    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>
        com.dina.filter.EncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Counting Line Numbers in Eclipse

You could use a batch file with the following script:

@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir "%CD%\src\*.java" /b /s') DO (type "%%G") >> lines.txt
SET count=1
FOR /f "tokens=*" %%G IN ('type lines.txt') DO (set /a lines+=1)
echo Your Project has currently totaled %lines% lines of code. 
del lines.txt
PAUSE

':app:lintVitalRelease' error when generating signed apk

Try These 3 lines in your app.gradle file.

android {
lintOptions {
    checkReleaseBuilds false
    // Or, if you prefer, you can continue to check for errors in release builds,
    // but continue the build even when errors are found:
    abortOnError false
}

What are the differences between the different saving methods in Hibernate?

None of the following answers are right. All these methods just seem to be alike, but in practice do absolutely different things. It is hard to give short comments. Better to give a link to full documentation about these methods: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html

Change location of log4j.properties

This is my class : Path is fine and properties is loaded.

package com.fiserv.dl.idp.logging;

import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class LoggingCapsule {

    private static Logger logger = Logger.getLogger(LoggingCapsule.class);

    public static void info(String message) {


        try {

            String configDir = System.getProperty("config.path");
            if (configDir == null) {
                throw new MissingResourceException("System property: config.path not set", "", "");
            }
            Properties properties = new Properties();
            properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
            PropertyConfigurator.configure(properties);
        } catch (Exception e) {
            e.printStackTrace();

        }
        logger.info(message);
    }
    public static void error(String message){
        System.out.println(message);
    }

}

Convert a date format in epoch

  String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
   DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
        LocalDateTime zdt  = LocalDateTime.parse(dateTime,dtf);
        LocalDateTime now = LocalDateTime.now();
        ZoneId zone = ZoneId.of("Asia/Kolkata");
        ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
        long a= zdt.toInstant(zoneOffSet).toEpochMilli();
        Log.d("time","---"+a);

you can get zone id form this a link!

Dynamically converting java object of Object class to a given class when class name is known

I think its pretty straight forward with reflection

MyClass mobj = MyClass.class.cast(obj);

and if class name is different

Object newObj = Class.forName(classname).cast(obj);

Java equivalent to C# extension methods

Technically C# Extension have no equivalent in Java. But if you do want to implement such functions for a cleaner code and maintainability, you have to use Manifold framework.

package extensions.java.lang.String;

import manifold.ext.api.*;

@Extension
public class MyStringExtension {

  public static void print(@This String thiz) {
    System.out.println(thiz);
  }

  @Extension
  public static String lineSeparator() {
    return System.lineSeparator();
  }
}

How do I use Comparator to define a custom sort order?

I recommend you create an enum for your car colours instead of using Strings and the natural ordering of the enum will be the order in which you declare the constants.

public enum PaintColors {
    SILVER, BLUE, MAGENTA, RED
}

and

 static class ColorComparator implements Comparator<CarSort>
 {
     public int compare(CarSort c1, CarSort c2)
     {
         return c1.getColor().compareTo(c2.getColor());
     }
 }

You change the String to PaintColor and then in main your car list becomes:

carList.add(new CarSort("Ford Figo",PaintColor.SILVER));

...

Collections.sort(carList, new ColorComparator());

What is the equivalent of the C# 'var' keyword in Java?

It will be supported in JDK 10. It's even possible to see it in action in the early access build.

The JEP 286:

Enhance the Java Language to extend type inference to declarations of local variables with initializers.

So now instead of writing:

List<> list = new ArrayList<String>();
Stream<> stream = myStream();

You write:

var list = new ArrayList<String>();
var stream = myStream();

Notes:

  • var is now a reserved type name
  • Java is still commitment to static typing!
  • It can be only used in local variable declarations

If you want to give it a try without installing Java on your local system, I created a Docker image with JDK 10 installed on it:

$ docker run -it marounbassam/ubuntu-java10 bash
root@299d86f1c39a:/# jdk-10/bin/jshell
Mar 30, 2018 9:07:07 PM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
|  Welcome to JShell -- Version 10
|  For an introduction type: /help intro

jshell> var list = new ArrayList<String>();
list ==> []

How to add a Java Properties file to my Java Project in Eclipse

To create a property class please select your package where you wants to create your property file.

Right click on the package and select other. Now select File and type your file name with (.properties) suffix. For example: db.properties. Than click finish. Now you can write your code inside this property file.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

How to check if a String is numeric in Java

You can use NumberFormat#parse:

try
{
     NumberFormat.getInstance().parse(value);
}
catch(ParseException e)
{
    // Not a number.
}

How to view the list of compile errors in IntelliJ?

A more up to date answer for anyone else who comes across this:

(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)

Compile automatically:

To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option

Show all errors in one place:

The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.

Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.

While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.

What's the console.log() of java?

public class Console {

    public static void Log(Object obj){
        System.out.println(obj);
    }
}

to call and use as JavaScript just do this:

Console.Log (Object)

I think that's what you mean

How to find Max Date in List<Object>?

troubleshooting-friendly style

You should not call .get() directly. Optional<>, that Stream::max returns, was designed to benefit from .orElse... inline handling.

If you are sure your arguments have their size of 2+:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));

If you support empty lists, then return some default value, for example:

list.stream()
    .map(u -> u.date)
    .max(Date::compareTo)
    .orElse(new Date(Long.MIN_VALUE));

CREDITS to: @JimmyGeers, @assylias from the accepted answer.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Using merge is risky and tricky, so it's a dirty workaround in your case. You need to remember at least that when you pass an entity object to merge, it stops being attached to the transaction and instead a new, now-attached entity is returned. This means that if anyone has the old entity object still in their possession, changes to it are silently ignored and thrown away on commit.

You are not showing the complete code here, so I cannot double-check your transaction pattern. One way to get to a situation like this is if you don't have a transaction active when executing the merge and persist. In that case persistence provider is expected to open a new transaction for every JPA operation you perform and immediately commit and close it before the call returns. If this is the case, the merge would be run in a first transaction and then after the merge method returns, the transaction is completed and closed and the returned entity is now detached. The persist below it would then open a second transaction, and trying to refer to an entity that is detached, giving an exception. Always wrap your code inside a transaction unless you know very well what you are doing.

Using container-managed transaction it would look something like this. Do note: this assumes the method is inside a session bean and called via Local or Remote interface.

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void storeAccount(Account account) {
    ...

    if (account.getId()!=null) {
        account = entityManager.merge(account);
    }

    Transaction transaction = new Transaction(account,"other stuff");

    entityManager.persist(account);
}

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

DBMS_OUTPUT is not the best tool to debug, since most environments don't use it natively. If you want to capture the output of DBMS_OUTPUT however, you would simply use the DBMS_OUTPUT.get_line procedure.

Here is a small example:

SQL> create directory tmp as '/tmp/';

Directory created

SQL> CREATE OR REPLACE PROCEDURE write_log AS
  2     l_line VARCHAR2(255);
  3     l_done NUMBER;
  4     l_file utl_file.file_type;
  5  BEGIN
  6     l_file := utl_file.fopen('TMP', 'foo.log', 'A');
  7     LOOP
  8        EXIT WHEN l_done = 1;
  9        dbms_output.get_line(l_line, l_done);
 10        utl_file.put_line(l_file, l_line);
 11     END LOOP;
 12     utl_file.fflush(l_file);
 13     utl_file.fclose(l_file);
 14  END write_log;
 15  /

Procedure created

SQL> BEGIN
  2     dbms_output.enable(100000);
  3     -- write something to DBMS_OUTPUT
  4     dbms_output.put_line('this is a test');
  5     -- write the content of the buffer to a file
  6     write_log;
  7  END;
  8  /

PL/SQL procedure successfully completed

SQL> host cat /tmp/foo.log

this is a test

Routing with multiple Get methods in ASP.NET Web API

  // this piece of code in the WebApiConfig.cs file or your custom bootstrap application class
  // define two types of routes 1. DefaultActionApi  and 2. DefaultApi as below

   config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
   config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional });

  // decorate the controller action method with [ActionName("Default")] which need to invoked with below url
  // http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller
  // http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller
  // http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller


 public class DemoController : ApiController
 {
    // Mark the method with ActionName  attribute (defined in MapRoutes) 
    [ActionName("Default")]
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Get Method");
    }

    public HttpResponseMessage GetAll()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method");
    }

    public HttpResponseMessage GetById()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage DemoGet()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage CustomGetDetails()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method");
    }
}

After installation of Gulp: “no command 'gulp' found”

That's perfectly normal. If you want gulp-cli available on the command line, you need to install it globally.

npm install --global gulp-cli

See the install instruction.

Also, node_modules/.bin/ isn't in your $PATH. But it is automatically added by npm when running npm scripts (see this blog post for reference).

So you could add scripts to your package.json file:

{
    "name": "your-app",
    "version": "0.0.1",
    "scripts": {
        "gulp": "gulp",
        "minify": "gulp minify"
    }
}

You could then run npm run gulp or npm run minify to launch gulp tasks.

How to delete Certain Characters in a excel 2010 cell

If [John Smith] is in cell A1, then use this formula to do what you want:

=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")

The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.

Iterating through a JSON object

Your loading of the JSON data is a little fragile. Instead of:

json_raw= raw.readlines()
json_object = json.loads(json_raw[0])

you should really just do:

json_object = json.load(raw)

You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0], you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song].

None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.

Foreign key referencing a 2 columns primary key in SQL Server

The Content table likely to have multiple duplicate Application values that can't be mapped to Libraries. Is it possible to drop the Application column from the Libraries Primary Key Index and add it as a Unique Key Index instead?

Determine .NET Framework version for dll

In PowerShell you can use the following to get the target runtime:

$path = "C:\Some.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).ImageRuntimeVersion

I adapted this to PowerShell from Ben Griswold's answer.

If you want to know the target framework version specified in Visual Studio, use:

$path = "C:\Some.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).CustomAttributes |
Where-Object {$_.AttributeType.Name -eq "TargetFrameworkAttribute" } | 
Select-Object -ExpandProperty ConstructorArguments | 
Select-Object -ExpandProperty value

You should get something like

.NETFramework,Version=v4.5.2

How to send 100,000 emails weekly?

Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).

Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:

  • e-mail content that is not spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)
  • in addition, your content should be easy to distinguish from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)
  • a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)
  • some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's mail() is horrible enough by itself)
  • your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)

Surprisingly, that was the easy part. The hard part is actually sending it:

  • some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])
  • you need to have correct PTR, SPF, DKIM records
  • handling remote server timeouts, misconfigured DNS records and other network pleasantries
  • handling invalid e-mails (and no, regex is the wrong tool for that)
  • handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)
  • handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")
  • handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it will happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On average, it takes weeks to get yourself removed from a blacklist.)

And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).

I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:

  • the remote SMTP servers don't want to talk to your SMTP server
  • your mails are getting marked as spam (<blink> is not your friend here, nor is <font color=...>)
  • your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)
  • your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)
  • your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail looks more suspicious)
  • your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))
  • users with various versions of Microsoft Outlook and its special handling of Internet mail
  • wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you really don't want to be the one to set this off, as you'd anger half the internet at yourself)

and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.

If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.

Copy a variable's value into another

It's important to understand what the = operator in JavaScript does and does not do.

The = operator does not make a copy of the data.

The = operator creates a new reference to the same data.

After you run your original code:

var a = $('#some_hidden_var').val(),
    b = a;

a and b are now two different names for the same object.

Any change you make to the contents of this object will be seen identically whether you reference it through the a variable or the b variable. They are the same object.

So, when you later try to "revert" b to the original a object with this code:

b = a;

The code actually does nothing at all, because a and b are the exact same thing. The code is the same as if you'd written:

b = b;

which obviously won't do anything.

Why does your new code work?

b = { key1: a.key1, key2: a.key2 };

Here you are creating a brand new object with the {...} object literal. This new object is not the same as your old object. So you are now setting b as a reference to this new object, which does what you want.

To handle any arbitrary object, you can use an object cloning function such as the one listed in Armand's answer, or since you're using jQuery just use the $.extend() function. This function will make either a shallow copy or a deep copy of an object. (Don't confuse this with the $().clone() method which is for copying DOM elements, not objects.)

For a shallow copy:

b = $.extend( {}, a );

Or a deep copy:

b = $.extend( true, {}, a );

What's the difference between a shallow copy and a deep copy? A shallow copy is similar to your code that creates a new object with an object literal. It creates a new top-level object containing references to the same properties as the original object.

If your object contains only primitive types like numbers and strings, a deep copy and shallow copy will do exactly the same thing. But if your object contains other objects or arrays nested inside it, then a shallow copy doesn't copy those nested objects, it merely creates references to them. So you could have the same problem with nested objects that you had with your top-level object. For example, given this object:

var obj = {
    w: 123,
    x: {
        y: 456,
        z: 789
    }
};

If you do a shallow copy of that object, then the x property of your new object is the same x object from the original:

var copy = $.extend( {}, obj );
copy.w = 321;
copy.x.y = 654;

Now your objects will look like this:

// copy looks as expected
var copy = {
    w: 321,
    x: {
        y: 654,
        z: 789
    }
};

// But changing copy.x.y also changed obj.x.y!
var obj = {
    w: 123,  // changing copy.w didn't affect obj.w
    x: {
        y: 654,  // changing copy.x.y also changed obj.x.y
        z: 789
    }
};

You can avoid this with a deep copy. The deep copy recurses into every nested object and array (and Date in Armand's code) to make copies of those objects in the same way it made a copy of the top-level object. So changing copy.x.y wouldn't affect obj.x.y.

Short answer: If in doubt, you probably want a deep copy.

What does 'super' do in Python?

some great answers here, but they do not tackle how to use super() in the case where different classes in the hierarchy have different signatures ... especially in the case of __init__

to answer that part and to be able to effectively use super() i'd suggest reading my answer super() and changing the signature of cooperative methods.

here's just the solution to this scenario:

  1. the top-level classes in your hierarchy must inherit from a custom class like SuperObject:
  2. if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept **kwargs.
class SuperObject:        
    def __init__(self, **kwargs):
        print('SuperObject')
        mro = type(self).__mro__
        assert mro[-1] is object
        if mro[-2] is not SuperObject:
            raise TypeError(
                'all top-level classes in this hierarchy must inherit from SuperObject',
                'the last class in the MRO should be SuperObject',
                f'mro={[cls.__name__ for cls in mro]}'
            )

        # super().__init__ is guaranteed to be object.__init__        
        init = super().__init__
        init()

example usage:

class A(SuperObject):
    def __init__(self, **kwargs):
        print("A")
        super(A, self).__init__(**kwargs)

class B(SuperObject):
    def __init__(self, **kwargs):
        print("B")
        super(B, self).__init__(**kwargs)

class C(A):
    def __init__(self, age, **kwargs):
        print("C",f"age={age}")
        super(C, self).__init__(age=age, **kwargs)

class D(B):
    def __init__(self, name, **kwargs):
        print("D", f"name={name}")
        super(D, self).__init__(name=name, **kwargs)

class E(C,D):
    def __init__(self, name, age, *args, **kwargs):
        print( "E", f"name={name}", f"age={age}")
        super(E, self).__init__(name=name, age=age, *args, **kwargs)

E(name='python', age=28)

output:

E name=python age=28
C age=28
A
D name=python
B
SuperObject

How can I conditionally import an ES6 module?

Look at this example for clear understanding of how dynamic import works.

Dynamic Module Imports Example

To have Basic Understanding of importing and exporting Modules.

JavaScript modules Github

Javascript Modules MDN

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

You can also use ObjectId.isValid like the following :

if (!ObjectId.isValid(userId)) return Error({ status: 422 })

SELECT from nothing?

I'm using firebird First of all, create a one column table named "NoTable" like this

CREATE TABLE NOTABLE 
(
  NOCOLUMN              INTEGER
);
INSERT INTO NOTABLE VALUES (0); -- You can put any value

now you can write this

select 'hello world' as name

from notable

you can add any column you want to be shown

Changing an element's ID with jQuery

$("#LeNomDeMaBaliseID").prop('id', 'LeNouveauNomDeMaBaliseID');

What is the difference between IEnumerator and IEnumerable?

IEnumerable and IEnumerator are both interfaces. IEnumerable has just one method called GetEnumerator. This method returns (as all methods return something including void) another type which is an interface and that interface is IEnumerator. When you implement enumerator logic in any of your collection class, you implement IEnumerable (either generic or non generic). IEnumerable has just one method whereas IEnumerator has 2 methods (MoveNext and Reset) and a property Current. For easy understanding consider IEnumerable as a box that contains IEnumerator inside it (though not through inheritance or containment). See the code for better understanding:

class Test : IEnumerable, IEnumerator
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    public object Current
    {
        get { throw new NotImplementedException(); }
    }

    public bool MoveNext()
    {
        throw new NotImplementedException();
    }

    public void Reset()
    {
        throw new NotImplementedException();
    }
}

Make an image width 100% of parent div, but not bigger than its own width

Just specify max-width: 100% alone, that should do it.

How to set timeout on python's socket recv method?

The timeout that you are looking for is the connection socket's timeout not the primary socket's, if you implement the server side. In other words, there is another timeout for the connection socket object, which is the output of socket.accept() method. Therefore:

sock.listen(1)
connection, client_address = sock.accept()
connection.settimeout(5)    # This is the one that affects recv() method.
connection.gettimeout()     # This should result 5
sock.gettimeout()           # This outputs None when not set previously, if I remember correctly.

If you implement the client side, it would be simple.

sock.connect(server_address)
sock.settimeout(3)

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Set Focus After Last Character in Text Box

I tried lots of different solutions, the only one that worked for me was based on the solution by Chris G on this page (but with a slight modification).

I have turned it into a jQuery plugin for future use for anyone that needs it

(function($){
    $.fn.setCursorToTextEnd = function() {
        var $initialVal = this.val();
        this.val($initialVal);
    };
})(jQuery);

example of usage:

$('#myTextbox').setCursorToTextEnd();

How to pick a new color for each plotted line within a figure in matplotlib?

I don't know if you can automatically change the color, but you could exploit your loop to generate different colors:

for i in range(20):
   ax1.plot(x, y, color = (0, i / 20.0, 0, 1)

In this case, colors will vary from black to 100% green, but you can tune it if you want.

See the matplotlib plot() docs and look for the color keyword argument.

If you want to feed a list of colors, just make sure that you have a list big enough and then use the index of the loop to select the color

colors = ['r', 'b', ...., 'w']

for i in range(20):
   ax1.plot(x, y, color = colors[i])

How to generate .angular-cli.json file in Angular Cli?

In Angular 6, .angular-cli.json has been replaced with angular.json

For Angular < 6:

Create a new file with name '.angular-cli.json' and add this file in your main directory.

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "my-app"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

How to customize <input type="file">?

The trick is hide the input and customize the label.

enter image description here

HTML:

<div class="inputfile-box">
  <input type="file" id="file" class="inputfile" onchange='uploadFile(this)'>
  <label for="file">
    <span id="file-name" class="file-box"></span>
    <span class="file-button">
      <i class="fa fa-upload" aria-hidden="true"></i>
      Select File
    </span>
  </label>
</div>

CSS:

.inputfile-box {
  position: relative;
}

.inputfile {
  display: none;
}

.container {
  display: inline-block;
  width: 100%;
}

.file-box {
  display: inline-block;
  width: 100%;
  border: 1px solid;
  padding: 5px 0px 5px 5px;
  box-sizing: border-box;
  height: calc(2rem - 2px);
}

.file-button {
  background: red;
  padding: 5px;
  position: absolute;
  border: 1px solid;
  top: 0px;
  right: 0px;
}

JS:

function uploadFile(target) {
    document.getElementById("file-name").innerHTML = target.files[0].name;
}

You can check this example: https://jsfiddle.net/rjurado/hnf0zhy1/4/

Validate phone number using javascript

In JavaScript, the below regular expression can be used for a phone number :

^((\+1)?[\s-]?)?\(?[1-9]\d\d\)?[\s-]?[1-9]\d\d[\s-]?\d\d\d\d

e.g; 9999875099 , 8750999912 etc.

Reference : https://techsolutions.filebizz.com/2020/08/regular-expression-for-phone-number-in.html

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I managed to get FTP access to the customer's server and so was able to track down the problem.

After the form is POSTed, I authenticate the user and then redirect to the main part of the app.

Util::redirect('/apps/content');

The error was occurring not on the posting of the form, but on the redirect immediately following it. For some reason, IIS was continuing to presume the POST method for the redirect, and then objecting to the POST to /apps/content as it's a directory.

The error message never indicated that it was the following page that was generating the error - thanks Microsoft!

The solution was to add a trailing slash:

Util::redirect('/apps/content/');

IIS could then resolve the redirect to a default document as is no longer attempting to POST to a directory.

Infinite Recursion with Jackson JSON and Hibernate JPA issue

I have the same problem after doing more analysis i came to know that, we can get mapped entity also by just keeping @JsonBackReference at OneToMany annotation

@Entity
@Table(name = "ta_trainee", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Trainee extends BusinessObject {

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "id", nullable = false)
private Integer id;

@Column(name = "name", nullable = true)
private String name;

@Column(name = "surname", nullable = true)
private String surname;

@OneToMany(mappedBy = "trainee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Column(nullable = true)
@JsonBackReference
private Set<BodyStat> bodyStats;

Guzzle 6: no more json() method for responses

$response is instance of PSR-7 ResponseInterface. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces

getBody() returns StreamInterface:

/**
 * Gets the body of the message.
 *
 * @return StreamInterface Returns the body as a stream.
 */
public function getBody();

StreamInterface implements __toString() which does

Reads all data from the stream into a string, from the beginning to end.

Therefore, to read body as string, you have to cast it to string:

$stringBody = (string) $response->getBody()


Gotchas

  1. json_decode($response->getBody() is not the best solution as it magically casts stream into string for you. json_decode() requires string as 1st argument.
  2. Don't use $response->getBody()->getContents() unless you know what you're doing. If you read documentation for getContents(), it says: Returns the remaining contents in a string. Therefore, calling getContents() reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.

Generating HTML email body in C#

I use dotLiquid for exactly this task.

It takes a template, and fills special identifiers with the content of an anonymous object.

//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source

//Create DTO for the renderer
var bodyDto = new {
    Heading = "Heading Here",
    UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));

It also works with collections, see some online examples.

Getting the location from an IP address

In case anyone stumbles upon this thread, here's another solution. At timezoneapi.io you can request an IP address and get several objects in return (I've created the service). It was created because I needed to know which timezone my users were in, where in the world and what time it currently is.

In PHP - returns location, timezone and date/time:

// Get IP address
$ip_address = getenv('HTTP_CLIENT_IP') ?: getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?: getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?: getenv('REMOTE_ADDR');

// Get JSON object
$jsondata = file_get_contents("http://timezoneapi.io/api/ip/?" . $ip_address);

// Decode
$data = json_decode($jsondata, true);

// Request OK?
if($data['meta']['code'] == '200'){

    // Example: Get the city parameter
    echo "City: " . $data['data']['city'] . "<br>";

    // Example: Get the users time
    echo "Time: " . $data['data']['datetime']['date_time_txt'] . "<br>";

}

Using jQuery:

// Get JSON object
$.getJSON('https://timezoneapi.io/api/ip', function(data){

    // Request OK?
    if(data.meta.code == '200'){

        // Log
        console.log(data);

        // Example: Get the city parameter
        var city = data.data.city;
        alert(city);

        // Example: Get the users time
        var time = data.data.datetime.date_time_txt;
        alert(time);

    }

});

how to remove untracked files in Git?

While git clean works well, I still find it useful to use my own script to clean the git repo, it has some advantages.

This shows a list of files to be cleaned, then interactively prompts to clean or not. This is nearly always what I want since interactively prompting per file gets tedious.

It also allows manual filtering of the list which comes in handy when there are file types you don't want to clean (and have reason not to commit).


git_clean.sh


#!/bin/bash
readarray -t -d '' FILES < <(
    git ls-files -z --other --directory |
        grep --null-data --null -v '.bin$\|Cargo.lock$'
)
if [ "$FILES" = "" ]; then
    echo  "Nothing to clean!"
    exit 0
fi

echo "Dirty files:"
printf '  %s\n' "${FILES[@]}"

DO_REMOVE=0
while true; do
    echo ""
    read -p "Remove ${#FILES[@]} files? [y/n]: " choice
    case "$choice" in
        y|Y )
            DO_REMOVE=1
            break ;;
        n|N )
            echo "Exiting!"
            break ;;
        * ) echo "Invalid input, expected [Y/y/N/n]"
            continue ;;
    esac
done

if [ "$DO_REMOVE" -eq 1 ];then
    echo "Removing!"
    for f in "${FILES[@]}"; do
       rm -rfv "$f"
    done
fi

Change One Cell's Data in mysql

UPDATE will change only the columns you specifically list.

UPDATE some_table
SET field1='Value 1'
WHERE primary_key = 7;

The WHERE clause limits which rows are updated. Generally you'd use this to identify your table's primary key (or ID) value, so that you're updating only one row.

The SET clause tells MySQL which columns to update. You can list as many or as few columns as you'd like. Any that you do not list will not get updated.

How to add class active on specific li on user click with jQuery

 $(document).ready(function () {
    $('.dates li a').click(function (e) {

        $('.dates li a').removeClass('active');

        var $parent = $(this);
        if (!$parent.hasClass('active')) {
            $parent.addClass('active');
        }
        e.preventDefault();
    });
});

Removing an element from an Array (Java)

You could use commons lang's ArrayUtils.

array = ArrayUtils.removeElement(array, element)

commons.apache.org library:Javadocs

Merge/flatten an array of arrays

I originally thought to use the .reduce method and recursively call a function to flatten inner arrays, however this can lead to stack overflows when you are working with a deeply nested array of deeply nested arrays. Using concat is also not the best way to go, because each iteration will create a new shallow copy of the array. What we can do instead is this:

const flatten = arr => {
    for(let i = 0; i < arr.length;) {
        const val = arr[i];
        if(Array.isArray(val)) {
            arr.splice(i, 1, ...val);
        } else {
            i ++;
        }
    }
    return arr;
}

We are not creating new arrays via concat and we are not recursively calling any functions.

http://jsbin.com/firiru/4/edit?js,console

How can I trigger a Bootstrap modal programmatically?

If you are looking for a programmatical modal creation, you might love this:

http://nakupanda.github.io/bootstrap3-dialog/

Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I solved this converting the JSP from XHTML to HTML, doing this in the begining:

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
...

Using Java to find substring of a bigger string using Regular Expression

I'd define that I want a maximum number of non-] characters between [ and ]. These need to be escaped with backslashes (and in Java, these need to be escaped again), and the definition of non-] is a character class, thus inside [ and ] (i.e. [^\\]]). The result:

FOO\\[([^\\]]+)\\]

Passing variables to the next middleware using next() in Express.js

The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling

app.get('some/url/endpoint', middleware1, middleware2);

Since you can handle your request in the first middleware

(req, res, next) => {
    var yourvalue = anyvalue
}

In middleware 1 you handle your logic and store your value like below:

req.anyvariable = yourvalue

In middleware 2 you can catch this value from middleware 1 doing the following:

(req, res, next) => {
    var storedvalue = req.yourvalue
}

Python not working in the command line of git bash

For python version 3.7.3 in vscode with gitbash as the default terminal I was dealing with this for a while and then followed @Vitaliy Terziev advice of adding the alias to .bashrc but with the following specification:

alias python=’“/c/Users/my user name/AppData/Local/Programs/Python/Python37/python.exe”’

Notice the combination of single and double quotes because of “my user name” spaces.

For me, "winpty" couldn't resolve python path in vscode.

To find first N prime numbers in python

Anwer here is simple i.e run the loop 'n' times.

n=int(input())
count=0
i=2
while count<n:
    flag=0
    j=2
    while j<=int(i**0.5):
        if i%j==0:
            flag+=1
        j+=1
    if flag==0:
        print(i,end=" ")
        count+=1
    i+=1

How to click or tap on a TextView text

in textView

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:onClick="onClick"
    android:clickable="true"

You must also implement View.OnClickListener and in On Click method can use intent

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
           intent.setData(Uri.parse("https://youraddress.com"));    
            startActivity(intent);

I tested this solution works fine.

How do you add multi-line text to a UIButton?

It works perfectly.

Add to use this with config file like Plist, you need to use CDATA to write the multilined title, like this:

<string><![CDATA[Line1
Line2]]></string>

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

How to use a keypress event in AngularJS?

I think using document.bind is a bit more elegant

constructor($scope, $document) {
  var that = this;
  $document.bind("keydown", function(event) {
    $scope.$apply(function(){
      that.handleKeyDown(event);
    });
  });
}

To get document to the controller constructor:

controller: ['$scope', '$document', MyCtrl]

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

Android - How to regenerate R class?

I had that problem and I just right-clicked on packet of my project and Build Project. Instantly the class R appeared in packet gen.

How to implement a confirmation (yes/no) DialogPreference?

Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below

intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
    Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);

    intentClearCookies.setIntent(clearcookies);
    intentClearCookies.setTitle(R.string.ClearCookies);
    intentClearCookies.setEnabled(true);
    launchPrefCat.addPreference(intentClearCookies);

And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.

public class ClearCookies extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    showDialog();
}

/**
 * @throws NotFoundException
 */
private void showDialog() throws NotFoundException {
    new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.ClearCookies))
            .setMessage(
                    getResources().getString(R.string.ClearCookieQuestion))
            .setIcon(
                    getResources().getDrawable(
                            android.R.drawable.ic_dialog_alert))
            .setPositiveButton(
                    getResources().getString(R.string.PostiveYesButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here

                        }
                    })
            .setNegativeButton(
                    getResources().getString(R.string.NegativeNoButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here
                        }
                    }).show();
}}

As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Add elements in first arraylist

ArrayList<String> firstArrayList = new ArrayList<String>();

firstArrayList.add("A");
firstArrayList.add("B");
firstArrayList.add("C");
firstArrayList.add("D");
firstArrayList.add("E");

Add elements in second arraylist

ArrayList<String> secondArrayList = new ArrayList<String>();

secondArrayList.add("B");
secondArrayList.add("D");
secondArrayList.add("F");
secondArrayList.add("G");

Add first arraylist's elements in second arraylist

secondArrayList.addAll(firstArrayList);

Assign new combine arraylist and add all elements from both arraylists

ArrayList<String> comboArrayList = new ArrayList<String>(firstArrayList);
comboArrayList.addAll(secondArrayList);

Assign new Set for remove duplicate entries from arraylist

Set<String> setList = new LinkedHashSet<String>(comboArrayList);
comboArrayList.clear();
comboArrayList.addAll(setList);

Sorting arraylist

Collections.sort(comboArrayList);

Output

 A
 B
 C
 D
 E
 F
 G

How to set the thumbnail image on HTML5 video?

1) add the below jquery:

$thumbnail.on('click', function(e){
 e.preventDefault();
 src = src+'&autoplay=1'; // src: the original URL for embedding 
 $videoContainer.empty().append( $iframe.clone().attr({'src': src}) ); // $iframe: the original iframe for embedding
 }
);

note: in the first src (shown) add the original youtube link.

2) edit the iframe tag as:

<iframe width="1280" height="720" src="https://www.youtube.com/embed/nfQHF87vY0s?autoplay=1" frameborder="0" allowfullscreen></iframe>

note: copy paste the youtube video id after the embed/ in the iframe src.

Heatmap in matplotlib with pcolor?

Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.

With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

And here's the output:

Matplotlib HeatMap

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

in SQL*Plus you could also use a REFCURSOR variable:

SQL> VARIABLE x REFCURSOR
SQL> DECLARE
  2   V_Sqlstatement Varchar2(2000);
  3  BEGIN
  4   V_Sqlstatement := 'SELECT * FROM DUAL';
  5   OPEN :x for v_Sqlstatement;
  6  End;
  7  /

ProcÚdure PL/SQL terminÚe avec succÞs.

SQL> print x;

D
-
X

How do I pass a datetime value as a URI parameter in asp.net mvc?

Use the ticks value. It's quite simple to rebuild into a DateTime structure

 Int64 nTicks = DateTime.Now.Ticks;
 ....
 DateTime dtTime = new DateTime(nTicks);

How to insert text with single quotation sql server 2005

You asked how to escape an Apostrophe character (') in SQL Server. All the answers above do an excellent job of explaining that.

However, depending on the situation, the Right single quotation mark character (’) might be appropriate.

(No escape characters needed)

-- Direct insert
INSERT INTO Table1 (Column1) VALUES ('John’s')

• Apostrophe (U+0027)

Ascii Apostrophe on Wikipedia

• Right single quotation mark (U+2019)

Unicode Right single quotation on Wikipedia

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

What is the best way to convert an array to a hash in Ruby

NOTE: For a concise and efficient solution, please see Marc-André Lafortune's answer below.

This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.


Warning! Solutions using flatten will not preserve Array keys or values!

Building on @John Topley's popular answer, let's try:

a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]

This throws an error:

ArgumentError: odd number of arguments for Hash
        from (irb):10:in `[]'
        from (irb):10

The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.

If you want to use Array keys or values, you can use map:

h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"

This preserves the Array key:

h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}

Auto select file in Solution Explorer from its open tab

The best option now is to install the Microsoft Visual Studio add on called Productivity Power Tools.

With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits) - which then you can use to filter the files to only show "Open". You can even filter files to show "Edited" and "Unsaved".

html div onclick event

The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".

In fact, there are multiple solutions:

  • Checking in the DIV click event handler whether the actual target element was the anchor
    → jsFiddle

    $('.expandable-panel-heading').click(function (evt) {
        if (evt.target.tagName != "A") {
            alert('123');
        }
    
        // Also possible if conditions:
        // - evt.target.id != "ancherComplaint"
        // - !$(evt.target).is("#ancherComplaint")
    });
    
    $("#ancherComplaint").click(function () {
        alert($(this).attr("id"));
    });
    
  • Stopping the event propagation from the anchor click listener
    → jsFiddle

    $("#ancherComplaint").click(function (evt) {
        evt.stopPropagation();
        alert($(this).attr("id"));
    });
    


As you may have noticed, I have removed the following selector part from my examples:

:not(#ancherComplaint)

This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

iFrame Height Auto (CSS)

I had this same issue but found the following that works great:

The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.

Here is what a typical YouTube embed code looks like, with fixed width and height:

 <iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen></iframe>

It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):

 <div class="container">
 <iframe src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen class="video"></iframe>
 </div>

And use the following CSS:

 .container {
    position: relative;
     width: 100%;
     height: 0;
     padding-bottom: 56.25%;
 }
 .video {
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
 }

Here is the page I found the solution on:

https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed

Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%; to get the height right.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

How to pass multiple arguments in processStartInfo?

It is purely a string:

startInfo.Arguments = "-sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

Of course, when arguments contain whitespaces you'll have to escape them using \" \", like:

"... -ss \"My MyAdHocTestCert.cer\""

See MSDN for this.

Node.js heap out of memory

I just want to add that in some systems, even increasing the node memory limit with --max-old-space-size, it's not enough and there is an OS error like this:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

In this case, probably is because you reached the max mmap per process.

You can check the max_map_count by running

sysctl vm.max_map_count

and increas it by running

sysctl -w vm.max_map_count=655300

and fix it to not be reset after a reboot by adding this line

vm.max_map_count=655300

in /etc/sysctl.conf file.

Check here for more info.

A good method to analyse the error is by run the process with strace

strace node --max-old-space-size=128000 my_memory_consuming_process.js

Display tooltip on Label's hover?

Just set a title on the label:

<label for="male" title="Hello This Will Have Some Value">Hello...</label>

Using jQuery:

<label for="male" data-title="Language" />
<input type="hidden" name="Language" value="Hello This Will Have Some Value">

$("label").prop("title", function() {
    return $("input[name='" + $(this).data("title") + "']").text();
});

If you can use CSS3, you can use the text-overflow: ellipsis; to handle the ellipsis for you so all you need to do is copy the text from the label into the title attribute using jQuery:

HTML:

<label for="male">Hello This Will Have Some Value</label>

CSS:

label {
    display: inline-block;
    width: 50px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

jQuery:

$("label").prop("title", function() {
   return $(this).text(); 
});

Example: http://jsfiddle.net/Xm8Xe/

Finally, if you need robust and cross-browser support, you could use the DotDotDot jQuery plugin.

Is there an XSL "contains" directive?

Use the standard XPath function contains().

Function: boolean contains(string, string)

The contains function returns true if the first argument string contains the second argument string, and otherwise returns false

git diff between cloned and original remote repository

This example might help someone:

Note "origin" is my alias for remote "What is on Github"
Note "mybranch" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch to show where the branch name parameter is used.


What exactly are my remote repos on github?

$ git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)

Add the "other github repository of the same code" - we call this a fork:

$ git remote add someOtherRepo https://github.com/otherUser/Playground.git

$git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)

make sure our local repo is up to date:

$ git fetch

Change some stuff locally. let's say file ./foo/bar.py

$ git status
# On branch mybranch
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   foo/bar.py

Review my uncommitted changes

$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

Commit locally.

$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)

Now, I'm different than my remote (on github)

$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)

Diff this with remote - your fork: (this is frequently done with git diff master origin)

$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

(git push to apply these to remote)

How does my remote branch differ from the remote master branch?

$ git diff origin/mybranch origin/master

How does my local stuff differ from the remote master branch?

$ git diff origin/master

How does my stuff differ from someone else's fork, master branch of the same repo?

$git diff mybranch someOtherRepo/master

CSS pseudo elements in React

Not a direct answer to the question, but this may help those who are having trouble creating style information using Typescript.

I was getting an error telling me that the following was incorrect:

let iconStyle = {
    position: 'relative',
    maxHeight: '90px',
    top: '25%',
}

The error told me that "types of property 'position' are incompatible". I have no idea why.

I fixed this by adding a strict Typescript declaration, like so:

let iconStyle: CSSProperties = {
    position: 'relative',
    maxHeight: '90px',
    top: '25%',
}

This works.

Getting the first index of an object

Based on CMS answer. I don't get the value directly, instead I take the key at its index and use this to get the value:

Object.keyAt = function(obj, index) {
    var i = 0;
    for (var key in obj) {
        if ((index || 0) === i++) return key;
    }
};


var obj = {
    foo: '1st',
    bar: '2nd',
    baz: '3rd'
};

var key = Object.keyAt(obj, 1);
var val = obj[key];

console.log(key); // => 'bar'
console.log(val); // => '2nd'

In STL maps, is it better to use map::insert than []?

Now in c++11 I think that the best way to insert a pair in a STL map is:

typedef std::map<int, std::string> MyMap;
MyMap map;

auto& result = map.emplace(3,"Hello");

The result will be a pair with:

  • First element (result.first), points to the pair inserted or point to the pair with this key if the key already exist.

  • Second element (result.second), true if the insertion was correct or false it something went wrong.

PS: If you don´t case about the order you can use std::unordered_map ;)

Thanks!

Merge two array of objects based on a key

Here's an O(n) solution using reduce and Object.assign

const joinById = ( ...lists ) =>
    Object.values(
        lists.reduce(
            ( idx, list ) => {
                list.forEach( ( recod ) => {
                    if( idx[ recod.id ] )
                        idx[ recod.id ] = Object.assign( idx[ recod.id ], recod )
                    else
                        idx[ recod.id ] = recod
                } )
                return idx
            },
            {}
        )
    )

Each list gets reduced to a single object where the keys are ids and the values are the objects. If there's a value at the given key already, it gets object.assign called on it and the current record.

Here's the generic O(n*m) solution, where n is the number of records and m is the number of keys. This will only work for valid object keys. You can convert any value to base64 and use that if you need to.

const join = ( keys, ...lists ) =>
    lists.reduce(
        ( res, list ) => {
            list.forEach( ( record ) => {
                let hasNode = keys.reduce(
                    ( idx, key ) => idx && idx[ record[ key ] ],
                    res[ 0 ].tree
                )
                if( hasNode ) {
                    const i = hasNode.i
                    Object.assign( res[ i ].value, record )
                    res[ i ].found++
                } else {
                    let node = keys.reduce( ( idx, key ) => {
                        if( idx[ record[ key ] ] )
                            return idx[ record[ key ] ]
                        else
                            idx[ record[ key ] ] = {}
                        return idx[ record[ key ] ]
                    }, res[ 0 ].tree )
                    node.i = res[ 0 ].i++
                    res[ node.i ] = {
                        found: 1,
                        value: record
                    }
                }
            } )
            return res
        },
        [ { i: 1, tree: {} } ]
         )
         .slice( 1 )
         .filter( node => node.found === lists.length )
         .map( n => n.value )

This is essentially the same as the joinById method, except that it keeps an index object to identify records to join. The records are stored in an array and the index stores the position of the record for the given key set and the number of lists it's been found in.

Each time the same key set is encountered, the node is found in the tree, the element at it's index is updated, and the number of times it's been found is incremented.

finally, the idx object is removed from the array with the slice, any elements that weren't found in each set are removed. This makes it an inner join, you could remove this filter and have a full outer join.

finally each element is mapped to it's value, and you have the merged array.

Regular Expression to get all characters before "-"

So I see many possibilities to achieve this.

string text = "Foobar-test";
  1. Regex Match everything till the first "-"

    Match result = Regex.Match(text, @"^.*?(?=-)");
    
    • ^ match from the start of the string
    • .*? match any character (.), zero or more times (*) but as less as possible (?)
    • (?=-) till the next character is a "-" (this is a positive look ahead)
  2. Regex Match anything that is not a "-" from the start of the string

    Match result2 = Regex.Match(text, @"^[^-]*");
    
    • [^-]* matches any character that is not a "-" zero or more times
  3. Regex Match anything that is not a "-" from the start of the string till a "-"

    Match result21 = Regex.Match(text, @"^([^-]*)-");
    

    Will only match if there is a dash in the string, but the result is then found in capture group 1.

  4. Split on "-"

    string[] result3 = text.Split('-');
    

    Result is an Array the part before the first "-" is the first item in the Array

  5. Substring till the first "-"

    string result4 = text.Substring(0, text.IndexOf("-"));
    

    Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-"))

You get then all the results (all the same) with this

Console.WriteLine(result);
Console.WriteLine(result2);
Console.WriteLine(result21.Groups[1]);
Console.WriteLine(result3[0]);
Console.WriteLine(result4);

I would prefer the first method.

You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-") will be -1. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.

Excel: VLOOKUP that returns true or false?

You could wrap your VLOOKUP() in an IFERROR()

Edit: before Excel 2007, use =IF(ISERROR()...)

Replace text inside td using jQuery having td containing other elements

A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:

var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));

Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:

var $a = $('#demoTable td');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

How to hide console window in python?

This will hide your console. Implement these lines in your code first to start hiding your console at first.

import win32gui, win32con

the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)

Update May 2020 :

If you've got trouble on pip install win32con on Command Prompt, you can simply pip install pywin32.Then on your python script, execute import win32.lib.win32con as win32con instead of import win32con.

To show back your program again win32con.SW_SHOW works fine:

win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)

Serializing list to JSON

If using Python 2.5, you may need to import simplejson:

try:
    import json
except ImportError:
    import simplejson as json

ActionController::InvalidAuthenticityToken

Add

//= require rails-ujs 

in

\app\assets\javascripts\application.js

What is the difference between String and StringBuffer in Java?

I found interest answer for compare performance String vs StringBuffer by Reggie Hutcherso Source: http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:

 String str = new String ("Stanford  ");
 str += "Lost!!";

If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:

 StringBuffer str = new StringBuffer ("Stanford ");
 str.append("Lost!!");

Developers usually assume that the first example above is more efficient because they think that the second example, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.

The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:

0 new #7 <Class java.lang.String>
3 dup 
4 ldc #2 <String "Stanford ">
6 invokespecial #12 <Method java.lang.String(java.lang.String)>
9 astore_1
10 new #8 <Class java.lang.StringBuffer>
13 dup
14 aload_1
15 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)>
18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
21 ldc #1 <String "Lost!!">
23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
26 invokevirtual #22 <Method java.lang.String toString()>
29 astore_1

The bytecode at locations 0 through 9 is executed for the first line of code, namely:

 String str = new String("Stanford ");

Then, the bytecode at location 10 through 29 is executed for the concatenation:

 str += "Lost!!";

Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.

After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.

In summary, the two lines of code above result in the creation of three objects:

  1. A String object at location 0
  2. A StringBuffer object at location 10
  3. A String object at location 26

Now, let's look at the bytecode generated for the example using StringBuffer:

0 new #8 <Class java.lang.StringBuffer>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
9 astore_1
10 aload_1 
11 ldc #1 <String "Lost!!">
13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
16 pop

The bytecode at locations 0 to 9 is executed for the first line of code:

 StringBuffer str = new StringBuffer("Stanford ");

The bytecode at location 10 to 16 is then executed for the concatenation:

 str.append("Lost!!");

Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

When to use a linked list over an array/array list?

Arrays, by far, are the most widely used data structures. However, linked lists prove useful in their own unique way where arrays are clumsy - or expensive, to say the least.

Linked lists are useful to implement stacks and queues in situations where their size is subject to vary. Each node in the linked list can be pushed or popped without disturbing the majority of the nodes. Same goes for insertion/deletion of nodes somewhere in the middle. In arrays, however, all the elements have to be shifted, which is an expensive job in terms of execution time.

Binary trees and binary search trees, hash tables, and tries are some of the data structures wherein - at least in C - you need linked lists as a fundamental ingredient for building them up.

However, linked lists should be avoided in situations where it is expected to be able to call any arbitrary element by its index.

How to printf a 64-bit integer as hex?

The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.

Try using %lx or %llx. For more portability, include inttypes.h and use the PRIx64 macro.

For example: printf("val = 0x%" PRIx64 "\n", val); (note that it's string concatenation)

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

Determine if map contains a value for a key?

It already exists with find only not in that exact syntax.

if (m.find(2) == m.end() )
{
    // key 2 doesn't exist
}

If you want to access the value if it exists, you can do:

map<int, Bar>::iterator iter = m.find(2);
if (iter != m.end() )
{
    // key 2 exists, do something with iter->second (the value)
}

With C++0x and auto, the syntax is simpler:

auto iter = m.find(2);
if (iter != m.end() )
{
    // key 2 exists, do something with iter->second (the value)
}

I recommend you get used to it rather than trying to come up with a new mechanism to simplify it. You might be able to cut down a little bit of code, but consider the cost of doing that. Now you've introduced a new function that people familiar with C++ won't be able to recognize.

If you want to implement this anyway in spite of these warnings, then:

template <class Key, class Value, class Comparator, class Alloc>
bool getValue(const std::map<Key, Value, Comparator, Alloc>& my_map, int key, Value& out)
{
    typename std::map<Key, Value, Comparator, Alloc>::const_iterator it = my_map.find(key);
    if (it != my_map.end() )
    {
        out = it->second;
        return true;
    }
    return false;
}

Origin http://localhost is not allowed by Access-Control-Allow-Origin

There are 2 calls that need to set the correct headers. Initially there is a preflight check so you need something like...

app.get('/item', item.list);
app.options('/item', item.preflight);

and then have the following functions...

exports.list = function (req, res) {
Items.allItems(function (err, items) {
    ...
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(items);
      }
   );
};

and for the pre-flight checks

exports.preflight = function (req, res) {
Items.allItems(function (err, items) {
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(200);
    }
  );
};

You can consolidate the res.header() code into a single function if you want.

Also as stated above, be careful of using res.header('Access-Control-Allow-Origin', "*") this means anyone can access your site!

Recommended Fonts for Programming?

Don't forget the colours!

For some reason Delphi 7 in Twilight does not render Droid Sans Mono well, but in Visual Studio with an orange on black theme it is excellent. Deja Vu Sans Mono is the best all rounder. I use it almost everywhere. Consolas would be excellent apart from its ugly Q glyph.

One other thing I have found since I entered the world of work is that even though I have great eyesight I like to keep my code font around 12 or 13pt size both to reduce eye strain and to make sure I can't put too much text on screen. It's sort of an incentive to keep code blocks vertically short.

I note that this edit box does not respect my browser's default monospaced font. It's giving me Monaco (I'm on OSX). Monaco is horrible. It's glyphs have poorly angled elements and it's capitals are not well proportioned.

Oh, and it almost doesn't matter on Windows because your font will not look right anyway. /me dons flame retardent suit

Using the last-child selector

Another solution that might work for you is to reverse the relationship. So you would set the border for all list items. You would then use first-child to eliminate the border for the first item. The first-child is statically supported in all browsers (meaning it can't be added dynamically through other code, but first-child is a CSS2 selector, whereas last-child was added in the CSS3 specification)

Note: This only works the way you intended if you only have 2 items in the list like your example. Any 3rd item and on will have borders applied to them.

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Set HTML element's style property in javascript

For me, this works:

function transferAllStyles(elemFrom, elemTo)
{
  var prop;
  for (prop in elemFrom.style)
    if (typeof prop == "string")
      try { elemTo.style[prop] = elemFrom.style[prop]; }
      catch (ex) { /* don't care */ }
}

Jackson - Deserialize using generic class

Just write a static method in Util class. I am reading a Json from a file. you can give String also to readValue

public static <T> T convertJsonToPOJO(String filePath, Class<?> target) throws JsonParseException, JsonMappingException, IOException, ClassNotFoundException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(new File(filePath), objectMapper .getTypeFactory().constructCollectionType(List.class, Class.forName(target.getName())));
}

Usage:

List<TaskBean> list =  Util.<List<TaskBean>>convertJsonToPOJO("E:/J2eeWorkspaces/az_workspace_svn/az-client-service/dir1/dir2/filename.json", TaskBean.class);

How To Upload Files on GitHub

To upload files to your repo without using the command-line, simply type this after your repository name in the browser:

https://github.com/yourname/yourrepositoryname/upload/master

and then drag and drop your files.(provided you are on github and the repository has been created beforehand)

error C2065: 'cout' : undeclared identifier

I have VS2010, Beta 1 and Beta 2 (one on my work machine and one at home), and I've used std plenty without issues. Try typing:

std::

And see if Intellisense gives you anything. If it gives you the usual stuff (abort, abs, acos, etc.), except for cout, well then, that is quite a puzzler. Definitely look into your C++ headers in that case.

Beyond that, I would just add to make sure you're running a regular, empty project (not CLR, where Intellisense is crippled), and that you've actually attempted to build the project at least once. As I mentioned in a comment, VS2010 parses files once you've added an include; it could be that something stuck the parser and it didn't "find" cout right away. (In which case, try restarting VS maybe?)

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

AJAX jQuery refresh div every 5 seconds

Try using setInterval and include jquery library and just try removing unwrap()

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

var timeout = setInterval(reloadChat, 5000);    
function reloadChat () {

     $('#links').load('test.php');
}
</script>

UPDATE

you are using a jquery old version so include the latest jquery version

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

How to convert SecureString to System.String?

Dang. right after posting this I found the answer deep in this article. But if anyone knows how to access the IntPtr unmanaged, unencrypted buffer that this method exposes, one byte at a time so that I don't have to create a managed string object out of it to keep my security high, please add an answer. :)

static String SecureStringToString(SecureString value)
{
    IntPtr bstr = Marshal.SecureStringToBSTR(value);

    try
    {
        return Marshal.PtrToStringBSTR(bstr);
    }
    finally
    {
        Marshal.FreeBSTR(bstr);
    }
}

Check if array is empty or null

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

  1. $(this) is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).length if you need to, but that is not necessary here because the .each() loop wouldn't run if there were no items so $(this) inside your .each() loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with [] rather than new Array().
  4. if (value) when value is expected to be a string will both protect from value == null, value == undefined and value == "" so you don't have to do if (value && (value != "")). You can just do: if (value) to check for all three empty conditions.
  5. if (album_text.length === 0) will tell you if the array is empty as long as it is a valid, initialized array (which it is here).

What are you trying to do with this selector $("input[name='album_text[]']")?

excel plot against a date time x series

You will need to specify TimeSeries in Excel to be plotted. Have a look at this

Plotting Time Series

minimize app to system tray

Handle the form’s Resize event. In this handler, you override the basic functionality of the Resize event to make the form minimize to the system tray and not to the taskbar. This can be done by doing the following in your form’s Resize event handler: Check whether the form’s WindowState property is set to FormWindowState.Minimized. If yes, hide your form, enable the NotifyIcon object, and show the balloon tip that shows some information. Once the WindowState becomes FormWindowState.Normal, disable the NotifyIcon object by setting its Visible property to false. Now, you want the window to reappear when you double click on the NotifyIcon object in the taskbar. For this, handle the NotifyIcon’s MouseDoubleClick event. Here, you show the form using the Show() method.

private void frmMain_Resize(object sender, EventArgs e)
{
    if (FormWindowState.Minimized == this.WindowState)
    {
       mynotifyicon.Visible = true;
       mynotifyicon.ShowBalloonTip(500);
       this.Hide();
    }

    else if (FormWindowState.Normal == this.WindowState)
    {
       mynotifyicon.Visible = false;
    }
}

Sort & uniq in Linux shell

Beware! While it's true that "sort -u" and "sort|uniq" are equivalent, any additional options to sort can break the equivalence. Here's an example from the coreutils manual:

For example, 'sort -n -u' inspects only the value of the initial numeric string when checking for uniqueness, whereas 'sort -n | uniq' inspects the entire line.

Similarly, if you sort on key fields, the uniqueness test used by sort won't necessarily look at the entire line anymore. After being bitten by that bug in the past, these days I tend to use "sort|uniq" when writing Bash scripts. I'd rather have higher I/O overhead than run the risk that someone else in the shop won't know about that particular pitfall when they modify my code to add additional sort parameters.

CAST DECIMAL to INT

your can try this :

SELECT columnName1, CAST(columnName2 AS  SIGNED ) FROM tableName 

Finding elements not in a list

No, z is undefined. item contains a list of integers.

I think what you're trying to do is this:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in item:
  if i not in z: print i

As has been stated in other answers, you may want to try using sets.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Redirect From Action Filter Attribute

Alternatively to a redirect, if it is calling your own code, you could use this:

actionContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(new { controller = "Home", action = "Error" })
);

actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);

It is not a pure redirect but gives a similar result without unnecessary overhead.

How to request Location Permission at runtime

After having it defined in your manifest file, a friendlier alternative to the native solution would be using Aaper: https://github.com/LikeTheSalad/aaper like so:

@EnsurePermissions(permissions = [Manifest.permission.ACCESS_FINE_LOCATION])
private fun scanForLocation() {
    // Your code that needs the location permission granted.
}

Disclaimer, I'm the creator of Aaper.

Is there a way to get a list of all current temporary tables in SQL Server?

You can get list of temp tables by following query :

select left(name, charindex('_',name)-1) 
from tempdb..sysobjects
where charindex('_',name) > 0 and
xtype = 'u' and not object_id('tempdb..'+name) is null

Load CSV file with Spark

When using spark.read.csv, I find that using the options escape='"' and multiLine=True provide the most consistent solution to the CSV standard, and in my experience works the best with CSV files exported from Google Sheets.

That is,

#set inferSchema=False to read everything as string
df = spark.read.csv("myData.csv", escape='"', multiLine=True,
     inferSchema=False, header=True)

How do you give iframe 100% height

The iFrame attribute does not support percent in HTML5. It only supports pixels. http://www.w3schools.com/tags/att_iframe_height.asp

Matching a space in regex

If you're looking for a space, that would be " " (one space).

If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus).

If you're looking for common spacing, use "[ X]" or "[ X][ X]*" or "[ X]+" where X is the physical tab character (and each is preceded by a single space in all those examples).

These will work in every* regex engine I've ever seen (some of which don't even have the one-or-more "+" character, ugh).

If you know you'll be using one of the more modern regex engines, "\s" and its variations are the way to go. In addition, I believe word boundaries match start and end of lines as well, important when you're looking for words that may appear without preceding or following spaces.

For PHP specifically, this page may help.

From your edit, it appears you want to remove all non valid characters The start of this is (note the space inside the regex):

$newtag = preg_replace ("/[^a-zA-Z0-9 ]/", "", $tag);
#                                    ^ space here

If you also want trickery to ensure there's only one space between each word and none at the start or end, that's a little more complicated (and probably another question) but the basic idea would be:

$newtag = preg_replace ("/ +/", " ", $tag); # convert all multispaces to space
$newtag = preg_replace ("/^ /", "", $tag);  # remove space from start
$newtag = preg_replace ("/ $/", "", $tag);  # and end

How to add image background to btn-default twitter-bootstrap button?

Have you tried using a icon font like http://fortawesome.github.io/Font-Awesome/

Bootstrap comes with their own library, but it doesn't have as many icons as Font Awesome.

http://getbootstrap.com/components/#glyphicons

Differentiate between function overloading and function overriding

You are putting in place an overloading when you change the original types for the arguments in the signature of a method.

You are putting in place an overriding when you change the original Implementation of a method in a derived class.

How to implement Enums in Ruby?

Two ways. Symbols (:foo notation) or constants (FOO notation).

Symbols are appropriate when you want to enhance readability without littering code with literal strings.

postal_code[:minnesota] = "MN"
postal_code[:new_york] = "NY"

Constants are appropriate when you have an underlying value that is important. Just declare a module to hold your constants and then declare the constants within that.

module Foo
  BAR = 1
  BAZ = 2
  BIZ = 4
end
 
flags = Foo::BAR | Foo::BAZ # flags = 3

Added 2021-01-17

If you are passing the enum value around (for example, storing it in a database) and you need to be able to translate the value back into the symbol, there's a mashup of both approaches

COMMODITY_TYPE = {
  currency: 1,
  investment: 2,
}

def commodity_type_string(value)
  COMMODITY_TYPE.key(value)
end

COMMODITY_TYPE[:currency]

This approach inspired by andrew-grimm's answer https://stackoverflow.com/a/5332950/13468

I'd also recommend reading through the rest of the answers here since there are a lot of ways to solve this and it really boils down to what it is about the other language's enum that you care about

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

Are you using Git-Bash in Windows? I was getting the same error until I tried PowerShell and magically this error disappeared.

How do I calculate the percentage of a number?

Divide $percentage by 100 and multiply to $totalWidth. Simple maths.

How to check "hasRole" in Java Code with Spring Security?

Better late then never, let me put in my 2 cents worth.

In JSF world, within my managed bean, I did the following:


HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
SecurityContextHolderAwareRequestWrapper sc = new SecurityContextHolderAwareRequestWrapper(req, "");

As mentioned above, my understanding is that it can be done the long winded way as followed:


Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
if (principal instanceof UserDetails) {
    userDetails = (UserDetails) principal;
    Collection  authorities = userDetails.getAuthorities();
}

IOError: [Errno 2] No such file or directory trying to open a file

Hmm, there are a few things going wrong here.

for f in os.listdir(src_dir):
    os.path.join(src_dir, f)

You're not storing the result of join. This should be something like:

for f in os.listdir(src_dir):
    f = os.path.join(src_dir, f)

This open call is is the cause of your IOError. (Because without storing the result of the join above, f was still just 'file.csv', not 'src_dir/file.csv'.)

Also, the syntax:

with open(f): 

is close, but the syntax isn't quite right. It should be with open(file_name) as file_object:. Then, you use to the file_object to perform read or write operations.

And finally:

write(line)

You told python what you wanted to write, but not where to write it. Write is a method on the file object. Try file_object.write(line).

Edit: You're also clobbering your input file. You probably want to open the output file and write lines to it as you're reading them in from the input file.

See: input / output in python.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

It took me few hours to solved this because all off the settings that I found here about this error were the same but it still didn't work. The problem was tha I had a folder in my web service from which the file should be send to WinCE device, after converting that folder to an application with Classic.NetAppPool it started to work.

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.

How to know if other threads have finished?

You could also use SwingWorker, which has built-in property change support. See addPropertyChangeListener() or the get() method for a state change listener example.

Testing pointers for validity (C/C++)

Firstly, I don't see any point in trying to protect yourself from the caller deliberately trying to cause a crash. They could easily do this by trying to access through an invalid pointer themselves. There are many other ways - they could just overwrite your memory or the stack. If you need to protect against this sort of thing then you need to be running in a separate process using sockets or some other IPC for communication.

We write quite a lot of software that allows partners/customers/users to extend functionality. Inevitably any bug gets reported to us first so it is useful to be able to easily show that the problem is in the plug-in code. Additionally there are security concerns and some users are more trusted than others.

We use a number of different methods depending on performance/throughput requirements and trustworthyness. From most preferred:

  • separate processes using sockets (often passing data as text).

  • separate processes using shared memory (if large amounts of data to pass).

  • same process separate threads via message queue (if frequent short messages).

  • same process separate threads all passed data allocated from a memory pool.

  • same process via direct procedure call - all passed data allocated from a memory pool.

We try never to resort to what you are trying to do when dealing with third party software - especially when we are given the plug-ins/library as binary rather than source code.

Use of a memory pool is quite easy in most circumstances and needn't be inefficient. If YOU allocate the data in the first place then it is trivial to check the pointers against the values you allocated. You could also store the length allocated and add "magic" values before and after the data to check for valid data type and data overruns.

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

location.host vs location.hostname and cross-browser compatibility?

If you are insisting to use the window.location.origin You can put this in top of your code before reading the origin

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

Solution

PS: For the record, it was actually the original question. It was already edited :)

How to import an existing project from GitHub into Android Studio

You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.

The github repo will be created as a new project in android studio.

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

Set default option in mat-select

Try this

<mat-form-field>
    <mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
    </mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
    public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt.AsEnumerable()
    .GroupBy(r => new { Col1 = r["Col1"], Col2 = r["Col2"] })
    .Select(g =>
    {
        var row = dt.NewRow();

        row["PK"] = g.Min(r => r.Field<int>("PK"));
        row["Col1"] = g.Key.Col1;
        row["Col2"] = g.Key.Col2;

        return row;

    })
    .CopyToDataTable();

remove attribute display:none; so the item will be visible

The removeAttr() function only removes HTML attributes. The display is not a HTML attribute, it's a CSS property. You'd like to use css() function instead to manage CSS properties.

But jQuery offers a show() function which does exactly what you want in a concise call:

$("span").show();

How are "mvn clean package" and "mvn clean install" different?

package will add packaged jar or war to your target folder, We can check it when, we empty the target folder (using mvn clean) and then run mvn package.
install will do all the things that package does, additionally it will add packaged jar or war in local repository as well. We can confirm it by checking in your .m2 folder.

How to open the command prompt and insert commands using Java?

You have to set all \" (quotes) carefully. The parameter \k is used to leave the command prompt open after the execution.

1) to combine 2 commands use (for example pause and ipconfig)

Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"pause && ipconfig\"", null, selectedFile.getParentFile());

2) to show the content of a file use (MORE is a command line viewer on Windows)

File selectedFile = new File(pathToFile):
Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"MORE \"" + selectedFile.getName() + "\"\"", null, selectedFile.getParentFile());

One nesting quote \" is for the command and the file name, the second quote \" is for the filename itself, for spaces etc. in the name particularly.

Find multiple files and rename them in Linux

Scipt above can be written in one line:

find /tmp -name "*.txt" -exec bash -c 'mv $0 $(echo "$0" | sed -r \"s|.txt|.cpp|g\")' '{}' \;

How to efficiently concatenate strings in go

Note added in 2018

From Go 1.10 there is a strings.Builder type, please take a look at this answer for more detail.

Pre-201x answer

The benchmark code of @cd1 and other answers are wrong. b.N is not supposed to be set in benchmark function. It's set by the go test tool dynamically to determine if the execution time of the test is stable.

A benchmark function should run the same test b.N times and the test inside the loop should be the same for each iteration. So I fix it by adding an inner loop. I also add benchmarks for some other solutions:

package main

import (
    "bytes"
    "strings"
    "testing"
)

const (
    sss = "xfoasneobfasieongasbg"
    cnt = 10000
)

var (
    bbb      = []byte(sss)
    expected = strings.Repeat(sss, cnt)
)

func BenchmarkCopyPreAllocate(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        bs := make([]byte, cnt*len(sss))
        bl := 0
        for i := 0; i < cnt; i++ {
            bl += copy(bs[bl:], sss)
        }
        result = string(bs)
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

func BenchmarkAppendPreAllocate(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        data := make([]byte, 0, cnt*len(sss))
        for i := 0; i < cnt; i++ {
            data = append(data, sss...)
        }
        result = string(data)
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

func BenchmarkBufferPreAllocate(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        buf := bytes.NewBuffer(make([]byte, 0, cnt*len(sss)))
        for i := 0; i < cnt; i++ {
            buf.WriteString(sss)
        }
        result = buf.String()
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

func BenchmarkCopy(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        data := make([]byte, 0, 64) // same size as bootstrap array of bytes.Buffer
        for i := 0; i < cnt; i++ {
            off := len(data)
            if off+len(sss) > cap(data) {
                temp := make([]byte, 2*cap(data)+len(sss))
                copy(temp, data)
                data = temp
            }
            data = data[0 : off+len(sss)]
            copy(data[off:], sss)
        }
        result = string(data)
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

func BenchmarkAppend(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        data := make([]byte, 0, 64)
        for i := 0; i < cnt; i++ {
            data = append(data, sss...)
        }
        result = string(data)
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

func BenchmarkBufferWrite(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        var buf bytes.Buffer
        for i := 0; i < cnt; i++ {
            buf.Write(bbb)
        }
        result = buf.String()
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

func BenchmarkBufferWriteString(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        var buf bytes.Buffer
        for i := 0; i < cnt; i++ {
            buf.WriteString(sss)
        }
        result = buf.String()
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

func BenchmarkConcat(b *testing.B) {
    var result string
    for n := 0; n < b.N; n++ {
        var str string
        for i := 0; i < cnt; i++ {
            str += sss
        }
        result = str
    }
    b.StopTimer()
    if result != expected {
        b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
    }
}

Environment is OS X 10.11.6, 2.2 GHz Intel Core i7

Test results:

BenchmarkCopyPreAllocate-8         20000             84208 ns/op          425984 B/op          2 allocs/op
BenchmarkAppendPreAllocate-8       10000            102859 ns/op          425984 B/op          2 allocs/op
BenchmarkBufferPreAllocate-8       10000            166407 ns/op          426096 B/op          3 allocs/op
BenchmarkCopy-8                    10000            160923 ns/op          933152 B/op         13 allocs/op
BenchmarkAppend-8                  10000            175508 ns/op         1332096 B/op         24 allocs/op
BenchmarkBufferWrite-8             10000            239886 ns/op          933266 B/op         14 allocs/op
BenchmarkBufferWriteString-8       10000            236432 ns/op          933266 B/op         14 allocs/op
BenchmarkConcat-8                     10         105603419 ns/op        1086685168 B/op    10000 allocs/op

Conclusion:

  1. CopyPreAllocate is the fastest way; AppendPreAllocate is pretty close to No.1, but it's easier to write the code.
  2. Concat has really bad performance both for speed and memory usage. Don't use it.
  3. Buffer#Write and Buffer#WriteString are basically the same in speed, contrary to what @Dani-Br said in the comment. Considering string is indeed []byte in Go, it makes sense.
  4. bytes.Buffer basically use the same solution as Copy with extra book keeping and other stuff.
  5. Copy and Append use a bootstrap size of 64, the same as bytes.Buffer
  6. Append use more memory and allocs, I think it's related to the grow algorithm it use. It's not growing memory as fast as bytes.Buffer

Suggestion:

  1. For simple task such as what OP wants, I would use Append or AppendPreAllocate. It's fast enough and easy to use.
  2. If need to read and write the buffer at the same time, use bytes.Buffer of course. That's what it's designed for.

jQuery - Detect value change on hidden input field

This example returns the draft field value every time the hidden draft field changes its value (chrome browser):

var h = document.querySelectorAll('input[type="hidden"][name="draft"]')[0];
//or jquery.....
//var h = $('input[type="hidden"][name="draft"]')[0];

observeDOM(h, 'n', function(draftValue){ 
  console.log('dom changed draftValue:'+draftValue);
});


var observeDOM = (function(){
var MutationObserver = window.MutationObserver || 
window.WebKitMutationObserver;

  return function(obj, thistime, callback){
    if(typeof obj === 'undefined'){
      console.log('obj is undefined');
      return;
    }

    if( MutationObserver ){

        // define a new observer
        var obs = new MutationObserver(function(mutations, observer){

            if( mutations[0].addedNodes.length || mutations[0].removedNodes.length ){

               callback('pass other observations back...');

            }else if(mutations[0].attributeName == "value" ){

               // use callback to pass back value of hidden form field                            
               callback( obj.value );

            }

        });

        // have the observer observe obj for changes in children
        // note 'attributes:true' else we can't read the input attribute value
        obs.observe( obj, { childList:true, subtree:true, attributes:true  });

       }
  };
})();

MySQL timezone change?

If you have the SUPER privilege, you can set the global server time zone value at runtime with this statement:

mysql> SET GLOBAL time_zone = timezone;

How do I do pagination in ASP.NET MVC?

Here's a link that helped me with this.

It uses PagedList.MVC NuGet package. I'll try to summarize the steps

  1. Install the PagedList.MVC NuGet package

  2. Build project

  3. Add using PagedList; to the controller

  4. Modify your action to set page public ActionResult ListMyItems(int? page) { List list = ItemDB.GetListOfItems(); int pageSize = 3; int pageNumber = (page ?? 1); return View(list.ToPagedList(pageNumber, pageSize)); }

  5. Add paging links to the bottom of your view @*Your existing view*@ Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

adb devices command not working

HTC One m7 running fresh Cyanogenmod 11.

Phone is connected USB and tethering my data connection.

Then I get this surprise:

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
????????????    no permissions

SOLUTION: Turn tethering OFF on phone.

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858    device

Unique on a dataframe with only selected columns

Ok, if it doesn't matter which value in the non-duplicated column you select, this should be pretty easy:

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))
> dat[!duplicated(dat[,c('id','id2')]),]
  id id2 somevalue
1  1   1         x
3  3   4         z

Inside the duplicated call, I'm simply passing only those columns from dat that I don't want duplicates of. This code will automatically always select the first of any ambiguous values. (In this case, x.)

How to check if a div is visible state or not?

is(':visible') checks the display property of an element, you can use css method.

if (!$("#singlechatpanel-1").css('visibility') === 'hidden') {
   // ...
}

If you set the display property of the element to none then your if statement returns true.

How do I split a string on a delimiter in Bash?

You can set the internal field separator (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to IFS only takes place to that single command's environment (to read ). It then parses the input according to the IFS variable value into an array, which we can then iterate over.

IFS=';' read -ra ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
    # process "$i"
done

It will parse one line of items separated by ;, pushing it into an array. Stuff for processing whole of $IN, each time one line of input separated by ;:

 while IFS=';' read -ra ADDR; do
      for i in "${ADDR[@]}"; do
          # process "$i"
      done
 done <<< "$IN"

How to redirect user's browser URL to a different page in Nodejs?

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();

How to detect chrome and safari browser (webkit)

If you dont want to use $.browser, take a look at case 1, otherwise maybe case 2 and 3 can help you just to get informed because it is not recommended to use $.browser (the user agent can be spoofed using this). An alternative can be using jQuery.support that will detect feature support and not agent info.

But...

If you insist on getting browser type (just Chrome or Safari) but not using $.browser, case 1 is what you looking for...


This fits your requirement:

Case 1: (No jQuery and no $.browser, just javascript)

Live Demo: http://jsfiddle.net/oscarj24/DJ349/

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

if (isChrome) alert("You are using Chrome!");
if (isSafari) alert("You are using Safari!");

These cases I used in times before and worked well but they are not recommended...

Case 2: (Using jQuery and $.browser, this one is tricky)

Live Demo: http://jsfiddle.net/oscarj24/gNENk/

$(document).ready(function(){

    /* Get browser */
    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

    /* Detect Chrome */
    if($.browser.chrome){
        /* Do something for Chrome at this point */
        /* Finally, if it is Chrome then jQuery thinks it's 
           Safari so we have to tell it isn't */
        $.browser.safari = false;
    }

    /* Detect Safari */
    if($.browser.safari){
        /* Do something for Safari */
    }

});

Case 3: (Using jQuery and $.browser, "elegant" solution)

Live Demo: http://jsfiddle.net/oscarj24/uJuEU/

$.browser.chrome = $.browser.webkit && !!window.chrome;
$.browser.safari = $.browser.webkit && !window.chrome;

if ($.browser.chrome) alert("You are using Chrome!");
if ($.browser.safari) alert("You are using Safari!");

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

What is the Git equivalent for revision number?

Consider to use

git-rev-label

Gives information about Git repository revision in format like master-c73-gabc6bec. Can fill template string or file with environment variables and information from Git. Useful to provide information about version of the program: branch, tag, commit hash, commits count, dirty status, date and time. One of the most useful things is count of commits, not taking into account merged branches - only first parent.

Convert byte slice to io.Reader

To get a type that implements io.Reader from a []byte slice, you can use bytes.NewReader in the bytes package:

r := bytes.NewReader(byteData)

This will return a value of type bytes.Reader which implements the io.Reader (and io.ReadSeeker) interface.

Don't worry about them not being the same "type". io.Reader is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.

Multiple files upload (Array) with CodeIgniter 2.0

    public function imageupload() 
    {

      $count = count($_FILES['userfile']['size']);

  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'gif|jpg|png|bmp';
  $config['max_size']   = '0';
  $config['max_width']  = '0';
  $config['max_height']  = '0';

  $config['image_library'] = 'gd2';
  $config['create_thumb'] = TRUE;
  $config['maintain_ratio'] = FALSE;
  $config['width'] = 50;
  $config['height'] = 50;

  foreach($_FILES as $key=>$value)
  { 
     for($s=0; $s<=$count-1; $s++)
     {
     $_FILES['userfile']['name']=$value['name'][$s];
     $_FILES['userfile']['type']    = $value['type'][$s];
     $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s]; 
     $_FILES['userfile']['error']       = $value['error'][$s];
     $_FILES['userfile']['size']    = $value['size'][$s];  

         $this->load->library('upload', $config);

         if ($this->upload->do_upload('userfile'))
         {
           $data['userfile'][$i] = $this->upload->data();
       $full_path = $data['userfile']['full_path'];


           $config['source_image'] = $full_path;
           $config['new_image'] = './uploads/resiezedImage';

           $this->load->library('image_lib', $config);
           $this->image_lib->resize(); 
           $this->image_lib->clear();

         }
         else
         {
           $data['upload_errors'][$i] = $this->upload->display_errors();
         } 
     }
  }
}

Better naming in Tuple classes than "Item1", "Item2"

Here is an overly complicated version of what you are asking:

class MyTuple : Tuple<int, int>
{
    public MyTuple(int one, int two)
        :base(one, two)
    {

    }

    public int OrderGroupId { get{ return this.Item1; } }
    public int OrderTypeId { get{ return this.Item2; } }

}

Why not just make a class?

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Above solution didn't work for me.

First run brew doctor. if you see something like

Error: unknown or unsupported macOS version: :mountain_lion

then there are some outdated packages which needs to be removed, mine was
mongodb.

It could be python@2, node@6 or some other package.

uninstall those packages brew uninstall [name] then run brew doctor to verify if everything is ok. Then you can reinstall those packages again after brew update && brew upgrade.

How to set timeout for a line of c# code

You can use the IAsyncResult and Action class/interface to achieve this.

public void TimeoutExample()
{
    IAsyncResult result;
    Action action = () =>
    {
        // Your code here
    };

    result = action.BeginInvoke(null, null);

    if (result.AsyncWaitHandle.WaitOne(10000))
         Console.WriteLine("Method successful.");
    else
         Console.WriteLine("Method timed out.");
}

align images side by side in html

I suggest to use a container for each img p like this:

<div class="image123">
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif" height="200" width="200"  />
        <p style="text-align:center;">This is image 1</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 2</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 3</p>
    </div>
</div>

Then apply float:left to each container. I add and 5px margin right so there is a space between each image. Also alway close your elements. Maybe in html img tag is not important to close but in XHTML is.

fiddle

Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:

html

<div class="image123">
    <div>
        <img src="/images/tv.gif" />
        <p>This is image 1</p>
    </div>
    <div>
        <img class="middle-img" src="/images/tv.gif/" />
        <p>This is image 2</p>
    </div>
    <div>
        <img src="/images/tv.gif/" />
        <p>This is image 3</p>
    </div>
</div>

css

div{
    float:left;
    margin-right:5px;
}

div > img{
   height:200px;
    width:200px;
}

p{
    text-align:center;
}

It's generally recommended that you use linked style sheets because:

  • They can be cached by browsers for performance
  • Generally a lot easier to maintain for a development perspective

source

fiddle

Referenced Project gets "lost" at Compile Time

Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework

Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type

Finally, Rebuild the solution.

How to use componentWillMount() in React Hooks?

https://reactjs.org/docs/hooks-reference.html#usememo

Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.

how to set length of an column in hibernate with maximum length

You need to alter your table. Increase the column width using a DDL statement.

please see here

http://dba-oracle.com/t_alter_table_modify_column_syntax_example.htm

Can VS Code run on Android?

There is a browser-based implementation of VSC that allows you to run it on a browser on your Android (or any other) device. Check it out here:

https://stackblitz.com/

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

After validation and before INSERT check if username already exists, using mysqli(procedural). This works:

//check if username already exists
       include 'phpscript/connect.php'; //connect to your database

       $sql = "SELECT username FROM users WHERE username = '$username'";
       $result = $conn->query($sql);

       if($result->num_rows > 0) {
           $usernameErr =  "username already taken"; //takes'em back to form
       } else { // go on to INSERT new record

How to replace � in a string

As others have said, you posted 3 characters instead of one. I suggest you run this little snippet of code to see what's actually in your string:

public static void dumpString(String text)
{
    for (int i=0; i < text.length(); i++)
    {
        System.out.println("U+" + Integer.toString(text.charAt(i), 16) 
                           + " " + text.charAt(i));
    }
}

If you post the results of that, it'll be easier to work out what's going on. (I haven't bothered padding the string - we can do that by inspection...)

Node/Express file upload

Personally multer didn't work for me after weeks trying to get this file upload thing right. Then I switch to formidable and after a few days I got it working perfectly without any error, multiple files, express and react.js even though react is optional. Here's the guide: https://www.youtube.com/watch?v=jtCfvuMRsxE&t=122s

How to change checkbox's border style in CSS?

Here is a pure CSS (no images) cross-browser solution based on Martin's Custom Checkboxes and Radio Buttons with CSS3 LINK: http://martinivanov.net/2012/12/21/imageless-custom-checkboxes-and-radio-buttons-with-css3-revisited/

Here is a jsFiddle: http://jsfiddle.net/DJRavine/od26wL6n/

I have tested this on the following browsers:

  • FireFox (41.0.2) (42)
  • Google Chrome (46.0.2490.80 m)
  • Opera (33.0.1990.43)
  • Internet Explorer (11.0.10240.16431 [Update Versions: 11.0.22])
  • Microsoft Edge (20.10240.16384.0)
  • Safari Mobile iPhone iOS9 (601.1.46)

_x000D_
_x000D_
label,_x000D_
input[type="radio"] + span,_x000D_
input[type="radio"] + span::before,_x000D_
label,_x000D_
input[type="checkbox"] + span,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
 _x000D_
label *,_x000D_
label *_x000D_
{_x000D_
    cursor: pointer;_x000D_
}_x000D_
 _x000D_
input[type="radio"],_x000D_
input[type="checkbox"]_x000D_
{_x000D_
    opacity: 0;_x000D_
    position: absolute;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span,_x000D_
input[type="checkbox"] + span_x000D_
{_x000D_
    font: normal 11px/14px Arial, Sans-serif;_x000D_
    color: #333;_x000D_
}_x000D_
 _x000D_
label:hover span::before,_x000D_
label:hover span::before_x000D_
{_x000D_
    -moz-box-shadow: 0 0 2px #ccc;_x000D_
    -webkit-box-shadow: 0 0 2px #ccc;_x000D_
    box-shadow: 0 0 2px #ccc;_x000D_
}_x000D_
 _x000D_
label:hover span,_x000D_
label:hover span_x000D_
{_x000D_
    color: #000;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span::before,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    content: "";_x000D_
    width: 12px;_x000D_
    height: 12px;_x000D_
    margin: 0 4px 0 0;_x000D_
    border: solid 1px #a8a8a8;_x000D_
    line-height: 14px;_x000D_
    text-align: center;_x000D_
     _x000D_
    -moz-border-radius: 100%;_x000D_
    -webkit-border-radius: 100%;_x000D_
    border-radius: 100%;_x000D_
     _x000D_
    background: #f6f6f6;_x000D_
    background: -moz-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -o-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: radial-gradient(#f6f6f6, #dfdfdf);_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before,_x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    color: #666;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:disabled + span,_x000D_
input[type="checkbox"]:disabled + span_x000D_
{_x000D_
    cursor: default;_x000D_
     _x000D_
    -moz-opacity: .4;_x000D_
    -webkit-opacity: .4;_x000D_
    opacity: .4;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    -moz-border-radius: 2px;_x000D_
    -webkit-border-radius: 2px;_x000D_
    border-radius: 2px;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before_x000D_
{_x000D_
    content: "\2022";_x000D_
    font-size: 30px;_x000D_
    margin-top: -1px;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    content: "\2714";_x000D_
    font-size: 12px;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="blue"] + span::before_x000D_
{_x000D_
    border: solid 1px blue;_x000D_
    background: #B2DBFF;_x000D_
    background: -moz-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -o-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: radial-gradient(#B2DBFF, #dfdfdf);_x000D_
}_x000D_
input[class="blue"]:checked + span::before_x000D_
{_x000D_
    color: darkblue;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="red"] + span::before_x000D_
{_x000D_
    border: solid 1px red;_x000D_
    background: #FF9593;_x000D_
    background: -moz-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -o-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: radial-gradient(#FF9593, #dfdfdf);_x000D_
}_x000D_
input[class="red"]:checked + span::before_x000D_
{_x000D_
    color: darkred;_x000D_
}
_x000D_
 <label><input type="radio" checked="checked" name="radios-01" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" disabled="disabled" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-02"  class="blue" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" class="blue" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" disabled="disabled" class="blue" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-03"  class="red" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" class="red" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" disabled="disabled" class="red" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="blue" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="blue" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="blue" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="red" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="red" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="red" /><span>disabled checkbox</span></label>
_x000D_
_x000D_
_x000D_

Can vue-router open a link in a new tab?

Just write this code in your routing file :

{
  name: 'Google',
  path: '/google',
  beforeEnter() {                    
                window.open("http://www.google.com", 
                '_blank');
            }
}

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.

Use the subplots_adjust() function to move the bottom of the subplot up:

fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.

Then play with the offset in the legend bbox_to_anchor part of the legend command, to get the legend box where you want it. Some combination of setting the figsize and using the subplots_adjust(bottom=...) should produce a quality plot for you.

Alternative: I simply changed the line:

fig = plt.figure(1)

to:

fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')

and changed

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))

to

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))

and it shows up fine on my screen (a 24-inch CRT monitor).

Here figsize=(M,N) sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport option when including graphics.

AngularJS sorting by property

I will add my upgraded version of filter which able to supports next syntax:

ng-repeat="(id, item) in $ctrl.modelData | orderObjectBy:'itemProperty.someOrder':'asc'

app.filter('orderObjectBy', function(){

         function byString(o, s) {
            s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
            s = s.replace(/^\./, '');           // strip a leading dot
            var a = s.split('.');
            for (var i = 0, n = a.length; i < n; ++i) {
                var k = a[i];
                if (k in o) {
                    o = o[k];
                } else {
                    return;
                }
            }
            return o;
        }

        return function(input, attribute, direction) {
            if (!angular.isObject(input)) return input;

            var array = [];
            for(var objectKey in input) {
                if (input.hasOwnProperty(objectKey)) {
                    array.push(input[objectKey]);
                }
            }

            array.sort(function(a, b){
                a = parseInt(byString(a, attribute));
                b = parseInt(byString(b, attribute));
                return direction == 'asc' ? a - b : b - a;
            });
            return array;
        }
    })

Thanks to Armin and Jason for their answers in this thread, and Alnitak in this thread.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Get first key in a (possibly) associative array?

This is the easier way I had ever found. Fast and only two lines of code :-D

$keys = array_keys($array);
echo $array[$keys[0]];

How to search if dictionary value contains certain string with Python

You can do it like this:

#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
      'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(values, searchFor):
    for k in values:
        for v in values[k]:
            if searchFor in v:
                return k
    return None

#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName

Returning boolean if set is empty

"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()

How to apply an XSLT Stylesheet in C#

Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:

var myXslTrans = new XslCompiledTransform(); 
myXslTrans.Load("stylesheet.xsl"); 
myXslTrans.Transform("source.xml", "result.html"); 

(Sorry for posing this as an answer, but the code block support in comments is rather limited.)

In VB.NET, you don't even need a variable:

With New XslCompiledTransform()
    .Load("stylesheet.xsl")
    .Transform("source.xml", "result.html")
End With

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

'React' must be in scope when using JSX react/react-in-jsx-scope?

For those who still don't get the accepted solution :

Add

import React from 'react'
import ReactDOM from 'react-dom'

at the top of the file.

Drop rows containing empty cells from a pandas DataFrame

value_counts omits NaN by default so you're most likely dealing with "".

So you can just filter them out like

filter = df["Tenant"] != ""
dfNew = df[filter]

how to get the 30 days before date from Todays Date

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());

Example.

SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE()); 

Quickest way to clear all sheet contents VBA

The .Cells range isn't limited to ones that are being used, so your code is clearing the content of 1,048,576 rows and 16,384 columns - 17,179,869,184 total cells. That's going to take a while. Just clear the UsedRange instead:

Sheets("Zeros").UsedRange.ClearContents

Alternately, you can delete the sheet and re-add it:

Application.DisplayAlerts = False
Sheets("Zeros").Delete
Application.DisplayAlerts = True
Dim sheet As Worksheet
Set sheet = Sheets.Add
sheet.Name = "Zeros"

Extract digits from a string in Java

Use regular expression to match your requirement.

String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();     
System.out.print(num);                 
}

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

WCF Exception: Could not find a base address that matches scheme http for the endpoint

My issue was caused by missing bindings in IIS, in the left tree view "Connections", under Sites, Right click on your site > edit bindings > add > https

Choose 'IIS Express Development Certificate' and set port to 443 Then I added another binding to the webconfig:

<endpoint address="wsHttps" binding="wsHttpBinding" bindingConfiguration="DefaultWsHttpBinding" name="Your.bindingname" contract="Your.contract" />

Also added to serviceBehaviours: <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />

And eventually it worked, none of the solutions I checked on stackoverflow for this error was applicable to my specific scenario, so including here in case it helps others

Crontab Day of the Week syntax

    :-) Sunday    |    0  ->  Sun
                  |  
        Monday    |    1  ->  Mon
       Tuesday    |    2  ->  Tue
     Wednesday    |    3  ->  Wed
      Thursday    |    4  ->  Thu
        Friday    |    5  ->  Fri
      Saturday    |    6  ->  Sat
                  |  
    :-) Sunday    |    7  ->  Sun

As you can see above, and as said before, the numbers 0 and 7 are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.

Examples of Number or Abbreviation Use

15 09 * * 5,6,0             command
15 09 * * 5,6,7             command
15 09 * * 5-7               command
15 09 * * Fri,Sat,Sun       command

The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.

In Detail

Having two numbers 0 and 7 for Sunday can be useful for writing weekday ranges starting with 0 or ending with 7. So you can write ranges starting with Sunday or ending with it, like 0-2 or 5-7 for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

I had the same problem and it took a lot of reading SO posts and Google's documentation. I finally found this from the Cloud SQL FAQ:

Google Cloud SQL does not support SUPER privileges, which means that GRANT ALL PRIVILEGES statements will not work. As an alternative, you can use GRANT ALL ON `%`.*

Format a JavaScript string using placeholders and an object of substitutions?

As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf().

Placeholders:

  • %s String.
  • %d,%i Integer number.
  • %f Floating point number.
  • %o Object hyperlink.

e.g.

console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);

BTW, to see the output:

  • In Chrome, use shortcut Ctrl + Shift + J or F12 to open developer tool.
  • In Firefox, use shortcut Ctrl + Shift + K or F12 to open developer tool.

@Update - nodejs support

Seems nodejs don't support %f, instead, could use %d in nodejs. With %d number will be printed as floating number, not just integer.

Windows Batch Files: if else

You have to do the following:

if "%1" == "" (
    echo The variable is empty
) ELSE (
    echo The variable contains %1
)

How to check if an object is a list or tuple (but not string)?

Generally speaking, the fact that a function which iterates over an object works on strings as well as tuples and lists is more feature than bug. You certainly can use isinstance or duck typing to check an argument, but why should you?

That sounds like a rhetorical question, but it isn't. The answer to "why should I check the argument's type?" is probably going to suggest a solution to the real problem, not the perceived problem. Why is it a bug when a string is passed to the function? Also: if it's a bug when a string is passed to this function, is it also a bug if some other non-list/tuple iterable is passed to it? Why, or why not?

I think that the most common answer to the question is likely to be that developers who write f("abc") are expecting the function to behave as though they'd written f(["abc"]). There are probably circumstances where it makes more sense to protect developers from themselves than it does to support the use case of iterating across the characters in a string. But I'd think long and hard about it first.

How to close the command line window after running a batch file?

Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.

 tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
 exit 0

How to get complete current url for Cakephp

I use $this->here for the path, to get the whole URL you'll have to do as Juhana said and use the $_SERVER variables. There's no need to use a Cake function for this.

Numpy matrix to array

You can try the following variant:

result=np.array(M).flatten()

Increasing the Command Timeout for SQL command

Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code

scGetruntotals.CommandTimeout = 180;

Note : the parameter value is in seconds.

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

How to check if all inputs are not empty with jQuery

Use each:

var isValid;
$("input").each(function() {
   var element = $(this);
   if (element.val() == "") {
       isValid = false;
   }
});

However you probably will be better off using something like jQuery validate which IMO is cleaner.

How to download an entire directory and subdirectories using wget?

This will help

wget -m -np -c --level 0 --no-check-certificate -R"index.html*"http://www.your-websitepage.com/dir

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

If the mongoDB server is already installed and if you are unable to connect from a remote host then follow the below steps,

Login to your machine, open mongodb configuration file located at /etc/mongod.conf and change the bindIp field to specific ip / 0.0.0.0 , after that restart mongodb server.

    sudo vi /etc/mongod.conf
  • The file should contain the following kind of content:

      systemLog:
          destination: file
          path: "/var/log/mongodb/mongod.log"
          logAppend: true
      storage:
          journal:
              enabled: true
      processManagement:
          fork: true
      net:
          bindIp: 127.0.0.1  // change here to 0.0.0.0
          port: 27017
      setParameter:
          enableLocalhostAuthBypass: false
    
  • Once you change the bindIp, then you have to restart the mongodb, using the following command

      sudo service mongod restart
    
  • Now you'll be able to connect to the mongodb server, from remote server.

How can you undo the last git add?

You can use

git reset

to undo the recently added local files

 git reset file_name

to undo the changes for a specific file

Getting the 'external' IP address in Java

System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));

How to make <div> fill <td> height

This questions is already answered here. Just put height: 100% in both the div and the container td.

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

This is considered as features in Gitlab.

Maintainer / Owner access is never able to force push again for default & protected branch, as stated in this docs enter image description here

What is the "continue" keyword and how does it work in Java?

Let's see an example:

int sum = 0;
for(int i = 1; i <= 100 ; i++){
    if(i % 2 == 0)
         continue;
    sum += i;
}

This would get the sum of only odd numbers from 1 to 100.

Programmatically getting the MAC of an Android device

Getting the MAC address through WifiInfo.getMacAddress() won't work on Marshmallow and above, it has been disabled and will return the constant value of 02:00:00:00:00:00.

What is the difference between an int and a long in C++?

It is implementation dependent.

For example, under Windows they are the same, but for example on Alpha systems a long was 64 bits whereas an int was 32 bits. This article covers the rules for the Intel C++ compiler on variable platforms. To summarize:

  OS           arch           size
Windows       IA-32        4 bytes
Windows       Intel 64     4 bytes
Windows       IA-64        4 bytes
Linux         IA-32        4 bytes
Linux         Intel 64     8 bytes
Linux         IA-64        8 bytes
Mac OS X      IA-32        4 bytes
Mac OS X      Intel 64     8 bytes  

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

Using the int value 1002 seems to work for PHP 5.3.0:

public static function createDB() {
    $dbHost="localhost";
    $dbName="project";
    $dbUser="admin";
    $dbPassword="whatever";
    $dbOptions=array(1002 => 'SET NAMES utf8',);
    return new DB($dbHost, $dbName, $dbUser, $dbPassword,$dbOptions);
}

function createConnexion() {
    return new PDO(
        "mysql:host=$this->dbHost;dbname=$this->dbName",
        $this->dbUser,
        $this->dbPassword,
        $this->dbOptions); 
}

How to convert Varchar to Int in sql server 2008?

That is how you would do it, is it throwing an error? Are you sure the value you are trying to convert is convertible? For obvious reasons you cannot convert abc123 to an int.

UPDATE

Based on your comments I would remove any spaces that are in the values you are trying to convert.

Uncaught TypeError: Cannot read property 'value' of null

Instead of document or $(document) to avoid JQuery, you can add a TimeOut to validate the objects. TimeOut is executed after loading all objects within the page and other events...

setTimeout(function () { 

var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
....
....
....

}, 0);

How to calculate the angle between a line and the horizontal axis?

First find the difference between the start point and the end point (here, this is more of a directed line segment, not a "line", since lines extend infinitely and don't start at a particular point).

deltaY = P2_y - P1_y
deltaX = P2_x - P1_x

Then calculate the angle (which runs from the positive X axis at P1 to the positive Y axis at P1).

angleInDegrees = arctan(deltaY / deltaX) * 180 / PI

But arctan may not be ideal, because dividing the differences this way will erase the distinction needed to distinguish which quadrant the angle is in (see below). Use the following instead if your language includes an atan2 function:

angleInDegrees = atan2(deltaY, deltaX) * 180 / PI

EDIT (Feb. 22, 2017): In general, however, calling atan2(deltaY,deltaX) just to get the proper angle for cos and sin may be inelegant. In those cases, you can often do the following instead:

  1. Treat (deltaX, deltaY) as a vector.
  2. Normalize that vector to a unit vector. To do so, divide deltaX and deltaY by the vector's length (sqrt(deltaX*deltaX+deltaY*deltaY)), unless the length is 0.
  3. After that, deltaX will now be the cosine of the angle between the vector and the horizontal axis (in the direction from the positive X to the positive Y axis at P1).
  4. And deltaY will now be the sine of that angle.
  5. If the vector's length is 0, it won't have an angle between it and the horizontal axis (so it won't have a meaningful sine and cosine).

EDIT (Feb. 28, 2017): Even without normalizing (deltaX, deltaY):

  • The sign of deltaX will tell you whether the cosine described in step 3 is positive or negative.
  • The sign of deltaY will tell you whether the sine described in step 4 is positive or negative.
  • The signs of deltaX and deltaY will tell you which quadrant the angle is in, in relation to the positive X axis at P1:
    • +deltaX, +deltaY: 0 to 90 degrees.
    • -deltaX, +deltaY: 90 to 180 degrees.
    • -deltaX, -deltaY: 180 to 270 degrees (-180 to -90 degrees).
    • +deltaX, -deltaY: 270 to 360 degrees (-90 to 0 degrees).

An implementation in Python using radians (provided on July 19, 2015 by Eric Leschinski, who edited my answer):

from math import *
def angle_trunc(a):
    while a < 0.0:
        a += pi * 2
    return a

def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark):
    deltaY = y_landmark - y_orig
    deltaX = x_landmark - x_orig
    return angle_trunc(atan2(deltaY, deltaX))

angle = getAngleBetweenPoints(5, 2, 1,4)
assert angle >= 0, "angle must be >= 0"
angle = getAngleBetweenPoints(1, 1, 2, 1)
assert angle == 0, "expecting angle to be 0"
angle = getAngleBetweenPoints(2, 1, 1, 1)
assert abs(pi - angle) <= 0.01, "expecting angle to be pi, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 3)
assert abs(angle - pi/2) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 0)
assert abs(angle - (pi+pi/2)) <= 0.01, "expecting angle to be pi+pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(1, 1, 2, 2)
assert abs(angle - (pi/4)) <= 0.01, "expecting angle to be pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -2, -2)
assert abs(angle - (pi+pi/4)) <= 0.01, "expecting angle to be pi+pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -1, 2)
assert abs(angle - (pi/2)) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)

All tests pass. See https://en.wikipedia.org/wiki/Unit_circle