Programs & Examples On #Classpath

In Java, the classpath tells the Java Virtual Machine where to look for user-defined classes and packages when running Java programs. The classpath is a parameter and can be set either on the command-line, or through an environment variable.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

In Intellij 13, it looks it's slightly different again. Here are the instructions for Intellij 13:

  1. click on the Project view or unhide it by clicking on the "1: Project" button on the left border of the window or by pressing Alt + 1
  2. find your project or sub-module and click on it to highlight it, then press F4, or right click and choose "Open Module Settings" (on IntelliJ 14 it became F12)
  3. click on the dependencies tab
  4. Click the "+" button on the right and select "Jars or directories..."
  5. Find your path and click OK
  6. In the dialog with "Choose Categories of Selected File", choose Classes (even if it's properties), press OK and OK again
  7. You can now run your application and it will have the selected path in the class path

File inside jar is not visible for spring

The error message is correct (if not very helpful): the file we're trying to load is not a file on the filesystem, but a chunk of bytes in a ZIP inside a ZIP.

Through experimentation (Java 11, Spring Boot 2.3.x), I found this to work without changing any config or even a wildcard:

var resource = ResourceUtils.getURL("classpath:some/resource/in/a/dependency");
new BufferedReader(
  new InputStreamReader(resource.openStream())
).lines().forEach(System.out::println);

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

With the suggestions @jhadesdev and the explanations from others, I've found the issue here.

After adding the code to see what was visible to the various class loaders I found this:

All versions of log4j Logger: 
  zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of log4j visible from the classloader of the OAuthAuthorizer class: 
  zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of XMLConfigurator: 
  jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

All versions of XMLConfigurator visible from the classloader of the OAuthAuthorizer class: 
  jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

I noticed that another version of XMLConfigurator was possibly getting picked up. I decompiled that class and found this at line 60 (where the error was in the original stack trace) private static final Logger log = Logger.getLogger(XMLConfigurator.class); and that class was importing from org.apache.log4j.Logger!

So it was this class that was being loaded and used. My fix was to rename the jar file that contained this file as I can't find where I explicitly or indirectly load it. Which may pose a problem when I actually deploy.

Thanks for all help and the much needed lesson on class loading.

Where is the correct location to put Log4j.properties in an Eclipse project?

If you have a library and you want to append the log4j:

  1. Create a folder named "resources" in your projet.
  2. Create a .properties file named log4j
  3. Set properties in log4j.properties file
  4. Push right button in the project and go to properties->Java Build Path and, finally, go to the "Source" tab.
  5. Push Add folder and search the "resources" folder created in step 1.
  6. Finish.

(I have assumed that you have the log4j library added.)

PD: Sorry for my english.

Intellij Cannot resolve symbol on import

For 2020.1.4 Ultimate edition, I had to do the following

View -> Maven -> Generate Sources and Update Folders For all Projects

The issue for me was the libraries were not getting populated with mvn -U clean install from the terminal.

enter image description here

How to use ClassLoader.getResources() correctly?

Here is code based on bestsss' answer:

    Enumeration<URL> en = getClass().getClassLoader().getResources(
            "META-INF");
    List<String> profiles = new ArrayList<>();
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                System.out.println(entry);
            }
        }
    }

Adding to the classpath on OSX

If you want to make a certain set of JAR files (or .class files) available to every Java application on the machine, then your best bet is to add those files to /Library/Java/Extensions.

Or, if you want to do it for every Java application, but only when your Mac OS X account runs them, then use ~/Library/Java/Extensions instead.

EDIT: If you want to do this only for a particular application, as Thorbjørn asked, then you will need to tell us more about how the application is packaged.

Find where java class is loaded from

Typically, we don't what to use hardcoding. We can get className first, and then use ClassLoader to get the class URL.

        String className = MyClass.class.getName().replace(".", "/")+".class";
        URL classUrl  = MyClass.class.getClassLoader().getResource(className);
        String fullPath = classUrl==null ? null : classUrl.getPath();

How do I resolve ClassNotFoundException?

If you have added multiple (Third-Party)**libraries and Extends **Application class

Then it might occur.

For that, you have to set multiDexEnabled true and replace your extended Application class with MultiDexApplication.

It will be solved.

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

Adding an external directory to Tomcat classpath

I might be a bit late for the party but I follow below steps to make it fully configurable using IntelliJ's way of in-IDE app test. I believe the best way to go with is to Combine below with @BelusC's answer.

1. run the application using IDE's tomcat run config. 
2. ps -ef | grep -i tomcat //this will give you a good idea about what the ide doing actually.
3. Copy the -Dcatalina.base parameter value from the command. this is your application specific catalina base. In this folder you can play with catalina.properties, application root path etc.. basically everything you have been doing is doable here too. 

Get a list of resources from classpath directory

Neither of answers worked for me even though I had my resources put in resources folders and followed the above answers. What did make a trick was:

@Value("file:*/**/resources/**/schema/*.json")
private Resource[] resources;

Java Spring - How to use classpath to specify a file location?

From an answer of @NimChimpsky in similar question:

Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();

Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).

Note that Resource have a method to get a java.io.File so you can also use:

Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

Classpath including JAR within a JAR

You need to build a custom class-loader to do this or a third-party library that supports this. Your best bet is to extract the jar from the runtime and add them to the classpath (or have them already added to the classpath).

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

I have found when I am using a manifest that the listing of jars for the classpath need to have a space after the listing of each jar e.g. "required_lib/sun/pop3.jar required_lib/sun/smtp.jar ". Even if it is the last in the list.

Add a properties file to IntelliJ's classpath

I have the same problem and it annoys me tremendously!!

I have always thought I was surposed to do as answer 2. That used to work in Intellij 9 (now using 10).

However I figured out that by adding these line to my maven pom file helps:

<build>
  ...
  <resources>
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
  ...
</build>

How to place a file on classpath in Eclipse?

Just to add. If you right-click on an eclipse project and select Properties, select the Java Build Path link on the left. Then select the Source Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src folder is the classpath folder.

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

Differences between "java -cp" and "java -jar"?

I prefer the first version to start a java application just because it has less pitfalls ("welcome to classpath hell"). The second one requires an executable jar file and the classpath for that application has to be defined inside the jar's manifest (all other classpath declaration will be silently ignored...). So with the second version you'd have to look into the jar, read the manifest and try to find out if the classpath entries are valid from where the jar is stored... That's avoidable.

I don't expect any performance advantages or disadvantages for either version. It's just telling the jvm which class to use for the main thread and where it can find the libraries.

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Actually found this answer on superuser.com, but I had to copy tools.jar from my JDK\lib directory to the JRE\lib directory.

Makes ZERO sense...only thing I can think of is Sun introduced this bug in the latest Java runtime (Java 7 Update 11) or a bug in Ant in how it reads the current JDK location (the JRE is more updated than the JDK obviously which is also stupid of Sun...they should release the JDK each time they update the JRE).

My JAVA_HOME was set correctly. I confirmed by doing "set JAVA_HOME". It pointed to my JDK directory and was spelled correctly. However, Ant was claiming it couldn't find javac, but thought JAVA_HOME was in my JRE directory.

My system worked fine before the latest Sun JRE7 updates (10 and 11). Ant is version 1.8.4

"Could not find or load main class" Error while running java program using cmd prompt

When the Main class is inside a package then you need to run it as follows :

java <packageName>.<MainClassName>

In your case you should run the program as follows :

java org.tij.exercises.HelloWorld 

Execute jar file with multiple classpath libraries from command prompt

This will not work java -cp lib\*.jar -jar myproject.jar. You have to put it jar by jar.

So in case of commons-codec-1.3.jar.

java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar and so on.

The other solution might be putting all your jars to ext directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.

Unbound classpath container in Eclipse

I had the same problem even after installing JDK 1.7. I corrected it by adding the bin directory to my PATH. So I went to

computer>properties>advanced>environment variables

and then added

C:\Program Files\Java\jdk1.7.0_55\bin;

then I followed these instructions

http://clean-clouds.com/2012/12/06/how-to-install-and-add-jre7-in-eclipse/

Including all the jars in a directory within the Java classpath

If you really need to specify all the .jar files dynamically you could use shell scripts, or Apache Ant. There's a commons project called Commons Launcher which basically lets you specify your startup script as an ant build file (if you see what I mean).

Then, you can specify something like:

<path id="base.class.path">
    <pathelement path="${resources.dir}"/>
    <fileset dir="${extensions.dir}" includes="*.jar" />
    <fileset dir="${lib.dir}" includes="*.jar"/>
</path>

In your launch build file, which will launch your application with the correct classpath.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

Java: how to import a jar file from command line

You could run it without the -jar command line argument if you happen to know the name of the main class you wish to run:

java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass

If perchance you are using linux, you should use ":" instead of ";" in the classpath.

How to load/reference a file as a File instance from the classpath

I find this one-line code as most efficient and useful:

File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());

Works like a charm.

TestNG ERROR Cannot find class in classpath

in Intellij, what resolved the issue for me was to open the Maven right side toolbar

choose "Clean" , "install" and hit the "Play" button:

see screenshot

how to make jni.h be found?

For me it was a simple matter of being sure to include the JDK installation (I'd only had the JRE). My R CMD javareconf output was looking like:

Java interpreter : /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
Java version     : 1.8.0_191
Java home path   : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java compiler    : not present
Java headers gen.:
Java archive tool:

trying to compile and link a JNI program
detected JNI cpp flags    :
detected JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c conftest.c -o conftest.o
conftest.c:1:17: fatal error: jni.h: No such file or directory
compilation terminated.
/usr/lib/R/etc/Makeconf:159: recipe for target 'conftest.o' failed
make: *** [conftest.o] Error 1
Unable to compile a JNI program


JAVA_HOME        : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java library path:
JNI cpp flags    :
JNI linker flags :
Updating Java configuration in /usr/lib/R
Done.

And indeed there was no include file in my $JAVA_HOME. Very simple remedy:

sudo apt-get install openjdk-8-jre openjdk-8-jdk

(note that this is specifically intended to install the openJDK and not the one from Oracle)

Afterwards all is well:

Java interpreter : /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
Java version     : 1.8.0_191
Java home path   : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java compiler    : /usr/lib/jvm/java-8-openjdk-amd64/jre/../bin/javac
Java headers gen.: /usr/lib/jvm/java-8-openjdk-amd64/jre/../bin/javah
Java archive tool: /usr/lib/jvm/java-8-openjdk-amd64/jre/../bin/jar

trying to compile and link a JNI program
detected JNI cpp flags    : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux
detected JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include/linux     -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c conftest.c -o conftest.o
g++ -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o conftest.so conftest.o -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server -ljvm -L/usr/lib/R/lib -lR


JAVA_HOME        : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java library path: $(JAVA_HOME)/lib/amd64/server
JNI cpp flags    : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux
JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm
Updating Java configuration in /usr/lib/R
Done.

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

How to use a wildcard in the classpath to add multiple jars?

If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.

I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.

It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.

Java error: Only a type can be imported. XYZ resolves to a package

My contribution: I got this error because I created a package named 3lp. However, according to java spec, you are not allowed to name your package starts with a number. I changed it to _3lp, now it works.

How to add multiple jar files in classpath in linux

Step 1.

vi ~/.bashrc

Step 2. Append this line on the last:

export CLASSPATH=$CLASSPATH:/home/abc/lib/*;  (Assuming the jars are stored in /home/abc/lib) 

Step 3.

source ~/.bashrc

After these steps direct complile and run your programs(e.g. javac xyz.java)

Eclipse error "Could not find or load main class"

Check that your project has a builder by either:

  • check project properties (in the "package explorer", right click on the project, select "properties"), there the second section is "Builders", and it should hold the default "Java Builder"
  • or look in the ".project" file (in .../workspace/yourProjectName/.project) the section "buildSpec" should not be empty.

There must be other ways, but what I did was:

  • shut down eclipse
  • edit the ."project" file to add the "buildSpec" section
  • restart eclipse

A proper minimal java ".project" file should look like:

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
        <name>myProjectName</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
                <buildCommand>
                        <name>org.eclipse.jdt.core.javabuilder</name>
                        <arguments>
                        </arguments>
                </buildCommand>
        </buildSpec>
        <natures>       
                    <nature>org.eclipse.jdt.core.javanature</nature>
        </natures>      
</projectDescription>

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

ClassNotFoundException is a checked exception that occurs when we tell JVM to load a class by its string name using Class.forName() or ClassLoader.findSystemClass() or ClassLoader.loadClass() methods and mentioned class is not found in the classpath.

Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files. For Example, You may have seen this exception when doing the JDBC code to connect to your database i.e.MySQL but your classpath does not have JAR for it.

NoClassDefFoundError error occurs when JVM tries to load a particular class that is the part of your code execution (as part of a normal method call or as part of creating an instance using the new keyword) and that class is not present in your classpath but was present at compile time because in order to execute your program you need to compile it and if you are trying use a class which is not present compiler will raise compilation error.

Below is the brief description

enter image description here

You can read Everything About ClassNotFoundException Vs NoClassDefFoundError for more details.

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

adb is not recognized as internal or external command on windows

You have two ways:

First go to the particular path of Android SDK:

1) Open your command prompt and traverse to the platform-tools directory through it such as

$ cd Frameworks\Android-Sdk\platform-tools

2) Run your adb commands now such as to know that your adb is working properly :

$ adb devices OR adb logcat OR simply adb

Second way is :

1) Right click on your My Computer.

2) Open Environment variables.

3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).

4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.

5) Restart your computer once.

6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.

Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"

How to connect SQLite with Java?

If you are using Netbeans using Maven to add library is easier. I have tried using above solutions but it didn't work.

<dependencies>
    <dependency>
      <groupId>org.xerial</groupId>
      <artifactId>sqlite-jdbc</artifactId>
      <version>3.7.2</version>
    </dependency>
</dependencies>

I have added Maven dependency and java.lang.ClassNotFoundException: org.sqlite.JDBC error gone.

How to really read text file from classpath in Java

This is how I read all lines of a text file on my classpath, using Java 7 NIO:

...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

...

Files.readAllLines(
    Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());

NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.

Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets (these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").

Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8

Eclipse: How to build an executable jar with external jar?

You can do this by writing a manifest for your jar. Have a look at the Class-Path header. Eclipse has an option for choosing your own manifest on export.

The alternative is to add the dependency to the classpath at the time you invoke the application:

win32: java.exe -cp app.jar;dependency.jar foo.MyMainClass
*nix:  java -cp app.jar:dependency.jar foo.MyMainClass

spark submit add multiple jars in classpath

Just use the --jars parameter. Spark will share those jars (comma-separated) with the executors.

What is a classpath and how do I set it?

CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is used by the CMD shell to find the executable programs.

CLASSPATH can be set in one of the following ways:

CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose "System Variables" (for all the users) or "User Variables" (only the currently login user) ? choose "Edit" (if CLASSPATH already exists) or "New" ? Enter "CLASSPATH" as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include the current working directory (denoted by '.') in the CLASSPATH.

To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,

> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

Run a JAR file from the command line and specify classpath

You can do a Runtime.getRuntime.exec(command) to relaunch the jar including classpath with args.

Adding files to java classpath at runtime

The way I have done this is by using my own class loader

URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
DynamicURLClassLoader dynalLoader = new DynamicURLClassLoader(urlClassLoader);

And create the following class:

public class DynamicURLClassLoader extends URLClassLoader {

    public DynamicURLClassLoader(URLClassLoader classLoader) {
        super(classLoader.getURLs());
    }

    @Override
    public void addURL(URL url) {
        super.addURL(url);
    }
}

Works without any reflection

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I was just having the same issue...

To resolve the problem (at least in my case) ensure you have included the lib folder in your bundle classpath:

Manifest-Version: 1.0
... 
Bundle-ClassPath: lib/gson-1.6.jar,
 .
...

Or if you want to include all jar's in the folder:

Bundle-ClassPath: lib/

You will still need to place the jar files on the java build path as shown above. Then your imported jar's should appear in the folder "Referenced Libraries"

Docker-Compose can't connect to Docker Daemon

just try with sudo. It seems like permission issue!

sudo docker-compose -f docker-compose-deps.yml up -d

it worked for me.

Formula to determine brightness of RGB color

I found this code (written in C#) that does an excellent job of calculating the "brightness" of a color. In this scenario, the code is trying to determine whether to put white or black text over the color.

Reading string by char till end of line C/C++

A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes

if (c == '\n')

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);

Android: Force EditText to remove focus?

Remove focus but remain focusable:

editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setFocusable(true);

EditText will lose focus, but can gain it again on a new touch event.

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

How to import data from text file to mysql database

Walkthrough on using MySQL's LOAD DATA command:

  1. Create your table:

    CREATE TABLE foo(myid INT, mymessage VARCHAR(255), mydecimal DECIMAL(8,4));
    
  2. Create your tab delimited file (note there are tabs between the columns):

    1   Heart disease kills     1.2
    2   one out of every two    2.3
    3   people in America.      4.5
    
  3. Use the load data command:

    LOAD DATA LOCAL INFILE '/tmp/foo.txt' 
    INTO TABLE foo COLUMNS TERMINATED BY '\t';
    

    If you get a warning that this command can't be run, then you have to enable the --local-infile=1 parameter described here: How can I correct MySQL Load Error

  4. The rows get inserted:

    Query OK, 3 rows affected (0.00 sec)
    Records: 3  Deleted: 0  Skipped: 0  Warnings: 0
    
  5. Check if it worked:

    mysql> select * from foo;
    +------+----------------------+-----------+
    | myid | mymessage            | mydecimal |
    +------+----------------------+-----------+
    |    1 | Heart disease kills  |    1.2000 |
    |    2 | one out of every two |    2.3000 |
    |    3 | people in America.   |    4.5000 |
    +------+----------------------+-----------+
    3 rows in set (0.00 sec)
    

How to specify which columns to load your text file columns into:

Like this:

LOAD DATA LOCAL INFILE '/tmp/foo.txt' INTO TABLE foo
FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'
(@col1,@col2,@col3) set myid=@col1,mydecimal=@col3;

The file contents get put into variables @col1, @col2, @col3. myid gets column 1, and mydecimal gets column 3. If this were run, it would omit the second row:

mysql> select * from foo;
+------+-----------+-----------+
| myid | mymessage | mydecimal |
+------+-----------+-----------+
|    1 | NULL      |    1.2000 |
|    2 | NULL      |    2.3000 |
|    3 | NULL      |    4.5000 |
+------+-----------+-----------+
3 rows in set (0.00 sec)

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Using custom exception class you can return different HTTP status code and dto object.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new UserNotFoundException("A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

Exception class

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {

        super(message);
    }
}

How to fix "could not find a base address that matches schema http"... in WCF

Confirmed my fix:

In your web.config file you should configure it to look as such:

<system.serviceModel >
    <serviceHostingEnvironment configSource=".\Configurations\ServiceHosting.config" />
    ...

Then, build a folder structure that looks like this:

/web.config
/Configurations/ServiceHosting.config
/Configurations/Deploy/ServiceHosting.config

The base serviceHosting.config should look like this:

<?xml version="1.0"?>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
    <baseAddressPrefixFilters>
    </baseAddressPrefixFilters>
</serviceHostingEnvironment>

while the one in /Deploy looks like this:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
    <baseAddressPrefixFilters>
        <add prefix="http://myappname.web707.discountasp.net"/>
    </baseAddressPrefixFilters>
</serviceHostingEnvironment>

Beyond this, you need to add a manual or automated deployment step to copy the file from /Deploy overtop the one in /Configurations. This works incredibly well for service address and connection strings, and saves effort doing other workarounds.

If you don't like this approach (which scales well to farms, but is weaker on single machine), you might consider adding a web.config file a level up from the service deployment on the host's machine and put the serviceHostingEnvironment node there. It should cascade for you.

Accessing localhost of PC from USB connected Android mobile device

Hello you can access your xampp localhost by

  1. Control panel -->
  2. windows defender firewall -->
  3. Advance setting (on left side) --> Inbound Rules --> New Rule --> Port --> in specific local port write your Apache ports --> next --> next then you can access your localhost by using local PC IP address:

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

simple HTTP server in Java using only Java SE API

It's possible to create an httpserver that provides basic support for J2EE servlets with just the JDK and the servlet api in a just a few lines of code.

I've found this very useful for unit testing servlets, as it starts much faster than other lightweight containers (we use jetty for production).

Most very lightweight httpservers do not provide support for servlets, but we need them, so I thought I'd share.

The below example provides basic servlet support, or throws and UnsupportedOperationException for stuff not yet implemented. It uses the com.sun.net.httpserver.HttpServer for basic http support.

import java.io.*;
import java.lang.reflect.*;
import java.net.InetSocketAddress;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

@SuppressWarnings("deprecation")
public class VerySimpleServletHttpServer {
    HttpServer server;
    private String contextPath;
    private HttpHandler httpHandler;

    public VerySimpleServletHttpServer(String contextPath, HttpServlet servlet) {
        this.contextPath = contextPath;
        httpHandler = new HttpHandlerWithServletSupport(servlet);
    }

    public void start(int port) throws IOException {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
        server = HttpServer.create(inetSocketAddress, 0);
        server.createContext(contextPath, httpHandler);
        server.setExecutor(null);
        server.start();
    }

    public void stop(int secondsDelay) {
        server.stop(secondsDelay);
    }

    public int getServerPort() {
        return server.getAddress().getPort();
    }

}

final class HttpHandlerWithServletSupport implements HttpHandler {

    private HttpServlet servlet;

    private final class RequestWrapper extends HttpServletRequestWrapper {
        private final HttpExchange ex;
        private final Map<String, String[]> postData;
        private final ServletInputStream is;
        private final Map<String, Object> attributes = new HashMap<>();

        private RequestWrapper(HttpServletRequest request, HttpExchange ex, Map<String, String[]> postData, ServletInputStream is) {
            super(request);
            this.ex = ex;
            this.postData = postData;
            this.is = is;
        }

        @Override
        public String getHeader(String name) {
            return ex.getRequestHeaders().getFirst(name);
        }

        @Override
        public Enumeration<String> getHeaders(String name) {
            return new Vector<String>(ex.getRequestHeaders().get(name)).elements();
        }

        @Override
        public Enumeration<String> getHeaderNames() {
            return new Vector<String>(ex.getRequestHeaders().keySet()).elements();
        }

        @Override
        public Object getAttribute(String name) {
            return attributes.get(name);
        }

        @Override
        public void setAttribute(String name, Object o) {
            this.attributes.put(name, o);
        }

        @Override
        public Enumeration<String> getAttributeNames() {
            return new Vector<String>(attributes.keySet()).elements();
        }

        @Override
        public String getMethod() {
            return ex.getRequestMethod();
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            return is;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(getInputStream()));
        }

        @Override
        public String getPathInfo() {
            return ex.getRequestURI().getPath();
        }

        @Override
        public String getParameter(String name) {
            String[] arr = postData.get(name);
            return arr != null ? (arr.length > 1 ? Arrays.toString(arr) : arr[0]) : null;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            return postData;
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return new Vector<String>(postData.keySet()).elements();
        }
    }

    private final class ResponseWrapper extends HttpServletResponseWrapper {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final ServletOutputStream servletOutputStream = new ServletOutputStream() {

            @Override
            public void write(int b) throws IOException {
                outputStream.write(b);
            }
        };

        private final HttpExchange ex;
        private final PrintWriter printWriter;
        private int status = HttpServletResponse.SC_OK;

        private ResponseWrapper(HttpServletResponse response, HttpExchange ex) {
            super(response);
            this.ex = ex;
            printWriter = new PrintWriter(servletOutputStream);
        }

        @Override
        public void setContentType(String type) {
            ex.getResponseHeaders().add("Content-Type", type);
        }

        @Override
        public void setHeader(String name, String value) {
            ex.getResponseHeaders().add(name, value);
        }

        @Override
        public javax.servlet.ServletOutputStream getOutputStream() throws IOException {
            return servletOutputStream;
        }

        @Override
        public void setContentLength(int len) {
            ex.getResponseHeaders().add("Content-Length", len + "");
        }

        @Override
        public void setStatus(int status) {
            this.status = status;
        }

        @Override
        public void sendError(int sc, String msg) throws IOException {
            this.status = sc;
            if (msg != null) {
                printWriter.write(msg);
            }
        }

        @Override
        public void sendError(int sc) throws IOException {
            sendError(sc, null);
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            return printWriter;
        }

        public void complete() throws IOException {
            try {
                printWriter.flush();
                ex.sendResponseHeaders(status, outputStream.size());
                if (outputStream.size() > 0) {
                    ex.getResponseBody().write(outputStream.toByteArray());
                }
                ex.getResponseBody().flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                ex.close();
            }
        }
    }

    public HttpHandlerWithServletSupport(HttpServlet servlet) {
        this.servlet = servlet;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void handle(final HttpExchange ex) throws IOException {
        byte[] inBytes = getBytes(ex.getRequestBody());
        ex.getRequestBody().close();
        final ByteArrayInputStream newInput = new ByteArrayInputStream(inBytes);
        final ServletInputStream is = new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return newInput.read();
            }
        };

        Map<String, String[]> parsePostData = new HashMap<>();

        try {
            parsePostData.putAll(HttpUtils.parseQueryString(ex.getRequestURI().getQuery()));

            // check if any postdata to parse
            parsePostData.putAll(HttpUtils.parsePostData(inBytes.length, is));
        } catch (IllegalArgumentException e) {
            // no postData - just reset inputstream
            newInput.reset();
        }
        final Map<String, String[]> postData = parsePostData;

        RequestWrapper req = new RequestWrapper(createUnimplementAdapter(HttpServletRequest.class), ex, postData, is);

        ResponseWrapper resp = new ResponseWrapper(createUnimplementAdapter(HttpServletResponse.class), ex);

        try {
            servlet.service(req, resp);
            resp.complete();
        } catch (ServletException e) {
            throw new IOException(e);
        }
    }

    private static byte[] getBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        while (true) {
            int r = in.read(buffer);
            if (r == -1)
                break;
            out.write(buffer, 0, r);
        }
        return out.toByteArray();
    }

    @SuppressWarnings("unchecked")
    private static <T> T createUnimplementAdapter(Class<T> httpServletApi) {
        class UnimplementedHandler implements InvocationHandler {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                throw new UnsupportedOperationException("Not implemented: " + method + ", args=" + Arrays.toString(args));
            }
        }

        return (T) Proxy.newProxyInstance(UnimplementedHandler.class.getClassLoader(),
                new Class<?>[] { httpServletApi },
                new UnimplementedHandler());
    }
}

TypeError: '<=' not supported between instances of 'str' and 'int'

Change

vote = input('Enter the name of the player you wish to vote for')

to

vote = int(input('Enter the name of the player you wish to vote for'))

You are getting the input from the console as a string, so you must cast that input string to an int object in order to do numerical operations.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

How do I validate a date in this format (yyyy-mm-dd) using jquery?

try this Here is working Demo:

$(function() {
    $('#btnSubmit').bind('click', function(){
        var txtVal =  $('#txtDate').val();
        if(isDate(txtVal))
            alert('Valid Date');
        else
            alert('Invalid Date');
    });

function isDate(txtDate)
{
    var currVal = txtDate;
    if(currVal == '')
        return false;

    var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) 
        return false;

    //Checks for mm/dd/yyyy format.
    dtMonth = dtArray[3];
    dtDay= dtArray[5];
    dtYear = dtArray[1];        

    if (dtMonth < 1 || dtMonth > 12) 
        return false;
    else if (dtDay < 1 || dtDay> 31) 
        return false;
    else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
        return false;
    else if (dtMonth == 2) 
    {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                return false;
    }
    return true;
}

});

changed regex is:

var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex

Creating a Zoom Effect on an image on hover using CSS?

I like using a background image. I find it easier and more flexible:

DEMO

CSS:

#menu {
    max-width: 1200px;
    text-align: center;
    margin: auto;
}
.zoomimg {
    display: inline-block;
    width: 250px;
    height: 375px;
    padding: 0px 5px 0px 5px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center center;
    transition: all .5s ease;
}
.zoomimg:hover {
    cursor: pointer;
    background-size: 150% 150%;
}
.blog {
    background-image: url(http://s18.postimg.org/il7hbk7i1/image.png);
}
.music {
    background-image: url(http://s18.postimg.org/4st2fxgqh/image.png);
}
.projects {
    background-image: url(http://s18.postimg.org/sxtrxn115/image.png);
}
.bio {
    background-image: url(http://s18.postimg.org/5xn4lb37d/image.png);
}

HTML:

<div id="menu">
    <div class="blog zoomimg"></div>
    <div class="music zoomimg"></div>
    <div class="projects zoomimg"></div>
    <div class="bio zoomimg"></div>
</div>

DEMO 2 with Overlay

An array of List in c#

use

List<int>[] a = new List<int>[100];

Is it possible to change the content HTML5 alert messages?

You can use customValidity

$(function(){     var elements = document.getElementsByTagName("input");     for (var i = 0; i < elements.length; i++) {         elements[i].oninvalid = function(e) {             e.target.setCustomValidity("This can't be left blank!");         };     } }); 

I think that will work on at least Chrome and FF, I'm not sure about other browsers

How to set the color of an icon in Angular Material?

Or simply

add to your element

[ngStyle]="{'color': myVariableColor}"

eg

<mat-icon [ngStyle]="{'color': myVariableColor}">{{ getActivityIcon() }}</mat-icon>

Where color can be defined at another component etc

After installing SQL Server 2014 Express can't find local db

Just download and install LocalDB 64BIT\SqlLocalDB.msi can also solve this problem. You don't really need to uninstall and reinstall SQL Server 2014 Express with Advanced Services.

Get the current year in JavaScript

// Return today's date and time
var currentTime = new Date()

// returns the month (from 0 to 11)
var month = currentTime.getMonth() + 1

// returns the day of the month (from 1 to 31)
var day = currentTime.getDate()

// returns the year (four digits)
var year = currentTime.getFullYear()

// write output MM/dd/yyyy
document.write(month + "/" + day + "/" + year)

Plotting time-series with Date labels on x-axis

1) Since the times are dates be sure to use "Date" class, not "POSIXct" or "POSIXlt". See R News 4/1 for advice and try this where Lines is defined in the Note at the end. No packages are used here.

dm <- read.table(text = Lines, header = TRUE)
dm$Date <- as.Date(dm$Date, "%m/%d/%Y")
plot(Visits ~ Date, dm, xaxt = "n", type = "l")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)

The use of text = Lines is just to keep the example self-contained and in reality it would be replaced with something like "myfile.dat" . (continued after image)

screenshot

2) Since this is a time series you may wish to use a time series representation giving slightly simpler code:

library(zoo)

z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")
plot(z, xaxt = "n")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)

Depending on what you want the plot to look like it may be sufficient just to use plot(Visits ~ Date, dm) in the first case or plot(z) in the second case suppressing the axis command entirely. It could also be done using xyplot.zoo

library(lattice)
xyplot(z)

or autoplot.zoo:

library(ggplot2)
autoplot(z)

Note:

Lines <- "Date            Visits
11/1/2010   696537
11/2/2010   718748
11/3/2010   799355
11/4/2010   805800
11/5/2010   701262
11/6/2010   531579
11/7/2010   690068
11/8/2010   756947
11/9/2010   718757
11/10/2010  701768
11/11/2010  820113
11/12/2010  645259"

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

This occurred when trying to connect to the WCF Service using only host name e.g. https://host/MyService.svc while using a certificate tied to a name e.g. host.mysite.com.

Switching to the https://host.mysite.com/MyService.svc and this resolved it.

How to add `style=display:"block"` to an element using jQuery?

There are multiple function to do this work that wrote in bottom based on priority.

Set one or more CSS properties for the set of matched elements.

$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
  display: "block",
  color: "red",
  ...
})

Display the matched elements and is roughly equivalent to calling .css("display", "block")

You can display element using .show() instead

$("div").show()

Set one or more attributes for the set of matched elements.

If target element hasn't style attribute, you can use this method to add inline style to element.

$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")

  • JavaScript

You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.

var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

I ran into this when checking on a null or empty string

if (x == NULL || x == '') {

changed it to

if (is.null(x) || x == '') {

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

How do I make XAML DataGridColumns fill the entire DataGrid?

If you use Width="*" the column will fill to expand the available space.

If you want all columns to divide the grid equally apply this to all columns. If you just want one to fill the remaining space just apply it to that column with the rest being "Auto" or a specific width.

You can also use Width="0.25*" (for example) if you want the column to take up 1/4 of the available width.

Why XML-Serializable class need a parameterless constructor

The answer is: for no good reason whatsoever.

Contrary to its name, the XmlSerializer class is used not only for serialization, but also for deserialization. It performs certain checks on your class to make sure that it will work, and some of those checks are only pertinent to deserialization, but it performs them all anyway, because it does not know what you intend to do later on.

The check that your class fails to pass is one of the checks that are only pertinent to deserialization. Here is what happens:

  • During deserialization, the XmlSerializer class will need to create instances of your type.

  • In order to create an instance of a type, a constructor of that type needs to be invoked.

  • If you did not declare a constructor, the compiler has already supplied a default parameterless constructor, but if you did declare a constructor, then that's the only constructor available.

  • So, if the constructor that you declared accepts parameters, then the only way to instantiate your class is by invoking that constructor which accepts parameters.

  • However, XmlSerializer is not capable of invoking any constructor except a parameterless constructor, because it does not know what parameters to pass to constructors that accept parameters. So, it checks to see if your class has a parameterless constructor, and since it does not, it fails.

So, if the XmlSerializer class had been written in such a way as to only perform the checks pertinent to serialization, then your class would pass, because there is absolutely nothing about serialization that makes it necessary to have a parameterless constructor.

As others have already pointed out, the quick solution to your problem is to simply add a parameterless constructor. Unfortunately, it is also a dirty solution, because it means that you cannot have any readonly members initialized from constructor parameters.

In addition to all this, the XmlSerializer class could have been written in such a way as to allow even deserialization of classes without parameterless constructors. All it would take would be to make use of "The Factory Method Design Pattern" (Wikipedia). From the looks of it, Microsoft decided that this design pattern is far too advanced for DotNet programmers, who apparently should not be unnecessarily confused with such things. So, DotNet programmers should better stick to parameterless constructors, according to Microsoft.

True/False vs 0/1 in MySQL

Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.

This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.

This doesn't affect the database at all, since it's implemented in the application.

There is not really a BOOLEAN type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.

If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.

You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.

How to check compiler log in sql developer?

I can also use

show errors;

In sql worksheet.

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

Create two threads, one display odd & other even numbers

Nos will be printed in sequence

Main class
===========
package com.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class StartThread {
    static AtomicInteger no = new AtomicInteger(1);
    public static void main(String[] args) {
        Odd oddObj = new Odd();
        Thread odd = new Thread(oddObj);
        Thread even = new Thread(new Even(oddObj));
        odd.start();
        even.start();
    }
}

Odd Thread
===========
package com.thread;

public class Odd implements Runnable {

    @Override
    public void run() {
        while (StartThread.no.get() < 20) {
            synchronized (this) {
                System.out.println("Odd=>" + StartThread.no.get());
                StartThread.no.incrementAndGet();

                try {
                    this.notify();
                    if(StartThread.no.get() == 20)
                        break;
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

Even Thread
===========
package com.thread;

public class Even implements Runnable {
    Odd odd;

    public Even(Odd odd) {
        this.odd = odd;
    }

    @Override
    public void run() {
        while (StartThread.no.get() < 20) {
            synchronized (odd) {
                System.out.println("Even=>" + StartThread.no.get());
                StartThread.no.incrementAndGet();
                odd.notifyAll();
                try {
                    odd.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }       

    }

}

Output (Nos are printed in sequential)
======
Odd=>1
Even=>2
Odd=>3
Even=>4
Odd=>5
Even=>6
Odd=>7
Even=>8
Odd=>9
Even=>10
Odd=>11
Even=>12
Odd=>13
Even=>14
Odd=>15
Even=>16
Odd=>17
Even=>18
Odd=>19

How do you automatically set text box to Uppercase?

Using CSS text-transform: uppercase does not change the actual input but only changes its look. If you send the input data to a server it is still going to lowercase or however you entered it. To actually transform the input value you need to add javascript code as below:

_x000D_
_x000D_
document.querySelector("input").addEventListener("input", function(event) {_x000D_
  event.target.value = event.target.value.toLocaleUpperCase()_x000D_
})
_x000D_
<input>
_x000D_
_x000D_
_x000D_

Here I am using toLocaleUpperCase() to convert input value to uppercase. It works fine until you need to edit what you had entered, e.g. if you had entered ABCXYZ and now you try to change it to ABCLMNXYZ, it will become ABCLXYZMN because after every input the cursor jumps to the end.

To overcome this jumping of the cursor, we have to make following changes in our function:

_x000D_
_x000D_
document.querySelector("input").addEventListener("input", function(event) {_x000D_
  var input = event.target;_x000D_
  var start = input.selectionStart;_x000D_
  var end = input.selectionEnd;_x000D_
  input.value = input.value.toLocaleUpperCase();_x000D_
  input.setSelectionRange(start, end);_x000D_
})
_x000D_
<input>
_x000D_
_x000D_
_x000D_

Now everything works as expected, but if you have slow PC you may see text jumping from lowercase to uppercase as you type. If this annoys you, this is the time to use CSS, apply input: {text-transform: uppercase;} to CSS file and everything will be fine.

How to get the query string by javascript?

You need to simple use following function.

function GetQueryStringByParameter(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

--- How to Use ---

var QueryString= GetQueryStringByParameter('QueryString');

How do you get/set media volume (not ringtone volume) in Android?

If you happen to have a volume bar that you want to adjust –similar to what you see on iPhone's iPod app– here's how.

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        //Raise the Volume Bar on the Screen
        volumeControl.setProgress( audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_RAISE);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        //Adjust the Volume
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        //Lower the VOlume Bar on the Screen
        volumeControl.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_LOWER);
        return true;
    default:
        return false;
    }

Python Create unix timestamp five minutes in the future

Just found this, and its even shorter.

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

How to make --no-ri --no-rdoc the default for gem install?

On Windows XP the path to the .gemrc file is

c:\Documents and Settings\All Users\Application Data\gemrc 

and this file is not created by default, you should create it yourself.

Convert UTC/GMT time to local time

TimeZone.CurrentTimeZone.ToLocalTime(date);

How do I alias commands in git?

You can also chain commands if you use the '!' operator to spawn a shell:

aa = !git add -A && git status

This will both add all files and give you a status report with $ git aa.

For a handy way to check your aliases, add this alias:

alias = config --get-regexp ^alias\\.

Then a quick $ git alias gives you your current aliases and what they do.

TypeError: 'NoneType' object is not iterable in Python

It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can't be iterable as a list, as you are trying to do.

Using the slash character in Git branch name

Are you sure branch labs does not already exist (as in this thread)?

You can't have both a file, and a directory with the same name.

You're trying to get git to do basically this:

% cd .git/refs/heads
% ls -l
total 0
-rw-rw-r-- 1 jhe jhe 41 2009-11-14 23:51 labs
-rw-rw-r-- 1 jhe jhe 41 2009-11-14 23:51 master
% mkdir labs
mkdir: cannot create directory 'labs': File exists

You're getting the equivalent of the "cannot create directory" error.
When you have a branch with slashes in it, it gets stored as a directory hierarchy under .git/refs/heads.

How to copy an object by value, not by reference

You may use clone() which works well if your object has immutable objects and/or primitives, but it may be a little problematic when you don't have these ( such as collections ) for which you may need to perform a deep clone.

User userCopy = (User) user.clone();//make a copy

for(...) {
    user.age = 1;
    user.id = -1;

    UserDao.update(user)
    user = userCopy; 
}

It seems like you just want to preserve the attributes: age and id which are of type int so, why don't you give it a try and see if it works.

For more complex scenarios you could create a "copy" method:

publc class User { 
    public static User copy( User other ) {
         User newUser = new User();
         newUser.age = other.age;
         newUser.id = other.id;
         //... etc. 
         return newUser;
    }
}

It should take you about 10 minutes.

And then you can use that instead:

     User userCopy = User.copy( user ); //make a copy
     // etc. 

To read more about clone read this chapter in Joshua Bloch "Effective Java: Override clone judiciously"

PHP, getting variable from another php-file

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test';

mysecondfile.php

$var = 'tester';

test.php

include 'myfile.php';
echo $var;

include 'mysecondfile.php';
echo $var;

Output:

test

tester

I suggest using different variable names.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

How do I revert my changes to a git submodule?

my way to reset all submodules (WITHOUT detaching & keeping their "master" branch):

git submodule foreach 'git checkout master && git reset --hard $sha1'

Convert string to Date in java

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";

try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

} catch (ParseException e) {
    e.printStackTrace();
}

Output:

2014/08/06 16:06:54
2014/08/06 16:06:54

Best Way to do Columns in HTML/CSS

You should probably consider using css3 for this though it does include the use of vendor prefixes.

I've knocked up a quick fiddle to demo but the crux is this.

<style>
.3col
{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count:3;
    column-gap:10px;
}
</style>
<div class="3col">
<p>col1</p>
<p>col2</p>
<p>col3</p>
</div>

Django 1.7 - makemigrations not detecting changes

Make sure your model is not abstract. I actually made that mistake and it took a while, so I thought I'd post it.

How to send email from Terminal?

If all you need is a subject line (as in an alert message) simply do:

mailx -s "This is all she wrote" < /dev/null "myself@myaddress"

Check if a variable exists in a list in Bash

Prior answers don't use tr which I found to be useful with grep. Assuming that the items in the list are space delimited, to check for an exact match:

echo $mylist | tr ' ' '\n' | grep -F -x -q "$myitem"

This will return exit code 0 if the item is in the list, or exit code 1 if it isn't.

It's best to use it as a function:

_contains () {  # Check if space-separated list $1 contains line $2
  echo "$1" | tr ' ' '\n' | grep -F -x -q "$2"
}

mylist="aa bb cc"

# Positive check
if _contains "${mylist}" "${myitem}"; then
  echo "in list"
fi

# Negative check
if ! _contains "${mylist}" "${myitem}"; then
  echo "not in list"
fi

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

How do I convert a String to a BigInteger?

If you may want to convert plaintext (not just numbers) to a BigInteger you will run into an exception, if you just try to: new BigInteger("not a Number")

In this case you could do it like this way:

public  BigInteger stringToBigInteger(String string){
    byte[] asciiCharacters = string.getBytes(StandardCharsets.US_ASCII);
    StringBuilder asciiString = new StringBuilder();
    for(byte asciiCharacter:asciiCharacters){
        asciiString.append(Byte.toString(asciiCharacter));
    }
    BigInteger bigInteger = new BigInteger(asciiString.toString());
    return bigInteger;
}

React JS get current date

Your problem is that you are naming your component class Date. When you call new Date() within your class, it won't create an instance of the Date you expect it to create (which is likely this Date)- it will try to create an instance of your component class. Then the constructor will try to create another instance, and another instance, and another instance... Until you run out of stack space and get the error you're seeing.

If you want to use Date within your class, try naming your class something different such as Calendar or DateComponent.

The reason for this is how JavaScript deals with name scope: Whenever you create a new named entity, if there is already an entity with that name in scope, that name will stop referring to the previous entity and start referring to your new entity. So if you use the name Date within a class named Date, the name Date will refer to that class and not to any object named Date which existed before the class definition started.

How to parse the AndroidManifest.xml file inside an .apk package

Use android-apktool

There is an application that reads apk files and decodes XMLs to nearly original form.

Usage:

apktool d Gmail.apk && cat Gmail/AndroidManifest.xml

Check android-apktool for more information

Running Selenium Webdriver with a proxy in Python

If anyone is looking for a solution here's how :

from selenium import webdriver
PROXY = "YOUR_PROXY_ADDRESS_HERE"
webdriver.DesiredCapabilities.FIREFOX['proxy']={
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "autodetect":False
}
driver = webdriver.Firefox()
driver.get('http://www.whatsmyip.org/')

How to jump to top of browser page

You can set the scrollTop, like this:

$('html,body').scrollTop(0);

Or if you want a little animation instead of a snap to the top:

$('html, body').animate({ scrollTop: 0 }, 'fast');

What does ':' (colon) do in JavaScript?

One stupid mistake I did awhile ago that might help some people.

Keep in mind that if you are using ":" in an event like this, the value will not change

var ondrag = (function(event, ui) {
            ...

            nub0x: event.target.offsetLeft + event.target.clientWidth/2;
            nub0y = event.target.offsetTop + event.target.clientHeight/2;

            ...
        });

So "nub0x" will initialize with the first event that happens and will never change its value. But "nub0y" will change during the next events.

Android: keeping a background service alive (preventing process death)

When you bind your Service to Activity with BIND_AUTO_CREATE your service is being killed just after your Activity is Destroyed and unbound. It does not depend on how you've implemented your Services unBind method it will be still killed.

The other way is to start your Service with startService method from your Activity. This way even if your Activity is destroyed your service won't be destroyed or even paused but you have to pause/destroy it by yourself with stopSelf/stopService when appropriate.

Interface vs Abstract Class (general OO)

The interviewers are barking up an odd tree. For languages like C# and Java, there is a difference, but in other languages like C++ there is not. OO theory doesn't differentiate the two, merely the syntax of language.

An abstract class is a class with both implementation and interface (pure virtual methods) that will be inherited. Interfaces generally do not have any implementation but only pure virtual functions.

In C# or Java an abstract class without any implementation differs from an interface only in the syntax used to inherit from it and the fact you can only inherit from one.

How to run a script file remotely using SSH

I was able to invoke a shell script using this command:

ssh ${serverhost} "./sh/checkScript.ksh"

Of course, checkScript.ksh must exist in the $HOME/sh directory.

Setting Oracle 11g Session Timeout

This is likely caused by your application's connection pool; not an Oracle DBMS issue. Most connection pools have a validate statement that can execute before giving you the connection. In oracle you would want "Select 1 from dual".

The reason it started occurring after you restarted the server is that the connection pool was probably added without a restart and you are just now experiencing the use of the connection pool for the first time. What is the modification dates on your resource files that deal with database connections?

Validate Query example:

 <Resource name="jdbc/EmployeeDB" auth="Container" 
            validationQuery="Select 1 from dual" type="javax.sql.DataSource" username="dbusername" password="dbpassword"
            driverClassName="org.hsql.jdbcDriver" url="jdbc:HypersonicSQL:database"
            maxActive="8" maxIdle="4"/>

EDIT: In the case of Grails, there are similar configuration options for the grails pool. Example for Grails 1.2 (see release notes for Grails 1.2)

dataSource {
    pooled = true
    dbCreate = "update"
    url = "jdbc:mysql://localhost/yourDB"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "yourUser"
    password = "yourPassword"
    properties {
        maxActive = 50
        maxIdle = 25
        minIdle = 5
        initialSize = 5
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        maxWait = 10000     
    }   
}

Favicon dimensions?

Seems like your file should be .ico type.

Check this post about favicons:

http://www.html-kit.com/support/favicon/image-size/

Why doesn't JavaScript have a last method?

Because Javascript changes very slowly. And that's because people upgrade browsers slowly.

Many Javascript libraries implement their own last() function. Use one!

explicit casting from super class to subclass

Because theoretically Animal animal can be a dog:

Animal animal = new Dog();

Generally, downcasting is not a good idea. You should avoid it. If you use it, you better include a check:

if (animal instanceof Dog) {
    Dog dog = (Dog) animal;
}

How to get an absolute file path in Python

Today you can also use the unipath package which was based on path.py: http://sluggo.scrapping.cc/python/unipath/

>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>

I would recommend using this package as it offers a clean interface to common os.path utilities.

What is the command for cut copy paste a file from one directory to other directory

mv in unix-ish systems, move in dos/windows.

e.g.

C:\> move c:\users\you\somefile.txt   c:\temp\newlocation.txt

and

$ mv /home/you/somefile.txt /tmp/newlocation.txt

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

How can I access the MySQL command line with XAMPP for Windows?

You can access the MySQL command line with XAMPP for Windows

enter image description here

  1. click XAMPP icon to launch its cPanel

  2. click on Shell button

  3. Type this mysql -h localhost -u root and click enter

You should see all the command lines and what they do

Setting environment for using XAMPP for Windows.
Your PC c:\xampp

# mysql -h localhost - root

mysql  Ver 15.1 Distrib 10.1.19-MariaDB, for Win32 (AMD64)
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Usage: mysql [OPTIONS] [database]

Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf C:\xampp\mysql\my.ini C:\xampp\mysql\my.cnf C:\xampp\mysql\bin\my.ini C:\xampp\mysql\bin\my.cnf
The following groups are read: mysql client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.

  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --abort-source-on-error
Abort 'source filename' operations in case of errors
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash
                      No automatic rehashing. One has to use 'rehash' to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.
  --auto-vertical-output
                      Automatically switch to vertical output mode if the
                      result is wider than the terminal width.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --character-sets-dir=name
                      Directory for character set files.
  --column-type-info  Display column type information.
  -c, --comments      Preserve comments. Send comments to the server. The
                      default is --skip-comments (discard comments), enable
                      with --comments.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       Check memory and open file usage at exit.
  -T, --debug-info    Print some debug info at exit.
  -D, --database=name Database to use.
  --default-character-set=name
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error. Sets
                      abort-source-on-error to 0
  -G, --named-commands
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  -i, --ignore-spaces Ignore space after function names.
  --init-command=name SQL Command to execute when connecting to MySQL server.
                      Will automatically be re-executed when reconnecting.
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
  -b, --no-beep       Turn off beep on error.
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
  --column-names      Write column names in results.
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names
                      Don't write column names in results.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
  -o, --one-database  Ignore statements except those that occur while the
                      default database is the one named at the command line.
  -p, --password[=name]
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -W, --pipe          Use named pipes to connect to server.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --progress-reports  Get progress reports for long running commands (like
                      ALTER TABLE)
                      (Defaults to on; use --skip-progress-reports to disable.)
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -q, --quick         Don't cache result, print it row by row. This may slow
                      down the server if the output is suspended. Doesn't use
                      history file.
  -r, --raw           Write fields without conversion. Used with --batch.
  --reconnect         Reconnect if the connection is lost. Disable with
                      --disable-reconnect. This option is enabled by default.
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
                      each row on new line.
  --shared-memory-base-name=name
                      Base name of shared memory.
  -S, --socket=name   The socket file to use for connection.
  --ssl               Enable SSL for connection (automatically enabled with
                      other flags).
  --ssl-ca=name       CA file in PEM format (check OpenSSL docs, implies
                      --ssl).
  --ssl-capath=name   CA directory (check OpenSSL docs, implies --ssl).
  --ssl-cert=name     X509 cert in PEM format (implies --ssl).
  --ssl-cipher=name   SSL cipher to use (implies --ssl).
  --ssl-key=name      X509 key in PEM format (implies --ssl).
  --ssl-crl=name      Certificate revocation list (implies --ssl).
  --ssl-crlpath=name  Certificate revocation list path (implies --ssl).
  --ssl-verify-server-cert
                      Verify server's "Common Name" in its cert against
                      hostname used when connecting. This option is disabled by
                      default.
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  -u, --user=name     User for login if not current user.
  -U, --safe-updates  Only allow UPDATE and DELETE that uses keys.
  -U, --i-am-a-dummy  Synonym for option --safe-updates, -U.
  -v, --verbose       Write more. (-v -v -v gives the table output format).
  -V, --version       Output version information and exit.
  -w, --wait          Wait and retry if connection is down.
  --connect-timeout=# Number of seconds before connection timeout.
  --max-allowed-packet=#
                      The maximum packet length to send to or receive from
                      server.
  --net-buffer-length=#
                      The buffer size for TCP/IP and socket communication.
  --select-limit=#    Automatic limit for SELECT when using --safe-updates.
  --max-join-size=#   Automatic limit for rows in a join when using
                      --safe-updates.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol.
  --server-arg=name   Send embedded server this as a parameter.
  --show-warnings     Show warnings after every statement.
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
                      translated to '\n'. This switch turns off both features,
                      and also turns off parsing of all clientcommands except
                      \C and DELIMITER, in non-interactive mode (for input
                      piped to mysql or loaded using the 'source' command).
                      This is necessary when processing output from mysqlbinlog
                      that may contain blobs.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
abort-source-on-error             FALSE
auto-rehash                       FALSE
auto-vertical-output              FALSE
character-sets-dir                (No default value)
column-type-info                  FALSE
comments                          FALSE
compress                          FALSE
debug-check                       FALSE
debug-info                        FALSE
database                          (No default value)
default-character-set             auto
delimiter                         ;
vertical                          FALSE
force                             FALSE
named-commands                    FALSE
ignore-spaces                     FALSE
init-command                      (No default value)
local-infile                      FALSE
no-beep                           FALSE
host                              localhost
html                              FALSE
xml                               FALSE
line-numbers                      TRUE
unbuffered                        FALSE
column-names                      TRUE
sigint-ignore                     FALSE
port                              3306
progress-reports                  TRUE
prompt                            \N [\d]>
quick                             FALSE
raw                               FALSE
reconnect                         TRUE
shared-memory-base-name           (No default value)
socket                            C:/xampp/mysql/mysql.sock
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
ssl-verify-server-cert            FALSE
table                             FALSE
user                              (No default value)
safe-updates                      FALSE
i-am-a-dummy                      FALSE
connect-timeout                   0
max-allowed-packet                16777216
net-buffer-length                 16384
select-limit                      1000
max-join-size                     1000000
secure-auth                       FALSE
show-warnings                     FALSE
plugin-dir                        (No default value)
default-auth                      (No default value)
binary-mode                       FALSE

Create Word Document using PHP in Linux

There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.

string encoding and decoding?

That's because your input string can’t be converted according to the encoding rules (strict by default).

I don't know, but I always encoded using directly unicode() constructor, at least that's the ways at the official documentation:

unicode(your_str, errors="ignore")

#define macro for debug printing in C?

I use something like this:

#ifdef DEBUG
 #define D if(1) 
#else
 #define D if(0) 
#endif

Than I just use D as a prefix:

D printf("x=%0.3f\n",x);

Compiler sees the debug code, there is no comma problem and it works everywhere. Also it works when printf is not enough, say when you must dump an array or calculate some diagnosing value that is redundant to the program itself.

EDIT: Ok, it might generate a problem when there is else somewhere near that can be intercepted by this injected if. This is a version that goes over it:

#ifdef DEBUG
 #define D 
#else
 #define D for(;0;)
#endif

How to set timer in android?

I think you can do it in Rx way like:

 timerSubscribe = Observable.interval(1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long aLong) {
                      //TODO do your stuff
                }
            });

And cancel this like:

timerSubscribe.unsubscribe();

Rx Timer http://reactivex.io/documentation/operators/timer.html

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

If you downloaded the file from the internet, either separately or inside a .zip file or similar, it may have been "locked" because it is flagged as coming from the internet zone. Many programs will use this as a sign that the content should not be trusted.

The simplest solution is to right-click the file in Windows Explorer, select Properties, and along the bottom of this dialog, you should have an "Unblock" option. Remember to click OK to accept the change.

If you got the file from an archive, it is usually better to unblock the archive first, if the file is flagged as coming from the internet zone, and you unzip it, that flag might propagate to many of the files you just unarchived. If you unblock first, the unarchived files should be fine.

There's also a Powershell command for this, Unblock-File:

> Unblock-File *

Additionally, there are ways to write code that will remove the lock as well.

From the comments by @Defcon1: You can also combine Unblock-File with Get-ChildItem to create a pipeline that unblocks file recursively. Since Unblock-File has no way to find files recursively by itself, you have to use Get-ChildItem to do that part.

> Get-ChildItem -Path '<YOUR-SOLUTION-PATH>' -Recurse | Unblock-File

Installed SSL certificate in certificate store, but it's not in IIS certificate list

If you are using Godaddy certificate, then the issue is that the machine on which the certificate request is created and the machine on which is you are trying to complete the request are different. So do the following:

  1. Use the "generated-private-key.txt" file that was created the godaddy. Use this file to create .pfx certificate(with private key) you can use OpenSSL command:

    openssl pkcs12 -export -out {mydomain}.pfx -inkey generated-private-key.txt -in {your .crt file}

  2. The above command will generate certificate with private key {mydomain}.pfx.

  3. Import this certificate in IIS using "Import" option

Sorting a DropDownList? - C#, ASP.NET

You may not have access to the SQL, but if you have the DataSet or DataTable, you can certainly call the Sort() method.

How to pass a parameter to routerLink that is somewhere inside the URL?

constructor(private activatedRoute: ActivatedRoute) {

this.activatedRoute.queryParams.subscribe(params => {
  console.log(params['type'])
  });  }

This works for me!

How to get an isoformat datetime string including the default timezone?

Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).

>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>

Creating a class object in c++

First of all, both cases calls a constructor. If you write

Example *example = new Example();

then you are creating an object, call the constructor and retrieve a pointer to it.

If you write

Example example;

The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.

As for the singleton question, you must simple invoke your static method by writing:

Example *e = Singleton::getExample();

SQL Column definition : default value and not null redundant?

My SQL teacher said that if you specify both a DEFAULT value and NOT NULLor NULL, DEFAULT should always be expressed before NOT NULL or NULL.

Like this:

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL

How can I detect window size with jQuery?

You could also use plain Javascript window.innerWidth to compare width.

But use jQuery's .resize() fired automatically for you:

$( window ).resize(function() {
  // your code...
}); 

http://api.jquery.com/resize/

How do I make a request using HTTP basic authentication with PHP curl?

If the authorization type is Basic auth and data posted is json then do like this

<?php

$data = array("username" => "test"); // data u want to post                                                                   
$data_string = json_encode($data);                                                                                   
 $api_key = "your_api_key";   
 $password = "xxxxxx";                                                                                                                 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxxxxxxxxxxx");    
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($ch, CURLOPT_POST, true);                                                                   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
    'Accept: application/json',
    'Content-Type: application/json')                                                           
);             

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}                                                                                                      
$errors = curl_error($ch);                                                                                                            
$result = curl_exec($ch);
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);  
echo $returnCode;
var_dump($errors);
print_r(json_decode($result, true));

Cross-platform way of getting temp directory in Python

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

This answer does not address the Debug button (you'd have to design a form and use the buttons on that to do something like the method in your next question). But it does address this part:

now I don't want to lose the comfortableness of the default handler which also point me to the exact line where the error has occured.

First, I'll assume you don't want this in production code - you want it either for debugging or for code you personally will be using. I use a compiler flag to indicate debugging; then if I'm troubleshooting a program, I can easily find the line that's causing the problem.

# Const IsDebug = True

Sub ProcA()
On Error Goto ErrorHandler
' Main code of proc

ExitHere:
    On Error Resume Next
    ' Close objects and stuff here
    Exit Sub

ErrorHandler:
    MsgBox Err.Number & ": " & Err.Description, , ThisWorkbook.Name & ": ProcA"
    #If IsDebug Then
        Stop            ' Used for troubleshooting - Then press F8 to step thru code 
        Resume          ' Resume will take you to the line that errored out
    #Else
        Resume ExitHere ' Exit procedure during normal running
    #End If
End Sub

Note: the exception to Resume is if the error occurs in a sub-procedure without an error handling routine, then Resume will take you to the line in this proc that called the sub-procedure with the error. But you can still step into and through the sub-procedure, using F8 until it errors out again. If the sub-procedure's too long to make even that tedious, then your sub-procedure should probably have its own error handling routine.

There are multiple ways to do this. Sometimes for smaller programs where I know I'm gonna be stepping through it anyway when troubleshooting, I just put these lines right after the MsgBox statement:

    Resume ExitHere         ' Normally exits during production
    Resume                  ' Never will get here
Exit Sub

It will never get to the Resume statement, unless you're stepping through and set it as the next line to be executed, either by dragging the next statement pointer to that line, or by pressing CtrlF9 with the cursor on that line.

Here's an article that expands on these concepts: Five tips for handling errors in VBA. Finally, if you're using VBA and haven't discovered Chip Pearson's awesome site yet, he has a page explaining Error Handling In VBA.

Create Table from View

In SQL SERVER you do it like this:

SELECT *
INTO A
FROM dbo.myView

This will create a new table A with the contents of your view.
See here for more info.

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

Unfinished Stubbing Detected in Mockito

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.

For mocking of void methods try out below:

//Kotlin Syntax

 Mockito.`when`(voidMethodCall())
           .then {
                Unit //Do Nothing
            }

How to move/rename a file using an Ansible task on a remote system

This is the way I got it working for me:

  Tasks:
  - name: checking if the file 1 exists
     stat:      
      path: /path/to/foo abc.xts
     register: stat_result

  - name: moving file 1
    command: mv /path/to/foo abc.xts /tmp
    when: stat_result.stat.exists == True

the playbook above, will check if file abc.xts exists before move the file to tmp folder.

Difference between Activity Context and Application Context

You can see a difference between the two contexts when you launch your app directly from the home screen vs when your app is launched from another app via share intent.

Here a practical example of what "non-standard back stack behaviors", mentioned by @CommonSenseCode, means:

Suppose that you have two apps that communicate with each other, App1 and App2.

Launch App2:MainActivity from launcher. Then from MainActivity launch App2:SecondaryActivity. There, either using activity context or application context, both activities live in the same task and this is ok (given that you use all standard launch modes and intent flags). You can go back to MainActivity with a back press and in the recent apps you have only one task.

Suppose now that you are in App1 and launch App2:MainActivity with a share intent (ACTION_SEND or ACTION_SEND_MULTIPLE). Then from there try to launch App2:SecondaryActivity (always with all standard launch modes and intent flags). What happens is:

  • if you launch App2:SecondaryActivity with application context on Android < 10 you cannot launch all the activities in the same task. I have tried with android 7 and 8 and the SecondaryActivity is always launched in a new task (I guess is because App2:SecondaryActivity is launched with the App2 application context but you're coming from App1 and you didn't launch the App2 application directly. Maybe under the hood android recognize that and use FLAG_ACTIVITY_NEW_TASK). This can be good or bad depending on your needs, for my application was bad.
    On Android 10 the app crashes with the message
    "Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?".
    So to make it work on Android 10 you have to use FALG_ACTIVITY_NEW_TASK and you cannot run all activities in the same task.
    As you can see the behavior is different between android versions, weird.

  • if you launch App2:SecondaryActivity with activity context all goes well and you can run all the activities in the same task resulting in a linear backstack navigation.

I hope I have added some useful information

Unioning two tables with different number of columns

I came here and followed above answer. But mismatch in the Order of data type caused an error. The below description from another answer will come handy.

Are the results above the same as the sequence of columns in your table? because oracle is strict in column orders. this example below produces an error:

create table test1_1790 (
col_a varchar2(30),
col_b number,
col_c date);

create table test2_1790 (
col_a varchar2(30),
col_c date,
col_b number);

select * from test1_1790
union all
select * from test2_1790;

ORA-01790: expression must have same datatype as corresponding expression

As you see the root cause of the error is in the mismatching column ordering that is implied by the use of * as column list specifier. This type of errors can be easily avoided by entering the column list explicitly:

select col_a, col_b, col_c from test1_1790 union all select col_a, col_b, col_c from test2_1790; A more frequent scenario for this error is when you inadvertently swap (or shift) two or more columns in the SELECT list:

select col_a, col_b, col_c from test1_1790
union all
select col_a, col_c, col_b from test2_1790;

OR if the above does not solve your problem, how about creating an ALIAS in the columns like this: (the query is not the same as yours but the point here is how to add alias in the column.)

SELECT id_table_a, 
       desc_table_a, 
       table_b.id_user as iUserID, 
       table_c.field as iField
UNION
SELECT id_table_a, 
       desc_table_a, 
       table_c.id_user as iUserID, 
       table_c.field as iField

Get file name from URI string in C#

this is my sample you can use:

        public static string GetFileNameValidChar(string fileName)
    {
        foreach (var item in System.IO.Path.GetInvalidFileNameChars())
        {
            fileName = fileName.Replace(item.ToString(), "");
        }
        return fileName;
    }

    public static string GetFileNameFromUrl(string url)
    {
        string fileName = "";
        if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
        {
            fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
        }
        string ext = "";
        if (!string.IsNullOrEmpty(fileName))
        {
            ext = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(ext))
                ext = ".html";
            else
                ext = "";
            return GetFileNameValidChar(fileName + ext);

        }

        fileName = Path.GetFileName(url);
        if (string.IsNullOrEmpty(fileName))
        {
            fileName = "noName";
        }
        ext = Path.GetExtension(fileName);
        if (string.IsNullOrEmpty(ext))
            ext = ".html";
        else
            ext = "";
        fileName = fileName + ext;
        if (!fileName.StartsWith("?"))
            fileName = fileName.Split('?').FirstOrDefault();
        fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
        return GetFileNameValidChar(fileName);
    }

Usage:

var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");

How to get the file path from URI?

File myFile = new File(uri.toString());
myFile.getAbsolutePath()

should return u the correct path

EDIT

As @Tron suggested the working code is

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

How to iterate object keys using *ngFor

If you are using a map() operator on your response,you could maybe chain a toArray() operator to it...then you should be able to iterate through newly created array...at least that worked for me :)

How to calculate the bounding box for a given lat/lng location?

Here I have converted Federico A. Ramponi's answer to C# for anybody interested:

public class MapPoint
{
    public double Longitude { get; set; } // In Degrees
    public double Latitude { get; set; } // In Degrees
}

public class BoundingBox
{
    public MapPoint MinPoint { get; set; }
    public MapPoint MaxPoint { get; set; }
}        

// Semi-axes of WGS-84 geoidal reference
private const double WGS84_a = 6378137.0; // Major semiaxis [m]
private const double WGS84_b = 6356752.3; // Minor semiaxis [m]

// 'halfSideInKm' is the half length of the bounding box you want in kilometers.
public static BoundingBox GetBoundingBox(MapPoint point, double halfSideInKm)
{            
    // Bounding box surrounding the point at given coordinates,
    // assuming local approximation of Earth surface as a sphere
    // of radius given by WGS84
    var lat = Deg2rad(point.Latitude);
    var lon = Deg2rad(point.Longitude);
    var halfSide = 1000 * halfSideInKm;

    // Radius of Earth at given latitude
    var radius = WGS84EarthRadius(lat);
    // Radius of the parallel at given latitude
    var pradius = radius * Math.Cos(lat);

    var latMin = lat - halfSide / radius;
    var latMax = lat + halfSide / radius;
    var lonMin = lon - halfSide / pradius;
    var lonMax = lon + halfSide / pradius;

    return new BoundingBox { 
        MinPoint = new MapPoint { Latitude = Rad2deg(latMin), Longitude = Rad2deg(lonMin) },
        MaxPoint = new MapPoint { Latitude = Rad2deg(latMax), Longitude = Rad2deg(lonMax) }
    };            
}

// degrees to radians
private static double Deg2rad(double degrees)
{
    return Math.PI * degrees / 180.0;
}

// radians to degrees
private static double Rad2deg(double radians)
{
    return 180.0 * radians / Math.PI;
}

// Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
private static double WGS84EarthRadius(double lat)
{
    // http://en.wikipedia.org/wiki/Earth_radius
    var An = WGS84_a * WGS84_a * Math.Cos(lat);
    var Bn = WGS84_b * WGS84_b * Math.Sin(lat);
    var Ad = WGS84_a * Math.Cos(lat);
    var Bd = WGS84_b * Math.Sin(lat);
    return Math.Sqrt((An*An + Bn*Bn) / (Ad*Ad + Bd*Bd));
}

Remove All Event Listeners of Specific Type

You must override EventTarget.prototype.addEventListener to build an trap function for logging all 'add listener' calls. Something like this:

var _listeners = [];

EventTarget.prototype.addEventListenerBase = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, listener)
{
    _listeners.push({target: this, type: type, listener: listener});
    this.addEventListenerBase(type, listener);
};

Then you can build an EventTarget.prototype.removeEventListeners:

EventTarget.prototype.removeEventListeners = function(targetType)
{
    for(var index = 0; index != _listeners.length; index++)
    {
        var item = _listeners[index];

        var target = item.target;
        var type = item.type;
        var listener = item.listener;

        if(target == this && type == targetType)
        {
            this.removeEventListener(type, listener);
        }
    }
}

In ES6 you can use a Symbol, to hide the original function and the list of all added listener directly in the instantiated object self.

(function()
{
    let target = EventTarget.prototype;
    let functionName = 'addEventListener';
    let func = target[functionName];

    let symbolHidden = Symbol('hidden');

    function hidden(instance)
    {
        if(instance[symbolHidden] === undefined)
        {
            let area = {};
            instance[symbolHidden] = area;
            return area;
        }

        return instance[symbolHidden];
    }

    function listenersFrom(instance)
    {
        let area = hidden(instance);
        if(!area.listeners) { area.listeners = []; }
        return area.listeners;
    }

    target[functionName] = function(type, listener)
    {
        let listeners = listenersFrom(this);

        listeners.push({ type, listener });

        func.apply(this, [type, listener]);
    };

    target['removeEventListeners'] = function(targetType)
    {
        let self = this;

        let listeners = listenersFrom(this);
        let removed = [];

        listeners.forEach(item =>
        {
            let type = item.type;
            let listener = item.listener;

            if(type == targetType)
            {
                self.removeEventListener(type, listener);
            }
        });
    };
})();

You can test this code with this little snipper:

document.addEventListener("DOMContentLoaded", event => { console.log('event 1'); });
document.addEventListener("DOMContentLoaded", event => { console.log('event 2'); });
document.addEventListener("click", event => { console.log('click event'); });

document.dispatchEvent(new Event('DOMContentLoaded'));
document.removeEventListeners('DOMContentLoaded');
document.dispatchEvent(new Event('DOMContentLoaded'));
// click event still works, just do a click in the browser

Changing the highlight color when selecting text in an HTML text input

I guess this can help :

selection styles

It's possible to define color and background for text the user selects.

Try it below. If you select something and it looks like this, your browser supports selection styles.

This is the paragraph with normal ::selection.

This is the paragraph with ::-moz-selection.

This is the paragraph with ::-webkit-selection.

Testsheet:

p.normal::selection {
  background:#cc0000;
  color:#fff;
}

p.moz::-moz-selection {
  background:#cc0000;
  color:#fff;
}

p.webkit::-webkit-selection {
  background:#cc0000;
  color:#fff;
}

Quoted from Quirksmode

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Split string in C every white space

Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.

int print_words(const char *string, FILE *f)
{
   static const char space_characters[] = " \t";
   const char *next_space;

   // Find the next space in the string
   //
   while ((next_space = strpbrk(string, space_characters)))
   {
      const char *p;

      // If there are non-space characters between what we found
      // and what we started from, print them.
      //
      if (next_space != string)
      {
         for (p=string; p<next_space; p++)
         {
            if(fputc(*p, f) == EOF)
            {
               return -1;
            }
         }

         // Print a newline
         //
         if (fputc('\n', f) == EOF)
         {
            return -1;
         }
      }

      // Advance next_space until we hit a non-space character
      //
      while (*next_space && strchr(space_characters, *next_space))
      {
         next_space++;
      }

      // Advance the string
      //
      string = next_space;
   }

   // Handle the case where there are no spaces left in the string
   //
   if (*string)
   {
      if (fprintf(f, "%s\n", string) < 0)
      {
         return -1;
      }
   }

   return 0;
}

How to get file creation date/time in Bash/Debian?

Another trick to add to your arsenal is the following:

$ grep -r "Copyright" /<path-to-source-files>/src

Generally speaking, if one changes a file they should claim credit in the “Copyright”. Examine the results for dates, file names, contributors and contact email.

example grep result:

/<path>/src/someobject.h: * Copyright 2007-2012 <creator's name> <creator's email>(at)<some URL>>

convert strtotime to date time format in php

Use date() function to get the desired date

<?php
// set default timezone
date_default_timezone_set('UTC');

//define date and time
$strtotime = 1307595105;

// output
echo date('d M Y H:i:s',$strtotime);

// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format
?>

Recommended online tool for strtotime to date conversion:

http://freeonlinetools24.com/

How to restart remote MySQL server running on Ubuntu linux?

  1. SSH into the machine. Using the proper credentials and ip address, ssh [email protected]. This should provide you with shell access to the Ubuntu server.
  2. Restart the mySQL service. sudo service mysql restart should do the job.

If your mySQL service is named something else like mysqld you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart

What is the maximum length of a Push Notification alert text?

It should be 236 bytes. There is no restriction on the size of the alert text as far as I know, but only the total payload size. So considering if the payload is minimal and only contains the alert information, it should look like:

{"aps":{"alert":""}}

That takes up 20 characters (20 bytes), leaving 236 bytes to put inside the alert string. With ASCII that will be 236 characters, and could be lesser with UTF8 and UTF16.

Need to get a string after a "word" in a string in c#

use indexOf() function

string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
  //DO YOUR LOGIC
  string errorCode = s.Substring(index+4);
}

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

What are the differences between the urllib, urllib2, urllib3 and requests module?

To get the content of a url:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

  • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
  • Python3 urllib.urlopen(url) returns an instance
  • Request request.get(url) returns a requests.models.Response

AngularJS : Initialize service with asynchronous data

You can use JSONP to asynchronously load service data. The JSONP request will be made during the initial page load and the results will be available before your application starts. This way you won't have to bloat your routing with redundant resolves.

You html would look like this:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>

function MyService {
  this.getData = function(){
    return   MyService.data;
  }
}
MyService.setData = function(data) {
  MyService.data = data;
}

angular.module('main')
.service('MyService', MyService)

</script>
<script src="/some_data.php?jsonp=MyService.setData"></script>

TypeError: 'int' object is not subscriptable

sumall = summ + sumd + sumy

Your sumall is an integer. If you want the individual characters from it, convert it to a string first.

Moment Js UTC to Local Time

Note: please update the date format accordingly.

Format Date

   __formatDate: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('D-MMM-Y');
   }

Format Time

  __formatTime: function(myDate){
      var ts = moment.utc(myDate);
      return ts.local().format('HH:mm');
  },

What's the best way to test SQL Server connection programmatically?

Look for an open listener on port 1433 (the default port). If you get any response after creating a tcp connection there, the server's probably up.

Running a simple shell script as a cronjob

It should run properly at cron also. Please check below things.

1- You are editing proper file to set cron.

2- You have given proper permission(execute permission) to script mean your script is executable.

How to create a floating action button (FAB) in android, using AppCompat v21?

There is no longer a need for creating your own FAB nor using a third party library, it was included in AppCompat 22.

https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html

Just add the new support library called design in in your gradle-file:

compile 'com.android.support:design:22.2.0'

...and you are good to go:

<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@drawable/ic_happy_image" />

What is the difference between YAML and JSON?

If you don't need any features which YAML has and JSON doesn't, I would prefer JSON because it is very simple and is widely supported (has a lot of libraries in many languages). YAML is more complex and has less support. I don't think the parsing speed or memory use will be very much different, and maybe not a big part of your program's performance.

Convert data.frame columns from factors to characters

This works for me - I finally figured a one liner

df <- as.data.frame(lapply(df,function (y) if(class(y)=="factor" ) as.character(y) else y),stringsAsFactors=F)

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

This worked for me. Although i'm curious of the reason I started getting the errors in the first place. When I logged out yesterday, it was fine. Log in this morning, it wasn't.

rm .git/index

git reset

sql like operator to get the numbers only

You can try this

ISNUMERIC (Transact-SQL)

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

DECLARE @Table TABLE(
        Col VARCHAR(50)
)

INSERT INTO @Table SELECT 'ABC' 
INSERT INTO @Table SELECT 'Italy' 
INSERT INTO @Table SELECT 'Apple' 
INSERT INTO @Table SELECT '234.62' 
INSERT INTO @Table SELECT '2:234:43:22' 
INSERT INTO @Table SELECT 'France' 
INSERT INTO @Table SELECT '6435.23'
INSERT INTO @Table SELECT '2' 
INSERT INTO @Table SELECT 'Lions'

SELECT  *
FROM    @Table
WHERE   ISNUMERIC(Col) = 1

What characters are allowed in an email address?

Check for @ and . and then send an email for them to verify.

I still can't use my .name email address on 20% of the sites on the internet because someone screwed up their email validation, or because it predates the new addresses being valid.

How do I fix a Git detached head?

A solution without creating a temporary branch.

How to exit (“fix”) detached HEAD state when you already changed something in this mode and, optionally, want to save your changes:

  1. Commit changes you want to keep. If you want to take over any of the changes you made in detached HEAD state, commit them. Like:

    git commit -a -m "your commit message"
    
  2. Discard changes you do not want to keep. The hard reset will discard any uncommitted changes that you made in detached HEAD state:

    git reset --hard
    

    (Without this, step 3 would fail, complaining about modified uncommitted files in the detached HEAD.)

  3. Check out your branch. Exit detached HEAD state by checking out the branch you worked on before, for example:

    git checkout master
    
  4. Take over your commits. You can now take over the commits you made in detached HEAD state by cherry-picking, as shown in my answer to another question.

    git reflog
    git cherry-pick <hash1> <hash2> <hash3> …
    

How to switch position of two items in a Python list?

How can it ever be longer than

tmp = my_list[indexOfPwd2]
my_list[indexOfPwd2] = my_list[indexOfPwd2 + 1]
my_list[indexOfPwd2 + 1] = tmp

That's just a plain swap using temporary storage.

How to get absolute path to file in /resources folder of your project

You can use ClassLoader.getResource method to get the correct resource.

URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();

OR

Although this may not work all the time, a simpler solution -

You can create a File object and use getAbsolutePath method:

File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();

ps command doesn't work in docker container

If you're running a CentOS container, you can install ps using this command:

yum install -y procps

Running this command on Dockerfile:

RUN yum install -y procps

Jenkins not executing jobs (pending - waiting for next executor)

In my case I've to set Execute concurrent builds if necessary in job's General settings.

ping response "Request timed out." vs "Destination Host unreachable"

Put very simply, request timeout means there was no response whereas destination unreachable may mean the address specified does not exist i.e. you typed in the wrong IP address.

downloading all the files in a directory with cURL

Oh, I have just the thing you need!

$host = "ftp://example.com/dir/";
$savePath = "downloadedFiles";
if($check = isFtpUp($host)){

    echo $ip." -is alive<br />";

    $check = trim($check);
    $files = explode("\n",$check);

    foreach($files as $n=>$file){
        $file = trim($file);
        if($file !== "." || $file !== ".."){
            if(!saveFtpFile($file, $host.$file, $savePath)){
                // downloading failed. possible reason: $file is a folder name.
                // echo "Error downloading file.<br />";
            }else{
                echo "File: ".$file." - saved!<br />";
            }
        }else{
            // do nothing
        }
    }
}else{
    echo $ip." - is down.<br />";
}

and functions isFtpUp and saveFtpFile are as follows:

function isFtpUp($host){
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_USERPWD, "anonymous:[email protected]");
curl_setopt($ch, CURLOPT_FTPLISTONLY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

$result = curl_exec($ch);

return $result;

}

function saveFtpFile( $targetFile = null, $sourceFile = null, $savePath){

// function settings
set_time_limit(60);
$timeout = 60;
$ftpuser = "anonymous";
$ftppassword = "[email protected]";
$savePath = "downloadedFiles"; // should exist!
$curl = curl_init();
$file = @fopen ($savePath.'/'.$targetFile, 'w');

if(!$file){
    return false;
}

curl_setopt($curl, CURLOPT_URL, $sourceFile);
curl_setopt($curl, CURLOPT_USERPWD, $ftpuser.':'.$ftppassword);

// curl settings

// curl_setopt($curl, CURLOPT_FAILONERROR, 1);
// curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_FILE, $file);

$result = curl_exec($curl);


if(!$result){
    return false;
}

curl_close($curl);
fclose($file);

return $result;
}

EDIT:

it's a php script. save it as a .php file, put it on your webserver, change $ip to address(need not be ip) of ftp server you want to download files from, create a directory named downloadedFiles on the same directory as this file.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

How to change port number in vue-cli project

Best way is to update the serve script command in your package.json file. Just append --port 3000 like so:

"scripts": {
  "serve": "vue-cli-service serve --port 3000",
  "build": "vue-cli-service build",
  "inspect": "vue-cli-service inspect",
  "lint": "vue-cli-service lint"
},

UIImage resize (Scale proportion)

I used this single line of code to create a new UIImage which is scaled. Set the scale and orientation params to achieve what you want. The first line of code just grabs the image.

    // grab the original image
    UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
    // scaling set to 2.0 makes the image 1/2 the size. 
    UIImage *scaledImage = 
                [UIImage imageWithCGImage:[originalImage CGImage] 
                              scale:(originalImage.scale * 2.0)
                                 orientation:(originalImage.imageOrientation)];

How to add jQuery to an HTML page?

You need this code wrap in tags and put on the end of page. Or create JS file (for example test.js), write this code on it and put on the end of page this tag

What's the environment variable for the path to the desktop?

While I realize this is a bit of an older post, I thought this might help people in a similar situation. I made a quick one line VBScript to pull info for whatever special folder you would like (no error checking though) and it works like this:

Create a file "GetShellFolder.vbs" with the following line:

WScript.Echo WScript.CreateObject("WScript.Shell").SpecialFolders(WScript.Arguments(0))

I always make sure to copy cscript.exe (32-bit version) to the same folder as the batch file I am running this from, I will assume you are doing the same (I have had situations where users have somehow removed C:\Windows\system32 from their path, or managed to get rid of cscript.exe, or it's infected or otherwise doesn't work).

Now copy the file to be copied to the same folder and create a batch file in there with the following lines:

for /f "delims=" %%i in ('^""%~dp0cscript.exe" "%~dp0GetShellFolder.vbs" "Desktop" //nologo^"') DO SET SHELLDIR=%%i
copy /y "%~dp0<file_to_copy>" "%SHELLDIR%\<file_to_copy>"

In the above code you can replace "Desktop" with any valid special folder (Favorites, StartMenu, etc. - the full official list is at https://msdn.microsoft.com/en-us/library/0ea7b5xe%28v=vs.84%29.aspx) and of course <file_to_copy> with the actual file you want placed there. This saves you from trying to access the registry (which you can't do as a limited user anyway) and should be simple enough to adapt to multiple applications.

Oh and for those that don't know the "%~dp0" is just the directory from which the script is being called. It works for UNC paths as well which makes the batch file using it extremely portable. That specifically ends in a trailing "\" though so it can look a little odd at first glance.

Reading HTTP headers in a Spring REST controller

I'm going to give you an example of how I read REST headers for my controllers. My controllers only accept application/json as a request type if I have data that needs to be read. I suspect that your problem is that you have an application/octet-stream that Spring doesn't know how to handle.

Normally my controllers look like this:

@Controller
public class FooController {
    @Autowired
    private DataService dataService;

    @RequestMapping(value="/foo/", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Data> getData(@RequestHeader String dataId){
        return ResponseEntity.newInstance(dataService.getData(dataId);
    }

Now there is a lot of code doing stuff in the background here so I will break it down for you.

ResponseEntity is a custom object that every controller returns. It contains a static factory allowing the creation of new instances. My Data Service is a standard service class.

The magic happens behind the scenes, because you are working with JSON, you need to tell Spring to use Jackson to map HttpRequest objects so that it knows what you are dealing with.

You do this by specifying this inside your <mvc:annotation-driven> block of your config

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

ObjectMapper is simply an extension of com.fasterxml.jackson.databind.ObjectMapper and is what Jackson uses to actually map your request from JSON into an object.

I suspect you are getting your exception because you haven't specified a mapper that can read an Octet-Stream into an object, or something that Spring can handle. If you are trying to do a file upload, that is something else entirely.

So my request that gets sent to my controller looks something like this simply has an extra header called dataId.

If you wanted to change that to a request parameter and use @RequestParam String dataId to read the ID out of the request your request would look similar to this:

contactId : {"fooId"} 

This request parameter can be as complex as you like. You can serialize an entire object into JSON, send it as a request parameter and Spring will serialize it (using Jackson) back into a Java Object ready for you to use.

Example In Controller:

@RequestMapping(value = "/penguin Details/", method = RequestMethod.GET)
@ResponseBody
public DataProcessingResponseDTO<Pengin> getPenguinDetailsFromList(
        @RequestParam DataProcessingRequestDTO jsonPenguinRequestDTO)

Request Sent:

jsonPengiunRequestDTO: {
    "draw": 1,
    "columns": [
        {
            "data": {
                "_": "toAddress",
                "header": "toAddress"
            },
            "name": "toAddress",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "fromAddress",
                "header": "fromAddress"
            },
            "name": "fromAddress",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "customerCampaignId",
                "header": "customerCampaignId"
            },
            "name": "customerCampaignId",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "penguinId",
                "header": "penguinId"
            },
            "name": "penguinId",
            "searchable": false,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "validpenguin",
                "header": "validpenguin"
            },
            "name": "validpenguin",
            "searchable": true,
            "orderable": true,
            "search": {
                "value": "",
                "regex": false
            }
        },
        {
            "data": {
                "_": "",
                "header": ""
            },
            "name": "",
            "searchable": false,
            "orderable": false,
            "search": {
                "value": "",
                "regex": false
            }
        }
    ],
    "order": [
        {
            "column": 0,
            "dir": "asc"
        }
    ],
    "start": 0,
    "length": 10,
    "search": {
        "value": "",
        "regex": false
    },
    "objectId": "30"
}

which gets automatically serialized back into an DataProcessingRequestDTO object before being given to the controller ready for me to use.

As you can see, this is quite powerful allowing you to serialize your data from JSON to an object without having to write a single line of code. You can do this for @RequestParam and @RequestBody which allows you to access JSON inside your parameters or request body respectively.

Now that you have a concrete example to go off, you shouldn't have any problems once you change your request type to application/json.

Default username password for Tomcat Application Manager

To reset your keyring.

  1. Go into your home folder.

  2. Press ctrl & h to show your hidden folders.

  3. Now look in your .gnome2/keyrings directory.

  4. Find the default.keyring file.

  5. Move that file to a different folder.

  6. Once done, reboot your computer.

How to find which views are using a certain table in SQL Server (2008)?

To find table dependencies you can use the sys.sql_expression_dependencies catalog view:

SELECT 
referencing_object_name = o.name, 
referencing_object_type_desc = o.type_desc, 
referenced_object_name = referenced_entity_name, 
referenced_object_type_desc =so1.type_desc 
FROM sys.sql_expression_dependencies sed 
INNER JOIN sys.views o ON sed.referencing_id = o.object_id 
LEFT OUTER JOIN sys.views so1 ON sed.referenced_id =so1.object_id 
WHERE referenced_entity_name = 'Person'  

You can also try out ApexSQL Search a free SSMS and VS add-in that also has the View Dependencies feature. The View Dependencies feature has the ability to visualize all SQL database objects’ relationships, including those between encrypted and system objects, SQL server 2012 specific objects, and objects stored in databases encrypted with Transparent Data Encryption (TDE)

Disclaimer: I work for ApexSQL as a Support Engineer

Chrome not rendering SVG referenced via <img> tag

I exported my svg from Photoshop CC initially and had to manually add

version="1.1" into the <svg> tag

to get it showing on chrome.

C# password TextBox in a ASP.net website

//in aspx page

<asp:TextBox ID="password" runat="server" TextMode="Password" />

//in MVC cshtml

@Html.Password("password", "", new { id = "password", Textmode = "Password" })

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

In my case problem was when i added com.fasterxml.jackson.dataformat i put the version 2.11.0.

While all other Jackson dependencies were 2.8.0 and one of them was 2.11.0 and changing all to be 2.8.0 fixed it.

FYI, 2.11 is the latest but due to my legacy code, i kept it as 2.8 as well.

Before Fix [ERROR]

com.fasterxml.jackson.dataformat version is 2.11.0    
com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.11.0
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

After Fix [WORKED] com.fasterxml.jackson.dataformat version is 2.8.0

com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.8.0
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

How would I find the second largest salary from the employee table?

select max(sal) from emp
where sal not in (select max(sal) from emp )

OR

select max(salary) from emp table 
where sal<(select max(salary)from emp)

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

Display Yes and No buttons instead of OK and Cancel in Confirm box?

There is the Jquery alert plugin

$.alerts.okButton = ' Yes ';
$.alerts.cancelButton = ' No ';

Named capturing groups in JavaScript regex?

As Tim Pietzcker said ECMAScript 2018 introduces named capturing groups into JavaScript regexes. But what I did not find in the above answers was how to use the named captured group in the regex itself.

you can use named captured group with this syntax: \k<name>. for example

var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/

and as Forivin said you can use captured group in object result as follow:

let result = regexObj.exec('2019-28-06 year is 2019');
// result.groups.year === '2019';
// result.groups.month === '06';
// result.groups.day === '28';

_x000D_
_x000D_
  var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/mgi;_x000D_
_x000D_
function check(){_x000D_
    var inp = document.getElementById("tinput").value;_x000D_
    let result = regexObj.exec(inp);_x000D_
    document.getElementById("year").innerHTML = result.groups.year;_x000D_
    document.getElementById("month").innerHTML = result.groups.month;_x000D_
    document.getElementById("day").innerHTML = result.groups.day;_x000D_
}
_x000D_
td, th{_x000D_
  border: solid 2px #ccc;_x000D_
}
_x000D_
<input id="tinput" type="text" value="2019-28-06 year is 2019"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span>Pattern: "(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>";_x000D_
<br/>_x000D_
<br/>_x000D_
<button onclick="check()">Check!</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>Year</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Month</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Day</span>_x000D_
      </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <span id="year"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="month"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="day"></span>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

An "and" operator for an "if" statement in Bash

Try this:

if [ $STATUS -ne 200 -a "$STRING" != "$VALUE" ]; then

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

How do you set the document title in React?

You can use React Helmet:

import React from 'react'
import { Helmet } from 'react-helmet'

const TITLE = 'My Page Title'

class MyComponent extends React.PureComponent {
  render () {
    return (
      <>
        <Helmet>
          <title>{ TITLE }</title>
        </Helmet>
        ...
      </>
    )
  }
}

How to convert decimal to hexadecimal in JavaScript

Arbitrary precision

This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm

  • split number to sign (s), integer part (i) and fractional part (f) e.g for -123.75 we have s=true, i=123, f=75
  • integer part to hex:
    • if i='0' stop
    • get modulo: m=i%16 (in arbitrary precision)
    • convert m to hex digit and put to result string
    • for next step calc integer part i=i/16 (in arbitrary precision)
  • fractional part
    • count fractional digits n
    • multiply k=f*16 (in arbitrary precision)
    • split k to right part with n digits and put them to f, and left part with rest of digits and put them to d
    • convert d to hex and add to result.
    • finish when number of result fractional digits is enough

_x000D_
_x000D_
// @param decStr - string with non-negative integer
// @param divisor - positive integer
function dec2HexArbitrary(decStr, fracDigits=0) {   
    // Helper: divide arbitrary precision number by js number
    // @param decStr - string with non-negative integer
    // @param divisor - positive integer
    function arbDivision(decStr, divisor) 
    { 
        // algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/
        let ans=''; 
        let idx = 0; 
        let temp = +decStr[idx]; 
        while (temp < divisor) temp = temp * 10 + +decStr[++idx]; 

        while (decStr.length > idx) { 
            ans += (temp / divisor)|0 ; 
            temp = (temp % divisor) * 10 + +decStr[++idx]; 
        } 

        if (ans.length == 0) return "0"; 

        return ans; 
    } 

    // Helper: calc module of arbitrary precision number
    // @param decStr - string with non-negative integer
    // @param mod - positive integer
    function arbMod(decStr, mod) { 
      // algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/
      let res = 0; 

      for (let i = 0; i < decStr.length; i++) 
        res = (res * 10 + +decStr[i]) % mod; 

      return res; 
    } 

    // Helper: multiply arbitrary precision integer by js number
    // @param decStr - string with non-negative integer
    // @param mult - positive integer
    function arbMultiply(decStr, mult) {
      let r='';
      let m=0;
      for (let i = decStr.length-1; i >=0 ; i--) {
        let n = m+mult*(+decStr[i]);
        r= (i ? n%10 : n) + r 
        m= n/10|0;
      }
      return r;
    }
    
    
    // dec2hex algorithm starts here
    
    let h= '0123456789abcdef';                                         // hex 'alphabet'
    let m= decStr.match(/-?(.*?)\.(.*)?/) || decStr.match(/-?(.*)/);   // separate sign,integer,ractional
    let i= m[1].replace(/^0+/,'').replace(/^$/,'0');                   // integer part (without sign and leading zeros)
    let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0');            // fractional part (without last zeros)
    let s= decStr[0]=='-';                                                                             // sign

    let r='';                                                                                                          // result
    
    if(i=='0') r='0';
        
    while(i!='0') {                                                    // integer part
      r=h[arbMod(i,16)]+r; 
      i=arbDivision(i,16);
    }
            
    if(fracDigits) r+=".";
        
    let n = f.length;
    
    for(let j=0; j<fracDigits; j++) {                                  // frac part
      let k= arbMultiply(f,16);
      f = k.slice(-n);
      let d= k.slice(0,k.length-n); 
      r+= d.length ? h[+d] : '0';
    }
            
    return (s?'-':'')+r;
}








// -----------
// TESTS
// -----------



let tests = [
  ["0",2],
  ["000",2],  
  ["123",0],
  ["-123",0],  
  ["00.000",2],
  
  ["255.75",5],
  ["-255.75",5], 
  ["127.999",32], 
];

console.log('Input      Standard          Abitrary');
tests.forEach(t=> {
  let nonArb = (+t[0]).toString(16).padEnd(17,' ');
  let arb = dec2HexArbitrary(t[0],t[1]);
  console.log(t[0].padEnd(10,' '), nonArb, arb); 
});


// Long Example (40 digits after dot)
let example = "123456789012345678901234567890.09876543210987654321"
console.log(`\nLong Example:`);
console.log('dec:',example);
console.log('hex:     ',dec2HexArbitrary(example,40));
_x000D_
_x000D_
_x000D_

How to check what version of jQuery is loaded?

…just because this method hasn't been mentioned so far - open the console and type:

$ === jQuery

As @Juhana mentioned above $().jquery will return the version number.

Playing mp3 song on python

At this point, why not mentioning python-audio-tools:

It's the best solution I found.

(I needed to install libasound2-dev, on Raspbian)

Code excerpt loosely based on:
https://github.com/tuffy/python-audio-tools/blob/master/trackplay

#!/usr/bin/python

import os
import re
import audiotools.player


START = 0
INDEX = 0

PATH = '/path/to/your/mp3/folder'

class TracklistPlayer:
    def __init__(self,
                 tr_list,
                 audio_output=audiotools.player.open_output('ALSA'),  
                 replay_gain=audiotools.player.RG_NO_REPLAYGAIN,
                 skip=False):

        if skip:
            return

        self.track_index = INDEX + START - 1
        if self.track_index < -1:
            print('--> [track index was negative]')
            self.track_index = self.track_index + len(tr_list)

        self.track_list = tr_list

        self.player = audiotools.player.Player(
                audio_output,
                replay_gain,
                self.play_track)

        self.play_track(True, False)

    def play_track(self, forward=True, not_1st_track=True):
        try:
            if forward:
                self.track_index += 1
            else:
                self.track_index -= 1

            current_track = self.track_list[self.track_index]
            audio_file = audiotools.open(current_track)
            self.player.open(audio_file)
            self.player.play()

            print('--> index:   ' + str(self.track_index))
            print('--> PLAYING: ' + audio_file.filename)

            if not_1st_track:
                pass  # here I needed to do something :)

            if forward:
                pass  # ... and also here

        except IndexError:
            print('\n--> playing finished\n')

    def toggle_play_pause(self):
        self.player.toggle_play_pause()

    def stop(self):
        self.player.stop()

    def close(self):
        self.player.stop()
        self.player.close()


def natural_key(el):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)]


def natural_cmp(a, b):
    return cmp(natural_key(a), natural_key(b))


if __name__ == "__main__":

    print('--> path:    ' + PATH)

    # remove hidden files (i.e. ".thumb")
    raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH))

    # mp3 and wav files only list
    file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list)

    # natural order sorting
    file_list.sort(key=natural_key, reverse=False)

    track_list = []
    for f in file_list:
        track_list.append(os.path.join(PATH, f))


    TracklistPlayer(track_list)

How does the "final" keyword in Java work? (I can still modify an object.)

Following are different contexts where final is used.

Final variables A final variable can only be assigned once. If the variable is a reference, this means that the variable cannot be re-bound to reference another object.

class Main {
   public static void main(String args[]){
      final int i = 20;
      i = 30; //Compiler Error:cannot assign a value to final variable i twice
   }
}

final variable can be assigned value later (not compulsory to assigned a value when declared), but only once.

Final classes A final class cannot be extended (inherited)

final class Base { }
class Derived extends Base { } //Compiler Error:cannot inherit from final Base

public class Main {
   public static void main(String args[]) {
   }
}

Final methods A final method cannot be overridden by subclasses.

//Error in following program as we are trying to override a final method.
class Base {
  public final void show() {
       System.out.println("Base::show() called");
    }
}     
class Derived extends Base {
    public void show() {  //Compiler Error: show() in Derived cannot override
       System.out.println("Derived::show() called");
    }
}     
public class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}

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?

What is the difference between signed and unsigned int

In practice, there are two differences:

  1. printing (eg with cout in C++ or printf in C): unsigned integer bit representation is interpreted as a nonnegative integer by print functions.
  2. ordering: the ordering depends on signed or unsigned specifications.

this code can identify the integer using ordering criterion:

char a = 0;
a--;
if (0 < a)
    printf("unsigned");
else
    printf("signed");

char is considered signed in some compilers and unsigned in other compilers. The code above determines which one is considered in a compiler, using the ordering criterion. If a is unsigned, after a--, it will be greater than 0, but if it is signed it will be less than zero. But in both cases, the bit representation of a is the same. That is, in both cases a-- does the same change to the bit representation.

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

What's NSLocalizedString equivalent in Swift?

I've created my own genstrings sort of tool for extracting strings using a custom translation function

extension String {

    func localizedWith(comment:String) -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: comment)
    }

}

https://gist.github.com/Maxdw/e9e89af731ae6c6b8d85f5fa60ba848c

It will parse all your swift files and exports the strings and comments in your code to a .strings file.

Probably not the easiest way to do it, but it is possible.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.

If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.


Update: There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.

http://swfupload.org/

CSS text-align not working

I try to avoid floating elements unless the design really needs it. Because you have floated the <li> they are out of normal flow.

If you add .navigation { text-align:center; } and change .navigation li { float: left; } to .navigation li { display: inline-block; } then entire navigation will be centred.

One caveat to this approach is that display: inline-block; is not supported in IE6 and needs a workaround to make it work in IE7.

Javascript "Uncaught TypeError: object is not a function" associativity question

JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.

Unfortunately, the code

var a = new B(args)(stuff)()

does not result in a syntax error, so no ; will be inserted. (An example which can run is

var answer = new Function("x", "return x")(function(){return 42;})();

To avoid surprises like this, train yourself to always end a statement with ;.


* This is just a rule of thumb and not always true. The insertion rule is much more complicated. This blog page about semicolon insertion has more detail.

Accessing Object Memory Address

You could reimplement the default repr this way:

def __repr__(self):
    return '<%s.%s object at %s>' % (
        self.__class__.__module__,
        self.__class__.__name__,
        hex(id(self))
    )

Read JSON data in a shell script

Similarly using Bash regexp. Shall be able to snatch any key/value pair.

key="Body"
re="\"($key)\": \"([^\"]*)\""

while read -r l; do
    if [[ $l =~ $re ]]; then
        name="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]}"
        echo "$name=$value"
    else
        echo "No match"
    fi
done

Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded ". This is an illustration. Better to use some "industrial" parser :)

How to remove &quot; from my Json in javascript?

Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from

result.replace(/&quot;/g,'"')

to

result.replace(/&#34;/g,'"')

Instead of this I use that:

result.replace(/(&quot\;)/g,"\"")

By this notation it works.

Can Python test the membership of multiple values in a list?

I would say we can even leave those square brackets out.

array = ['b', 'a', 'foo', 'bar']
all([i in array for i in 'a', 'b'])

Difference between <span> and <div> with text-align:center;?

the difference is not between <span> and <div> specifically, but between inline and block elements. <span> defaults to being display:inline; whereas <div> defaults to being display:block;. But these can be overridden in CSS.

The difference in the way text-align:center works between the two is down to the width.

A block element defaults to being the width of its container. It can have its width set using CSS, but either way it is a fixed width.

An inline element takes its width from the size of its content text.

text-align:center tells the text to position itself centrally in the element. But in an inline element, this is clearly not going to have any effect because the element is the same width as the text; aligning it one way or the other is meaningless.

In a block element, because the element's width is independent of the content, the content can be positioned within the element using the text-align style.

Finally, a solution for you:

There is an additional value for the display property which provides a half-way house between block and inline. Conveniently enough, it's called inline-block. If you specify a <span> to be display:inline-block; in the CSS, it will continue to work as an inline element but will take on some of the properties of a block as well, such as the ability to specify a width. Once you specify a width for it, you will be able to center the text within that width using text-align:center;

Hope that helps.

How can I run a PHP script in the background after a form is submitted?

As I know you cannot do this in easy way (see fork exec etc (don't work under windows)), may be you can reverse the approach, use the background of the browser posting the form in ajax, so if the post still work you've no wait time.
This can help even if you have to do some long elaboration.

About sending mail it's always suggest to use a spooler, may be a local & quick smtp server that accept your requests and the spool them to the real MTA or put all in a DB, than use a cron that spool the queue.
The cron may be on another machine calling the spooler as external url:

* * * * * wget -O /dev/null http://www.example.com/spooler.php

multiple figure in latex with captions

Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.

\begin{figure}[htp]
  \centering
  \label{figur}\caption{equation...}

  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \\
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \\
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}

\end{figure}

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

Not equal to != and !== in PHP

== and != do not take into account the data type of the variables you compare. So these would all return true:

'0'   == 0
false == 0
NULL  == false

=== and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:

'0'   === 0
false === 0
NULL  === false

You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():

// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false);  // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

What are the differences in die() and exit() in PHP?

PHP manual on die:

die — Equivalent to exit

You can even do die; the same way as exit; - with or without parens.

The only advantage of choosing die() over exit(), might be the time you spare on typing an extra letter ;-)

What's the difference between primitive and reference types?

these are primitive data types

  • boolean
  • character
  • byte
  • short
  • integer
  • long
  • float
  • double

saved in stack in the memory which is managed memory on the other hand object data type or reference data type stored in head in the memory managed by GC

this is the most important difference

How can I specify my .keystore file with Spring Boot and Tomcat?

If you don't want to implement your connector customizer, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer. According to the README, you only have to create your keystore, configure connector.https.*, import the library and add @ComponentScan("org.ycavatars.sboot.kit"). Then you'll have HTTPS connection.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

My solution uses positioning to get wrapped lines automatically line up correctly. So you don't have to worry about setting padding-right on the li:before.

_x000D_
_x000D_
ul {_x000D_
  margin-left: 0;_x000D_
  padding-left: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  position: relative;_x000D_
  margin-left: 1em;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  position: absolute;_x000D_
  left: -1em;_x000D_
  content: "+";_x000D_
}
_x000D_
<ul>_x000D_
  <li>Item 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 4</li>_x000D_
  <li>Item 5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Printing variables in Python 3.4

The syntax has changed in that print is now a function. This means that the % formatting needs to be done inside the parenthesis:1

print("%d. %s appears %d times." % (i, key, wordBank[key]))

However, since you are using Python 3.x., you should actually be using the newer str.format method:

print("{}. {} appears {} times.".format(i, key, wordBank[key]))

Though % formatting is not officially deprecated (yet), it is discouraged in favor of str.format and will most likely be removed from the language in a coming version (Python 4 maybe?).


1Just a minor note: %d is the format specifier for integers, not %s.

Fixing slow initial load for IIS

Writing a ping service/script to hit your idle website is rather a best way to go because you will have a complete control. Other options that you have mentioned would be available if you have leased a dedicated hosting box.

In a shared hosting space, warmup scripts are the best first level defense (self help is the best help). Here is an article which shares an idea on how to do it from your own web application.

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

Round double in two decimal places in C#?

Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)

Bootstrap 3 modal responsive

From the docs:

Modals have two optional sizes, available via modifier classes to be placed on a .modal-dialog: modal-lg and modal-sm (as of 3.1).

Also the modal dialogue will scale itself on small screens (as of 3.1.1).

How to hide column of DataGridView when using custom DataSource?

Just set DataGridView.AutoGenerateColumns = false;

You need click on the arrow on top right corner (in datagridview) to add columns, and in DataPropertyName you need to put a name of your property in your class.

Then, after you defined your columns in datagridview, you can set datagridview.datasource = myClassViewModel.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Good Hash Function for Strings

sdbm:this algorithm was created for sdbm (a public-domain reimplementation of ndbm) database library

static unsigned long sdbm(unsigned char *str)
{   
    unsigned long hash = 0;
    int c;
    while (c = *str++)
            hash = c + (hash << 6) + (hash << 16) - hash;

    return hash;
}

How remove border around image in css?

Thank for the answers,

The border is removed for Internet Explorer, but this there for Firefox.

So, I added this class to the img:

.clearBorder{border:none;}

And it worked!

How to parse float with two decimal places in javascript?

Solution for FormArray controllers 

Initialize FormArray form Builder

  formInitilize() {
    this.Form = this._formBuilder.group({
      formArray: this._formBuilder.array([this.createForm()])
    });
  }

Create Form

  createForm() {
    return (this.Form = this._formBuilder.group({
      convertodecimal: ['']
    }));
  }

Set Form Values into Form Controller

  setFormvalues() {
    this.Form.setControl('formArray', this._formBuilder.array([]));
    const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
    this.ListArrayValues.forEach((x) => {
      control.push(this.buildForm(x));
    });
  }

  private buildForm(x): FormGroup {
    const bindvalues= this._formBuilder.group({
      convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2)    --- option for two decimal value 
    });

    return bindvalues;
  }

How to modify values of JsonObject / JsonArray directly?

Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S

System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"

obj.addProperty("DebugLogId", "YYY");

System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"

Fastest way to convert string to integer in PHP

More ad-hoc benchmark results:

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = (integer) "-11";}'     

real    2m10.397s
user    2m10.220s
sys     0m0.025s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i += "-11";}'              

real    2m1.724s
user    2m1.635s
sys     0m0.009s

$ time php -r 'for ($x = 0;$x < 999999999; $x++){$i = + "-11";}'             

real    1m21.000s
user    1m20.964s
sys     0m0.007s

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

Missing MVC template in Visual Studio 2015

Just got the same issue after installing Developer Tools Microsoft ASP.NET and Web Tools 2015 (Beta7). I tried to reinstall ASP.NET Project Templates but it didn't help.

While looking into "Add / remove programs" -> "Visual 2015" -> "Modify" , I found the "Web developer tools" unchecked. This SO answer helps me to figure this.

After reinstalling this, everything reappears

enter image description here

Does bootstrap have builtin padding and margin classes?

There are built in classes, namely:

.padding-xs { padding: .25em; }
.padding-sm { padding: .5em; }
.padding-md { padding: 1em; }
.padding-lg { padding: 1.5em; }
.padding-xl { padding: 3em; }

.padding-x-xs { padding: .25em 0; }
.padding-x-sm { padding: .5em 0; }
.padding-x-md { padding: 1em 0; }
.padding-x-lg { padding: 1.5em 0; }
.padding-x-xl { padding: 3em 0; }

.padding-y-xs { padding: 0 .25em; }
.padding-y-sm { padding: 0 .5em; }
.padding-y-md { padding: 0 1em; }
.padding-y-lg { padding: 0 1.5em; }
.padding-y-xl { padding: 0 3em; }

.padding-top-xs { padding-top: .25em; }
.padding-top-sm { padding-top: .5em; }
.padding-top-md { padding-top: 1em; }
.padding-top-lg { padding-top: 1.5em; }
.padding-top-xl { padding-top: 3em; }

.padding-right-xs { padding-right: .25em; }
.padding-right-sm { padding-right: .5em; }
.padding-right-md { padding-right: 1em; }
.padding-right-lg { padding-right: 1.5em; }
.padding-right-xl { padding-right: 3em; }

.padding-bottom-xs { padding-bottom: .25em; }
.padding-bottom-sm { padding-bottom: .5em; }
.padding-bottom-md { padding-bottom: 1em; }
.padding-bottom-lg { padding-bottom: 1.5em; }
.padding-bottom-xl { padding-bottom: 3em; }

.padding-left-xs { padding-left: .25em; }
.padding-left-sm { padding-left: .5em; }
.padding-left-md { padding-left: 1em; }
.padding-left-lg { padding-left: 1.5em; }
.padding-left-xl { padding-left: 3em; }

.margin-xs { margin: .25em; }
.margin-sm { margin: .5em; }
.margin-md { margin: 1em; }
.margin-lg { margin: 1.5em; }
.margin-xl { margin: 3em; }

.margin-x-xs { margin: .25em 0; }
.margin-x-sm { margin: .5em 0; }
.margin-x-md { margin: 1em 0; }
.margin-x-lg { margin: 1.5em 0; }
.margin-x-xl { margin: 3em 0; }

.margin-y-xs { margin: 0 .25em; }
.margin-y-sm { margin: 0 .5em; }
.margin-y-md { margin: 0 1em; }
.margin-y-lg { margin: 0 1.5em; }
.margin-y-xl { margin: 0 3em; }

.margin-top-xs { margin-top: .25em; }
.margin-top-sm { margin-top: .5em; }
.margin-top-md { margin-top: 1em; }
.margin-top-lg { margin-top: 1.5em; }
.margin-top-xl { margin-top: 3em; }

.margin-right-xs { margin-right: .25em; }
.margin-right-sm { margin-right: .5em; }
.margin-right-md { margin-right: 1em; }
.margin-right-lg { margin-right: 1.5em; }
.margin-right-xl { margin-right: 3em; }

.margin-bottom-xs { margin-bottom: .25em; }
.margin-bottom-sm { margin-bottom: .5em; }
.margin-bottom-md { margin-bottom: 1em; }
.margin-bottom-lg { margin-bottom: 1.5em; }
.margin-bottom-xl { margin-bottom: 3em; }

.margin-left-xs { margin-left: .25em; }
.margin-left-sm { margin-left: .5em; }
.margin-left-md { margin-left: 1em; }
.margin-left-lg { margin-left: 1.5em; }
.margin-left-xl { margin-left: 3em; }

Apply style to cells of first row

Below works for first tr of the table under thead

table thead tr:first-child {
   background: #f2f2f2;
}

And this works for the first tr of thead and tbody both:

table thead tbody tr:first-child {
   background: #f2f2f2;
}

Plotting lines connecting points

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

Plot of two pairs of points, each connected by a separate line

Can't push to GitHub because of large file which I already deleted

I had this issue when I didn't have a gitignore file with my iOS project

I think maybe it was trying to push a humungous file to github and github was probably rejecting that giant file or (files)

Where can I download JSTL jar

http://jstl.java.net/download.html

It's been split into two separate JAR files: jstl-api.jar and jstl-impl.jar.

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

  • The first danger lies in reload(sys).

    When you reload a module, you actually get two copies of the module in your runtime. The old module is a Python object like everything else, and stays alive as long as there are references to it. So, half of the objects will be pointing to the old module, and half to the new one. When you make some change, you will never see it coming when some random object doesn't see the change:

    (This is IPython shell)
    
    In [1]: import sys
    
    In [2]: sys.stdout
    Out[2]: <colorama.ansitowin32.StreamWrapper at 0x3a2aac8>
    
    In [3]: reload(sys)
    <module 'sys' (built-in)>
    
    In [4]: sys.stdout
    Out[4]: <open file '<stdout>', mode 'w' at 0x00000000022E20C0>
    
    In [11]: import IPython.terminal
    
    In [14]: IPython.terminal.interactiveshell.sys.stdout
    Out[14]: <colorama.ansitowin32.StreamWrapper at 0x3a9aac8>
    
  • Now, sys.setdefaultencoding() proper

    All that it affects is implicit conversion str<->unicode. Now, utf-8 is the sanest encoding on the planet (backward-compatible with ASCII and all), the conversion now "just works", what could possibly go wrong?

    Well, anything. And that is the danger.

    • There may be some code that relies on the UnicodeError being thrown for non-ASCII input, or does the transcoding with an error handler, which now produces an unexpected result. And since all code is tested with the default setting, you're strictly on "unsupported" territory here, and no-one gives you guarantees about how their code will behave.
    • The transcoding may produce unexpected or unusable results if not everything on the system uses UTF-8 because Python 2 actually has multiple independent "default string encodings". (Remember, a program must work for the customer, on the customer's equipment.)
      • Again, the worst thing is you will never know that because the conversion is implicit -- you don't really know when and where it happens. (Python Zen, koan 2 ahoy!) You will never know why (and if) your code works on one system and breaks on another. (Or better yet, works in IDE and breaks in console.)

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Error with multiple definitions of function

You have #include "fun.cpp" in mainfile.cpp so compiling with:

g++ -o hw1 mainfile.cpp

will work, however if you compile by linking these together like

g++ -g -std=c++11 -Wall -pedantic   -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic   -c -o mainfile.o mainfile.cpp

As they mention above, adding #include "fun.hpp" will need to be done or it won't work. However, your case with the funct() function is slightly different than my problem.

I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.

Python regex for integer?

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers with a sign could be for example

^[-+]?[0-9]+$

meaning

  1. ^ - start of string
  2. [-+]? - an optional (this is what ? means) minus or plus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string

Note: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2 could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.

Android - How to download a file from a webserver

Here is the code help you to download file from server at the same time you can see the progress of downloading on your status bar.

See the functionality in below image of my code:

enter image description here enter image description here

STEP - 1 : Create on DownloadFileFromURL.java class file to download file content from server. Here i create an asynchronous task to download file.

public class DownloadFileFromURL extends AsyncTask<String, Integer, String> {

private NotificationManager mNotifyManager;
private NotificationCompat.Builder build;
private File fileurl;
int id = 123;
OutputStream output;
private Context context;
private String selectedDate;
private String ts = "";

public DownloadFileFromURL(Context context, String selectedDate) {
    this.context = context;
    this.selectedDate = selectedDate;

}

protected void onPreExecute() {
    super.onPreExecute();

    mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    build = new NotificationCompat.Builder(context);
    build.setContentTitle("Download")
            .setContentText("Download in progress")
            .setChannelId(id + "")
            .setAutoCancel(false)
            .setDefaults(0)
            .setSmallIcon(R.drawable.ic_menu_download);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(id + "",
                "Social Media Downloader",
                NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("no sound");
        channel.setSound(null, null);
        channel.enableLights(false);
        channel.setLightColor(Color.BLUE);
        channel.enableVibration(false);
        mNotifyManager.createNotificationChannel(channel);

    }
    build.setProgress(100, 0, false);
    mNotifyManager.notify(id, build.build());
    String msg = "Download started";
    //CustomToast.showToast(context,msg);
}

@Override
protected String doInBackground(String... f_url) {
    int count;
    ts = selectedDate.split("T")[0];
    try {
        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();
        int lenghtOfFile = conection.getContentLength();

        InputStream input = new BufferedInputStream(url.openStream(),
                8192);
        // Output stream
        output = new FileOutputStream(Environment
                .getExternalStorageDirectory().toString()
                + Const.DownloadPath + ts + ".pdf");
        fileurl = new File(Environment.getExternalStorageDirectory()
                + Const.DownloadPath + ts + ".pdf");
        byte[] data = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            int cur = (int) ((total * 100) / lenghtOfFile);

            publishProgress(Math.min(cur, 100));
            if (Math.min(cur, 100) > 98) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Log.d("Failure", "sleeping failure");
                }
            }
            Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);

            output.write(data, 0, count);
        }

        output.flush();

        output.close();
        input.close();

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return null;
}

protected void onProgressUpdate(Integer... progress) {
    build.setProgress(100, progress[0], false);
    mNotifyManager.notify(id, build.build());
    super.onProgressUpdate(progress);
}

@Override
protected void onPostExecute(String file_url) {
    build.setContentText("Download complete");
    build.setProgress(0, 0, false);
    mNotifyManager.notify(id, build.build());
} }

Note: If you want code with import package then Click Here

Now Step 2: You need to call above ayncronous task on your click event. for example i have set on pdf image icon. To call AsyncTask use below code:

 new DownloadFileFromURL(fContext,filename).execute(serverFileUrl);

Note: Here You can see filename variable in file parameter. This is the name which i use to save my downloaded file in local device. currently i am downloading only pdf file but you can use you url in serverFileUrl parameter.

How to change indentation mode in Atom?

All of the most popular answers on here are all great answers and will turn on spaces for tabs, but they are all missing one thing. How to apply the spaces instead of tabs to existing code.

To do this simply select all the code you want to format, then go to Edit->Lines->Auto Indent and it will fix everything selected.

Alternatively, you can just select all the code you want to format, then use Ctrl Shift P and search for Auto Indent. Just click it in the search results and it will fix everything selected.

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

Oracle: If Table Exists

You could always catch the error yourself.

begin
execute immediate 'drop table mytable';
exception when others then null;
end;

It is considered bad practice to overuse this, similar to empty catch()'es in other languages.

Regards
K

Parsing command-line arguments in C

With C++, the answer is usually in Boost...

Boost.Program Options

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

I have this issue in SOAP-UI and no one solution above dont helped me.

Proper solution for me was to add

-Dsoapui.sslcontext.algorithm=TLSv1

in vmoptions file (in my case it was ...\SoapUI-5.4.0\bin\SoapUI-5.4.0.vmoptions)

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Standard exists mainly to improve code sharing and make the APIs available in each .NET implementation more consistent.

While creating libraries we can have the target as .NET Standard 2.0 so that the library created would be compatible with different versions of .NET Framework including .NET Core, Mono, etc.