Programs & Examples On #Java home

JAVA_HOME is an environment variable which should point to the root directory of the JDK installation.

Make $JAVA_HOME easily changable in Ubuntu

Try these steps.

--We are going to edit "etc\profile". The environment variables are to be input at the bottom of the file. Since Ubuntu does not give access to root folder, we will have to use a few commands in the terminal

Step1: Start Terminal. Type in command: gksudo gedit /etc/profile

Step2: The profile text file will open. Enter the environment variables at the bottom of the page........... Eg: export JAVA_HOME=/home/alex/jdk1.6.0_22/bin/java

export PATH=/home/alex/jdk1.6.0_22/bin:$PATH

step3: save and close the file. Check if the environment variables are set by using echo command........ Eg echo $PATH

How to change Java version used by TOMCAT?

test open the termenal or cmd. go to the [tomcat-home]\bin directory. ex: c:\tomcat8\bin write the following command: Tomcat8W //ES//Tomcat8 will open dialog, select the java tap(top tap). change the Java virtual Machine value.

Tomcat is not running even though JAVA_HOME path is correct

Also ensure that you have the correct version of Tomcat for the CPU type. I had installed a 64bit tomcat on a 32bit O/S but it was giving me the JAVA_HOME exception when that wasn't the case at all.

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

Jenkins, specifying JAVA_HOME

Download package rpm package from http://pkg.jenkins-ci.org/redhat/ you can give additional java location like I have default 1.7 java in my system but I am using /opt/jdk1.8.0_60/bin/java for jenkins. Open jenkins startup script /etc/init.d/jenkins and add additional java here, I m case I have added /opt/jdk1.8.0_60/bin/java,

Search usable Java as /usr/bin/java might not point to minimal version required by Jenkins.

See http://www.nabble.com/guinea-pigs-wanted-----Hudson-RPM-for-RedHat-Linux-td25673707.html

candidates=" /opt/jdk1.8.0_60/bin/java

How to set JAVA_HOME in Mac permanently?

First, figure out where your java home is by running the command /usr/libexec/java_home -v <version> replacing with whatever version of OpenJDK your running.

Next use vim ~/.bash_profile to edit your bash profile. Add export JAVA_HOME="<java path>" replacing with the path to your java home found in the last step.

Finally, run the command source ~/.bash_profile

This should permanently set your JAVA_HOME environment variable.

To make sure it worked run echo $JAVA_HOME and make sure it returns the path you set

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

Installing Android Studio, does not point to a valid JVM installation error

Using c:/Program Files/Java/jre1.8.0_73/ instead of C:/Program Files/Java/jdk1.8.0_73 as JAVA_HOME variable solved the problem for me. Android studio now launches without problems.

How do I change the JAVA_HOME for ant?

You could create your own script for running ant, e.g. named ant.sh like:

#!/bin/sh
JAVA_HOME=</path/to/jdk>; export JAVA_HOME
ant $@

and then run your script.

$ chmod 755 ant.sh
$./ant.sh clean compile

or whatever ant target you wish to run

How to set JAVA_HOME in Linux for all users

While we are up to setting JAVA_HOME, let me share some benefits of setting JAVA_HOME or any other environment variable:

1) It's easy to upgrade JDK without affecting your application startup and config file which points to JAVA_HOME. you just need to download new version and make sure your JAVA_HOME points to new version of Java. This is best benefit of using environment variable or links.

2) JAVA_HOME variable is short and concise instead of full path to JDK installation directory.

3) JAVA_HOME variable is platform independence i.e. if your startup script uses JAVA_HOME then it can run on Windows and UNIX without any modification, you just need to set JAVA_HOME on respective operating system.

Read more: http://javarevisited.blogspot.com/2012/02/how-to-set-javahome-environment-in.html#ixzz4BWmaYIjH

How to change JAVA.HOME for Eclipse/ANT

In Eclipse the Ant java.home variable is not based on the Windows JAVA_HOME environment variable. Instead it is set to the home directory of the project's JRE.

To change the default JRE (e.g. change it to a JDK) you can go to Windows->Preferences... and choose Java->Installed JREs.

To change just a single project's JRE you can go to Project->Properties and choose Java Build Path and choose the Libraries tab. Find the JRE System Library and click it, then choose Edit and choose the JRE (or JDK) that you want.

If that doesn't work then when running the build file you can choose Run as->Ant Build... and click the JRE tab, choose separate JRE and specify the JRE you want there.

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

My correct target has always been to download it from Sun and just install it that way. Then you know exactly what directory everything goes in.

But if you'd prefer to stick with the odd way that Debian installs it, my best guess would be the parent directory just above where the java and javac binaries are located.

(since when you specify it in your path it's $JAVA_HOME/bin) (So in your case it would be ... $JAVA_HOME/share and $JAVA_HOME would be /usr ?)

Eh, that doesn't sound right...

I'm interested to hear the answer to this too!

Error: JAVA_HOME is not defined correctly executing maven

$JAVA_HOME should be the directory where java was installed, not one of its parts:

export JAVA_HOME=/usr/lib/jvm/java-7-oracle

How to set Oracle's Java as the default Java in Ubuntu?

to set Oracle's Java SE Development Kit as the system default Java just download the latest Java SE Development Kit from here then create a directory somewhere you like in your file system for example /usr/java now extract the files you just downloaded in that directory:

$ sudo tar xvzf jdk-8u5-linux-i586.tar.gz -C /usr/java

now to set your JAVA_HOME environment variable:

$ JAVA_HOME=/usr/java/jdk1.8.0_05/
$ sudo update-alternatives --install /usr/bin/java java ${JAVA_HOME%*/}/bin/java 20000
$ sudo update-alternatives --install /usr/bin/javac javac ${JAVA_HOME%*/}/bin/javac 20000

make sure the Oracle's java is set as default java by:

$ update-alternatives --config java

you get something like this:

There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                           Priority   Status
------------------------------------------------------------
* 0            /opt/java/jdk1.8.0_05/bin/java                  20000     auto mode
  1            /opt/java/jdk1.8.0_05/bin/java                  20000     manual mode
  2            /usr/lib/jvm/java-6-openjdk-i386/jre/bin/java   1061      manual mode

Press enter to keep the current choice[*], or type selection number:

pay attention to the asterisk before the numbers on the left and if the correct one is not set choose the correct one by typing the number of it and pressing enter. now test your java:

$ java -version

if you get something like the following, you are good to go:

java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) Server VM (build 25.5-b02, mixed mode)

also note that you might need root permission or be in sudoers group to be able to do this. I've tested this solution on both ubuntu 12.04 and Debian wheezy and it works in both of them.

"Unable to locate tools.jar" when running ant

The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.

I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.

Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin appears).

Android Studio error: "Environment variable does not point to a valid JVM installation"

I also had similar issue. Had correctly installed the application, had appropriately setup the JAVA_HOME, still it was not able to find the JDK and complains about the ver 1.6.0_17.

I no longer have any such version installed on my machine. After much digging I got onto the "HKEY_LOCAL_MACHINE\software\javasoft\Java Development Kit\" where I found multiple JDK version being mentioned.

I removed all except 1.8.0_25 that I currently have on my machine. Restarted the Android Studio, and it worked without any problem. May be someone visit this page, facing similar issue, might help.

How to set java_home on Windows 7?

In cmd (temporarily for that cmd window):

set JAVA_HOME="C:\\....\java\jdk1.x.y_zz"

echo %JAVA_HOME%

set PATH=%PATH%;%JAVA_HOME%\bin

echo %PATH%

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I actually looked at this a little in the disassembler, since source isn't available.

/usr/bin/java and /usr/libexec/java_home both make use of JavaLaunching.framework. The JAVA_HOME environment variable is indeed checked first by /usr/bin/java and friends (but not /usr/libexec/java_home.) The framework uses the JAVA_VERSION and JAVA_ARCH envirionment variables to filter the available JVMs. So, by default:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    11.0.5, x86_64: "Amazon Corretto 11"    /Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home
    1.8.0_232, x86_64:  "Amazon Corretto 8" /Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/amazon-corretto-11.jdk/Contents/Home

But setting, say, JAVA_VERSION can override the default:

$ JAVA_VERSION=1.8 /usr/libexec/java_home
/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home

You can also set JAVA_LAUNCHER_VERBOSE=1 to see some additional debug logging as far as search paths, found JVMs, etc., with both /usr/bin/java and /usr/libexec/java_home.

In the past, JavaLaunching.framework actually used the preferences system (under the com.apple.java.JavaPreferences domain) to set the preferred JVM order, allowing the default JVM to be set with PlistBuddy - but as best as I can tell, that code has been removed in recent versions of macOS. Environment variables seem to be the only way (aside from editing the Info.plist in the JDK bundles themselves.)

Setting default environment variables can of course be done through your .profile or via launchd, if you need them be set at a session level.

Where is the Java SDK folder in my computer? Ubuntu 12.04

WAY-1 : Updated for the shortest and easy way

Below command will give you the path, But it will only work if java command is working in other words if java path is configured.

readlink -f $(which java) 

Read more at Where can I find the Java SDK in Linux?


WAY-2 (Better than WAY-1) : Below answer is still working and try it if above command is not working for you.

You need to dig into symbolic links. Below is steps to get Java directory

Step 1:

$ whereis java
java: /usr/bin/java /etc/java /usr/share/java

That tells the command java resides in /usr/bin/java.

Dig again:

Step 2:

$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java

So, now we know that /usr/bin/java is actually a symbolic link to /etc/alternatives/java.

Dig deeper using the same method above:

Step 3:

$ ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java

So, thats the actual location of java: /usr/local/jre.....

You could still dig deeper to find other symbolic links.


Reference : where is java's home dir?

Set ANDROID_HOME environment variable in mac

Open Terminal

nano ~/.bash_profile


export ANDROID_HOME=/Users/qss/Library/Android/sdk
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH

Control+S to save
Control+X to exit
Y to save changes
Update changes in terminal
source ~/.bash_profile

Validate Path:
echo $PATH

Confirm if all okay:
adb devices

How to set CATALINA_HOME variable in windows 7?

Assuming Java (JDK + JRE) is installed in your system, do the following steps:

  1. Install Tomcat7
  2. Copy 'tools.jar' from 'C:\Program Files (x86)\Java\jdk1.6.0_27\lib' and paste it under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib'.
  3. Setup paths in your Environment Variables as shown below:

C:>echo %path%

C:\Program Files (x86)\Java\jdk1.6.0_27\bin;%CATALINA_HOME%\bin;

C:>echo %classpath%

C:\Program Files (x86)\Java\jdk1.6.0_27\lib\tools.jar;
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;

C:>echo %CATALINA_HOME%

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0;

C:>echo %JAVA_HOME%

C:\Program Files (x86)\Java\jdk1.6.0_27;

Now you can test whether Tomcat is setup correctly, by typing the following commands in your command prompt:

C:/>javap javax.servlet.ServletException
C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

Now start Tomcat service by double clicking on 'Tomcat7.exe' under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\bin'.

Extract source code from .jar file

suppose your JAR file is in C:\Documents and Settings\mmeher\Desktop\jar and the JAR file name is xx.jar, then write the below two commands in command prompt:

1> cd C:\Documents and Settings\mmeher\Desktop\jar

2> jar xf xx.jar

Pandas: change data type of Series to String

You can use:

df.loc[:,'id'] = df.loc[:, 'id'].astype(str)

This is why they recommend this solution: Pandas doc

TD;LR

To reflect some of the answers:

df['id'] = df['id'].astype("string")

This will break on the given example because it will try to convert to StringArray which can not handle any number in the 'string'.

df['id']= df['id'].astype(str)

For me this solution throw some warning:

> SettingWithCopyWarning:  
> A value is trying to be set on a copy of a
> slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

Is Fortran easier to optimize than C for heavy calculations?

Generally FORTRAN is slower than C. C can use hardware level pointers allowing the programmer to hand-optimize. FORTRAN (in most cases) doesn't have access to hardware memory addressing hacks. (VAX FORTRAN is another story.) I've used FORTRAN on and off since the '70's. (Really.)

However, starting in the 90's FORTRAN has evolved to include specific language constructs that can be optimized into inherently parallel algorithms that can really scream on a multi-core processor. For example, automatic Vectorizing allows multiple processors to handle each element in a vector of data concurrently. 16 processors -- 16 element vector -- processing takes 1/16th the time.

In C, you have to manage your own threads and design your algorithm carefully for multi-processing, and then use a bunch of API calls to make sure that the parallelism happens properly.

In FORTRAN, you only have to design your algorithm carefully for multi-processing. The compiler and run-time can handle the rest for you.

You can read a little about High Performance Fortran, but you find a lot of dead links. You're better off reading about Parallel Programming (like OpenMP.org) and how FORTRAN supports that.

How do I get to IIS Manager?

First of all, you need to check that the IIS is installed in your machine, for that you can go to:

Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'

If not, check it, and Press Accept to install it.

Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).

Edit: You should have something like this: enter image description here

Location of GlassFish Server Logs

tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log

You can also upload log from admin console : http://yoururl:4848

enter image description here

Android: Flush DNS

You have a few options:

  • Release an update for your app that uses a different hostname that isn't in anyone's cache.
  • Same thing, but using the IP address of your server
  • Have your users go into settings -> applications -> Network Location -> Clear data.

You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!

Android Studio drawable folders

In order to create the drawable directory structure for different image densities, You need to:

  1. Right-click on the \res folder
  2. Select new > android resource directory
  3. In the New Resource Directory window, under Available qualifiers resource type section, select drawable.

  4. Add density and choose the appropriate size.

Good examples using java.util.logging

SLF4J is a better logging facade than Apache Commons Logging (ACL). It has bridges to other logging frameworks, making direct calls to ACL, Log4J, or Java Util Logging go through SLF4J, so that you can direct all output to one log file if you wish, with just one log configuration file. Why would your application use multiple logging frameworks? Because 3rd-party libraries you use, especially older ones, probably do.

SLF4J supports various logging implementations. It can output everything to standard-out, use Log4J, or Logback (recommended over Log4J).

http://www.slf4j.org/

http://logback.qos.ch/

How to convert a Title to a URL slug in jQuery?

private string ToSeoFriendly(string title, int maxLength) {
    var match = Regex.Match(title.ToLower(), "[\\w]+");
    StringBuilder result = new StringBuilder("");
    bool maxLengthHit = false;
    while (match.Success && !maxLengthHit) {
        if (result.Length + match.Value.Length <= maxLength) {
            result.Append(match.Value + "-");
        } else {
            maxLengthHit = true;
            // Handle a situation where there is only one word and it is greater than the max length.
            if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
        }
        match = match.NextMatch();
    }
    // Remove trailing '-'
    if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
    return result.ToString();
}

CSS Animation and Display None

When animating height (from 0 to auto), using transform: scaleY(0); is another useful approach to hide the element, instead of display: none;:

.section {
  overflow: hidden;
  transition: transform 0.3s ease-out;
  height: auto;
  transform: scaleY(1);
  transform-origin: top;

  &.hidden {
    transform: scaleY(0);
  }
}

When should we use intern method of String on String literals

As you said, that string intern() method will first find from the String pool, if it finds, then it will return the object that points to that, or will add a new String into the pool.

    String s1 = "Hello";
    String s2 = "Hello";
    String s3 = "Hello".intern();
    String s4 = new String("Hello");

    System.out.println(s1 == s2);//true
    System.out.println(s1 == s3);//true
    System.out.println(s1 == s4.intern());//true

The s1 and s2 are two objects pointing to the String pool "Hello", and using "Hello".intern() will find that s1 and s2. So "s1 == s3" returns true, as well as to the s3.intern().

using lodash .groupBy. how to add your own keys for grouped output?

I would suggest a different approach, using my own library you could do this in a few lines:

var groupMe = sequence(
  groupBy(pluck('color')),
  forOwn(function(acc, k, v) {
    acc.push({colors: k, users: v});
    return acc;
  },[])
);

var result = groupMe(collection);

This would a be a bit difficult with lodash or Underscore because the arguments are in the opposite order order, so you'd have to use _.partial a lot.

Correct way to read a text file into a buffer in C?

Not tested, but should work.. And yes, it could be better implemented with fread, I'll leave that as an exercise to the reader.

#define DEFAULT_SIZE 100
#define STEP_SIZE 100

char *buffer[DEFAULT_SIZE];
size_t buffer_sz=DEFAULT_SIZE;
size_t i=0;
while(!feof(fp)){
  buffer[i]=fgetc(fp);
  i++;
  if(i>=buffer_sz){
    buffer_sz+=STEP_SIZE;
    void *tmp=buffer;
    buffer=realloc(buffer,buffer_sz);
    if(buffer==null){ free(tmp); exit(1);} //ensure we don't have a memory leak
  }
}
buffer[i]=0;

Aborting a stash pop in Git

Edit: From the git help stash documentation in the pop section:

Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.

If the --index option is used, then tries to reinstate not only the working tree's changes, but also the index's ones. However, this can fail, when you have conflicts (which are stored in the index, where you therefore can no longer apply the changes as they were originally).

Try hardcopying all your repo into a new dir (so you have a copy of it) and run:

git stash show and save that output somewhere if you care about it.

then: git stash drop to drop the conflicting stash then: git reset HEAD

That should leave your repo in the state it was before (hopefully, I still haven't been able to repro your problem)

===

I am trying to repro your problem but all I get when usin git stash pop is:

error: Your local changes to the following files would be overwritten by merge:
...
Please, commit your changes or stash them before you can merge.
Aborting

In a clean dir:

git init
echo hello world > a
git add a & git commit -m "a"
echo hallo welt >> a
echo hello world > b
git add b & git commit -m "b"
echo hallo welt >> b
git stash
echo hola mundo >> a
git stash pop

I don't see git trying to merge my changes, it just fails. Do you have any repro steps we can follow to help you out?

Git: force user and password prompt

This is most likely because you have multiple accounts, like one private, one for work with GitHub.

SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub

SOLUTION OnMac, issue following on terminal:

git remote set-url origin https://[email protected]/username/repo-name.git

by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.

Is there an alternative sleep function in C to milliseconds?

#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds

Difference between JSON.stringify and JSON.parse

Firstly, JSON.stringify() function converts a JavaScript value to a JavaScript Object Notation (JSON) string. JSON.parse() function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.

https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx

Secondly, the following sample will be helpful for you to understand these two functions.

<form id="form1" runat="server">
    <div>
        <div id="result"></div>
    </div>
</form>

<script>
    $(function () {
        //define a json object
        var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };

        //use JSON.stringify to convert it to json string
        var jsonstring = JSON.stringify(employee);
        $("#result").append('<p>json string: ' + jsonstring + '</p>');

        //convert json string to json object using JSON.parse function
        var jsonobject = JSON.parse(jsonstring);
        var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';

        $("#result").append('<p>json object:</p>');
        $("#result").append(info);
    });
</script>

How to run a program without an operating system?

I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive

This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.

How do you count the number of occurrences of a certain substring in a SQL varchar?

The following should do the trick for both single character and multiple character searches:

CREATE FUNCTION dbo.CountOccurrences
(
   @SearchString VARCHAR(1000),
   @SearchFor    VARCHAR(1000)
)
RETURNS TABLE
AS
   RETURN (
             SELECT COUNT(*) AS Occurrences
             FROM   (
                       SELECT ROW_NUMBER() OVER (ORDER BY O.object_id) AS n
                       FROM   sys.objects AS O
                    ) AS N
                    JOIN (
                            VALUES (@SearchString)
                         ) AS S (SearchString)
                         ON
                         SUBSTRING(S.SearchString, N.n, LEN(@SearchFor)) = @SearchFor
          );
GO

---------------------------------------------------------------------------------------
-- Test the function for single and multiple character searches
---------------------------------------------------------------------------------------
DECLARE @SearchForComma      VARCHAR(10) = ',',
        @SearchForCharacters VARCHAR(10) = 'de';

DECLARE @TestTable TABLE
(
   TestData VARCHAR(30) NOT NULL
);

INSERT INTO @TestTable
     (
        TestData
     )
VALUES
     ('a,b,c,de,de ,d e'),
     ('abc,de,hijk,,'),
     (',,a,b,cde,,');

SELECT TT.TestData,
       CO.Occurrences AS CommaOccurrences,
       CO2.Occurrences AS CharacterOccurrences
FROM   @TestTable AS TT
       OUTER APPLY dbo.CountOccurrences(TT.TestData, @SearchForComma) AS CO
       OUTER APPLY dbo.CountOccurrences(TT.TestData, @SearchForCharacters) AS CO2;

The function can be simplified a bit using a table of numbers (dbo.Nums):

   RETURN (
             SELECT COUNT(*) AS Occurrences
             FROM   dbo.Nums AS N
                    JOIN (
                            VALUES (@SearchString)
                         ) AS S (SearchString)
                         ON
                         SUBSTRING(S.SearchString, N.n, LEN(@SearchFor)) = @SearchFor
          );

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

The supplied host is not resolving for me (custom DNS or self configured host?) so I can only hazard to guess.

But as you are requesting the resources over SSL it is likely the certificate is invalid. Either it is self-signed and has not been added to your browser/OS exceptions or it is otherwise invalid.

Try the URI directly in the same browser and inspect the certificate.

Edit: this is in no way related to jQuery, JavaScript or CSS directly.

PHP remove special character from string

You want str replace, because performance-wise it's much cheaper and still fits your needs!

$title = str_replace( array( '\'', '"', ',' , ';', '<', '>' ), ' ', $rawtitle);

(Unless this is all about security and sql injection, in that case, I'd rather to go with a POSITIVE list of ALLOWED characters... even better, stick with tested, proven routines.)

Btw, since the OP talked about title-setting: I wouldn't replace special chars with nothing, but with a space. A superficious space is less of a problem than two words glued together...

MongoDB distinct aggregation

You can use $addToSet with the aggregation framework to count distinct objects.

For example:

db.collectionName.aggregate([{
    $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])

What are the main performance differences between varchar and nvarchar SQL Server data types?

If you are using NVARCHAR just because a system stored procedure requires it, the most frequent occurrence being inexplicably sp_executesql, and your dynamic SQL is very long, you would be better off from performance perspective doing all string manipulations (concatenation, replacement etc.) in VARCHAR then converting the end result to NVARCHAR and feeding it into the proc parameter. So no, do not always use NVARCHAR!

Difference between OData and REST web services

UPDATE Warning, this answer is extremely out of date now that OData V4 is available.


I wrote a post on the subject a while ago here.

As Franci said, OData is based on Atom Pub. However, they have layered some functionality on top and unfortunately have ignored some of the REST constraints in the process.

The querying capability of an OData service requires you to construct URIs based on information that is not available, or linked to in the response. It is what REST people call out-of-band information and introduces hidden coupling between the client and server.

The other coupling that is introduced is through the use of EDMX metadata to define the properties contained in the entry content. This metadata can be discovered at a fixed endpoint called $metadata. Again, the client needs to know this in advance, it cannot be discovered.

Unfortunately, Microsoft did not see fit to create media types to describe these key pieces of data, so any OData client has to make a bunch of assumptions about the service that it is talking to and the data it is receiving.

How to find the kth largest element in an unsorted array of length n in O(n)?

The C++ standard library has almost exactly that function call nth_element, although it does modify your data. It has expected linear run-time, O(N), and it also does a partial sort.

const int N = ...;
double a[N];
// ... 
const int m = ...; // m < N
nth_element (a, a + m, a + N);
// a[m] contains the mth element in a

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

It's a separate statement.

It's also not possible to insert into a table and select from it and build an index in the same statement either.

The BOL entry contains the information you need:

CLUSTERED | NONCLUSTERED
Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.

In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.

You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.

A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.

That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).

How to automatically indent source code?

It may be worth noting that auto-indent does not work if there are syntax errors in the document. Get rid of the red squigglies, and THEN try CTRL+K, CTRL+D, whatever...

Opening A Specific File With A Batch File?

start wgnplot.exe "c:\path to file to open\foo.dat"

Two column div layout with fluid left and fixed right column

CSS Solutuion

#left{
    float:right;
    width:200px;
    height:500px;
    background:red;   
}

#right{
    margin-right: 200px;
    height:500px;
    background:blue;
}

Check working example at http://jsfiddle.net/NP4vb/3/

jQuery Solution

var parentw = $('#parent').width();
var rightw = $('#right').width();
$('#left').width(parentw - rightw);

Check working example http://jsfiddle.net/NP4vb/

Uninstall / remove a Homebrew package including all its dependencies

EDIT:

It looks like the issue is now solved using an external command called brew rmdeps or brew rmtree.

To install and use, issue the following commands:

$ brew tap beeftornado/rmtree
$ brew rmtree <package>

See the above link for more information and discussion.


Original answer:

It appears that currently, there's no easy way to accomplish this.

However, I filed an issue on Homebrew's GitHub page, and somebody suggested a temporary solution until they add an exclusive command to solve this.

There's an external command called brew leaves which prints all packages that are not dependencies of other packages.

If you do a logical and on the output of brew leaves and brew deps <package>, you might just get a list of the orphaned dependency packages, which you can uninstall manually afterwards. Combine this with xargs and you'll get what you need, I guess (untested, don't count on this).


EDIT: Somebody just suggested a very similar solution, using join instead of xargs:

brew rm FORMULA
brew rm $(join <(brew leaves) <(brew deps FORMULA))

See the comment on the issue mentioned above for more info.

conflicting types error when compiling c program using gcc

If you don't declare a function and it only appears after being called, it is automatically assumed to be int, so in your case, you didn't declare

void my_print (char *);
void my_print2 (char *);

before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *); and int my_print2 (char *); and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types.

As Brian suggested, declare those two methods before main.

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

Replace Multiple String Elements in C#

If you are simply after a pretty solution and don't need to save a few nanoseconds, how about some LINQ sugar?

var input = "test1test2test3";
var replacements = new Dictionary<string, string> { { "1", "*" }, { "2", "_" }, { "3", "&" } };

var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));

What is the recommended way to make a numeric TextField in JavaFX?

Very old thread, but this seems neater and strips out non-numeric characters if pasted.

// force the field to be numeric only
textField.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, 
        String newValue) {
        if (!newValue.matches("\\d*")) {
            textField.setText(newValue.replaceAll("[^\\d]", ""));
        }
    }
});

Edit a specific Line of a Text File in C#

I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps

using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
        {
            var destinationReader = StreamReader(fs);
            var writer = StreamWriter(fs);
            while ((line = reader.ReadLine()) != null)
            {
              if (line_number == line_to_edit)
                {
                    writer.WriteLine(lineToWrite);
                }
                else
                {
                    destinationReader .ReadLine();
                }
                line_number++;
            }
        }

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

How to get integer values from a string in Python?

Here's your one-liner, without using any regular expressions, which can get expensive at times:

>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))

returns:

'123453120'

How do I apply CSS3 transition to all properties except background-position?

Try this...

* {
    transition: all .2s linear;
    -webkit-transition: all .2s linear;
    -moz-transition: all .2s linear;
    -o-transition: all .2s linear;
}
a {
    -webkit-transition: background-position 1ms linear;
    -moz-transition: background-position 1ms linear;
    -o-transition: background-position 1ms linear;
    transition: background-position 1ms linear;
}

How to create a zip archive of a directory in Python?

A solution using pathlib.Path, which is independent of the OS used:

import zipfile
from pathlib import Path

def zip_dir(path: Path, zip_file_path: Path):
    """Zip all contents of path to zip_file"""
    files_to_zip = [
        file for file in path.glob('*') if file.is_file()]
    with zipfile.ZipFile(
        zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zip_f:
        for file in files_to_zip:
            print(file.name)
            zip_f.write(file, file.name)

current_dir = Path.cwd()  
zip_dir = current_dir / "test"
tools.zip_dir(
    zip_dir, current_dir / 'Zipped_dir.zip')

How to pass Multiple Parameters from ajax call to MVC Controller

function final_submit1() {
    var city = $("#city").val();
    var airport = $("#airport").val();

    var vehicle = $("#vehicle").val();

    if(city && airport){
    $.ajax({
        type:"POST",
        cache:false,
        data:{"city": city,"airport": airport},
        url:'http://airportLimo/ajax-car-list', 
        success: function (html) {
             console.log(html);
          //$('#add').val('data sent');
          //$('#msg').html(html);
           $('#pprice').html("Price: $"+html);
        }
      });

    }  
}

Why would an Enum implement an Interface?

Here's one example (a similar/better one is found in Effective Java 2nd Edition):

public interface Operator {
    int apply (int a, int b);
}

public enum SimpleOperators implements Operator {
    PLUS { 
        int apply(int a, int b) { return a + b; }
    },
    MINUS { 
        int apply(int a, int b) { return a - b; }
    };
}

public enum ComplexOperators implements Operator {
    // can't think of an example right now :-/
}

Now to get a list of both the Simple + Complex Operators:

List<Operator> operators = new ArrayList<Operator>();

operators.addAll(Arrays.asList(SimpleOperators.values()));
operators.addAll(Arrays.asList(ComplexOperators.values()));

So here you use an interface to simulate extensible enums (which wouldn't be possible without using an interface).

how to update spyder on anaconda

In iOS,

  • Open Anaconda Navigator
  • Launch Spyder
  • Click on the tab "Consoles" (menu bar)
  • Then, "New Console"
  • Finally, in the console window, type conda update spyder

Your computer is going to start downloading and installing the new version. After finishing, just restart Spyder and that's it.

Regular Expression to match valid dates

This regex validates dates between 01-01-2000 and 12-31-2099 with matching separators.

^(0[1-9]|1[012])([- /.])(0[1-9]|[12][0-9]|3[01])\2(19|20)\d\d$

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How to center the content inside a linear layout?

I tried solutions mentioned here but It didn't help me. I mind the solution is layout_width have to use wrap_content as value.

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_weight="1" >

POST request with a simple string in body with Alamofire

func paramsFromJSON(json: String) -> [String : AnyObject]?
{
    let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
    var jsonDict: [ String : AnyObject]!
    do {
        jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
        return jsonDict
    } catch {
        print("JSON serialization failed:  \(error)")
        return nil
    }
}

let json = Mapper().toJSONString(loginJSON, prettyPrint: false)

Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)

How to get the stream key for twitch.tv

This may be an old thread but I came across it and figured that I would give a final answer.

The twitch api is json based and to recieve your stream key you need to authorize your app for use with the api. You do so under the connections tab within your profile on twitch.tv itself.. Down the bottom of said tab there is "register your app" or something similar. Register it and you'll get a client-id header for your get requests.

Now you need to attach your Oauthv2 key to your headers or as a param during the query to the following get request.

curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth ' \ -X GET https://api.twitch.tv/kraken/channel

documentataion here

As you can see in the documentation above, if you've done these two things, your stream key will be made available to you.

As I said - Sorry for the bump but some people do find it hard to read the twitch* api.

Hope that helps somebody in the future.

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

final

final can be used to mark a variable "unchangeable"

private final String name = "foo";  //the reference name can never change

final can also make a method not "overrideable"

public final String toString() {  return "NULL"; }

final can also make a class not "inheritable". i.e. the class can not be subclassed.

public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

finally

finally is used in a try/catch statement to execute code "always"

lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}

Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable

finalize

finalize is called when an object is garbage collected. You rarely need to override it. An example:

protected void finalize() {
  //free resources (e.g. unallocate memory)
  super.finalize();
}

PHP decoding and encoding json with unicode characters

$json = array('tag' => 'Odómetro'); // Original array
$json = json_encode($json); // {"Tag":"Od\u00f3metro"}
$json = json_decode($json); // Od\u00f3metro becomes  Odómetro
echo $json->{'tag'}; // Odómetro
echo utf8_decode($json->{'tag'}); // Odómetro

You were close, just use utf8_decode.

How can I check out a GitHub pull request with git?

Suppose your origin and upstream info is like below

   $ git remote -v
   origin  [email protected]:<yourname>/<repo_name>.git (fetch)
   origin  [email protected]:<yourname>/<repo_name>.git (push)
   upstream   [email protected]:<repo_owner>/<repo_name>.git (fetch)
   upstream   [email protected]:<repo_owner>/<repo_name>.git (push)

and your branch name is like

   <repo_owner>:<BranchName>

then

   git pull origin <BranchName>

shall do the job

How do you make a div follow as you scroll?

You can use the fixed CSS position property to accomplish this. There is a basic tutorial on this here.

EDIT: However, this approach is NOT supported in IE versions < IE7, and only in IE7 if it is in standards mode. This is discussed in a little more detail here.

There is also a hack, explained here, that shows how to accomplish fixed positioning in IE6 without affecting absolute positioning. What version of IE are you targeting your website for?

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How can I remove a button or make it invisible in Android?

IF you want to make invisible button, then use this:

<Button ... android:visibility="gone"/>

View.INVISIBLE:

Button will become transparent. But it taking space.

View.GONE

Button will be completely remove from the layout and we can add other widget in the place of removed button.

Python Matplotlib Y-Axis ticks on Right Side of Plot

Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:

import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()

It will show this:

enter image description here

Bootstrap Dropdown with Hover

You can use jQuery's hover function.

You just need to add the class open when the mouse enters and remove the class when the mouse leaves the dropdown.

Here's my code:

$(function(){
    $('.dropdown').hover(function() {
        $(this).addClass('open');
    },
    function() {
        $(this).removeClass('open');
    });
});

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Adding to this. If you use both INSERT IGNORE and ON DUPLICATE KEY UPDATE in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE clause itself causes a duplicate key error, that error will be ignored.

This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.

CREATE TABLE test 
 (id BIGINT (20) UNSIGNED AUTO_INCREMENT, 
  str VARCHAR(20), 
  PRIMARY KEY(id), 
  UNIQUE(str));

INSERT INTO test (str) VALUES('A'),('B');

/* duplicate key error caused not by the insert, 
but by the update: */
INSERT INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A'; 

/* duplicate key error is suppressed */
INSERT IGNORE INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A';

Python strptime() and timezones?

The datetime module documentation says:

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:

When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

Note that this doesn't work with %Z, so the case is important. See the following example:

In [1]: from datetime import datetime

In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')

In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None

In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')

In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00

Share Text on Facebook from Android App via ACTION_SEND

To make the Share work with the facebook app, you only need to have suply at least one link:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Wonderful search engine http://www.google.fr/");
startActivity(Intent.createChooser(intent, "Share with"));

This will show the correct sharing window but when you click on share, nothing happends (I also tried with the official Twitter App, it does not work).

The only way I found to make the Facebook app sharing work is to share only a link with no text:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "http://www.google.fr/");
startActivity(Intent.createChooser(intent, "Share with"));

It will show the following window and the Share button will work:

facebook share

Apparently it automatically takes an image and text from the link to populate the share.

If you want to share only text, you will have to use the facebook api: https://github.com/facebook/facebook-android-sdk

Default value for field in Django model

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

"Cloning" row or column vectors

One clean solution is to use NumPy's outer-product function with a vector of ones:

np.outer(np.ones(n), x)

gives n repeating rows. Switch the argument order to get repeating columns. To get an equal number of rows and columns you might do

np.outer(np.ones_like(x), x)

How to delete columns in a CSV file?

It depends on how you store the parsed CSV, but generally you want the del operator.

If you have an array of dicts:

input = [ {'day':01, 'month':04, 'year':2001, ...}, ... ]
for E in input: del E['year']

If you have an array of arrays:

input = [ [01, 04, 2001, ...],
          [...],
          ...
        ]
for E in input: del E[2]

MySQL - Trigger for updating same table after insert

This is how I update a row in the same table on insert

activationCode and email are rows in the table USER. On insert I don't specify a value for activationCode, it will be created on the fly by MySQL.

Change username with your MySQL username and db_name with your db name.

CREATE DEFINER=`username`@`localhost` 
       TRIGGER `db_name`.`user_BEFORE_INSERT` 
       BEFORE INSERT ON `user` 
       FOR EACH ROW
         BEGIN
            SET new.activationCode = MD5(new.email);
         END

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

Comparing two .jar files

Here is my script to do the process described by sje397:

    #!/bin/sh

    # Needed if running on Windows
    FIND="/usr/bin/find"
    DIFF="diff -r"

    # Extract the jar (war or ear)
    JAR_FILE1=$1
    JAR_FILE2=$2

    JAR_DIR=${PWD}          # to assign to a variable
    TEMP_DIR=$(mktemp -d)

    echo "Extracting jars in $TEMP_DIR"

    EXT_DIR1="${TEMP_DIR}/${JAR_FILE1%.*}"
    EXT_DIR2="${TEMP_DIR}/${JAR_FILE2%.*}"

    mkdir ${EXT_DIR1}
    cd ${EXT_DIR1}
    jar xf ${JAR_DIR}/${JAR_FILE1}
    jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
    cd ..

    mkdir ${EXT_DIR2}
    cd ${EXT_DIR2}
    jar xf ${JAR_DIR}/${JAR_FILE2}
    jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
    cd ..

    # remove class files so the diff is clean
    ${FIND} ${TEMP_DIR} -name '*.class' | xargs rm

    # diff recursively 
    ${DIFF} ${EXT_DIR1} ${EXT_DIR2}

I can run it on Windows using GIT for Windows. Just open a command prompt. Run bash and then execute the script from there.

Removing items from a ListBox in VB.net

If you only want to clear the list box, you should use the Clear (winforms | wpf | asp.net) method:

ListBox2.Items.Clear()

Getting title and meta tags from external website

My solution (adapted from parts of cronoklee's & shamittomar's posts) so I can call it from anywhere and get a JSON return. Can be easily parsed into any content.

<?php
header('Content-type: application/json; charset=UTF-8');

if (!empty($_GET['url']))
{
    file_get_contents_curl($_GET['url']);
}
else
{
    echo "No Valid URL Provided.";
}


function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    echo json_encode(getSiteOG($data), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function getSiteOG( $OGdata){
    $doc = new DOMDocument();
    @$doc->loadHTML($OGdata);
    $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;

    foreach ($doc->getElementsByTagName('meta') as $m){
        $tag = $m->getAttribute('name') ?: $m->getAttribute('property');
        if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = utf8_decode($m->getAttribute('content'));

    }

    return $res;
}
?>

Get values from a listbox on a sheet

Take selected value:

worksheet name = ordls
form control list box name = DEPDB1

selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)

Create a BufferedImage from file and make it TYPE_INT_ARGB

BufferedImage in = ImageIO.read(img);

BufferedImage newImage = new BufferedImage(
    in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();

Oracle - Insert New Row with Auto Incremental ID

There is no built-in auto_increment in Oracle.

You need to use sequences and triggers.

Read here how to do it right. (Step-by-step how-to for "Creating auto-increment columns in Oracle")

How to check if an email address exists without sending an email?

Some issues:

  1. I'm sure some SMTP servers will let you know immediately if an address you give them does not exist, but some won't as a privacy measure. They'll just accept whatever addresses you give them and silently ignore the ones that don't exist.
  2. As the article says, if you do this too often with some servers, they will blacklist you.
  3. For some SMTP servers (like gmail), you need to use SSL in order to do anything. This is only true when using gmail's SMTP server to send email.

How do I set the selected item in a comboBox to match my string using C#?

All methods, tricks, and lines of code setting ComboBox item will not work until the ComboBox has a parent.

Generate a random date between two other dates

from random import randrange
from datetime import timedelta

def random_date(start, end):
    """
    This function will return a random datetime between two datetime 
    objects.
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last line's calculation.

example run:

from datetime import datetime

d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))

output:

2008-12-04 01:50:17

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Adding to the thread, there's a new console in town called babun, im running tmux in it without a problem. lets you run bash or the zsh.

click here for github

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

What's the difference between "super()" and "super(props)" in React when using es6 classes?

Dan Abramov wrote an article on this topic:

Why Do We Write super(props)?

And the gist of it is that it's helpful to have a habit of passing it to avoid this scenario, that honestly, I don't see it unlikely to happen:

// Inside React
class Component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

// Inside your code
class Button extends React.Component {
  constructor(props) {
    super(); //  We forgot to pass props
    console.log(props);      // ? {}
    console.log(this.props); //  undefined 
  }
  // ...
}

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Simplest - and I changed the checkbox class to ID as well:

_x000D_
_x000D_
$(function() {_x000D_
  $("#coupon_question").on("click",function() {_x000D_
    $(".answer").toggle(this.checked);_x000D_
  });_x000D_
});
_x000D_
.answer { display:none }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<fieldset class="question">_x000D_
  <label for="coupon_question">Do you have a coupon?</label>_x000D_
  <input id="coupon_question" type="checkbox" name="coupon_question" value="1" />_x000D_
  <span class="item-text">Yes</span>_x000D_
</fieldset>_x000D_
_x000D_
<fieldset class="answer">_x000D_
  <label for="coupon_field">Your coupon:</label>_x000D_
  <input type="text" name="coupon_field" id="coupon_field" />_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

How to validate GUID is a GUID

Use GUID constructor standard functionality

Public Function IsValid(pString As String) As Boolean

    Try
        Dim mGuid As New Guid(pString)
    Catch ex As Exception
        Return False
    End Try
    Return True

End Function

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

Using NotNull Annotation in method argument

SO @NotNull just is a tag...If you want to validate it, then you must use something like hibernate validator jsr 303

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
 Set<ConstraintViolation<List<Searching>> violations = validator.validate(searchingList);

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Is there a way to programmatically scroll a scroll view to a specific edit text?

My EditText was nested several layers inside my ScrollView, which itself isn't the layout's root view. Because getTop() and getBottom() were seeming to report the coordinates within it's containing view, I had it compute the distance from the top of the ScrollView to the top of the EditText by iterating through the parents of the EditText.

// Scroll the view so that the touched editText is near the top of the scroll view
new Thread(new Runnable()
{
    @Override
    public
    void run ()
    {
        // Make it feel like a two step process
        Utils.sleep(333);

        // Determine where to set the scroll-to to by measuring the distance from the top of the scroll view
        // to the control to focus on by summing the "top" position of each view in the hierarchy.
        int yDistanceToControlsView = 0;
        View parentView = (View) m_editTextControl.getParent();
        while (true)
        {
            if (parentView.equals(scrollView))
            {
                break;
            }
            yDistanceToControlsView += parentView.getTop();
            parentView = (View) parentView.getParent();
        }

        // Compute the final position value for the top and bottom of the control in the scroll view.
        final int topInScrollView = yDistanceToControlsView + m_editTextControl.getTop();
        final int bottomInScrollView = yDistanceToControlsView + m_editTextControl.getBottom();

        // Post the scroll action to happen on the scrollView with the UI thread.
        scrollView.post(new Runnable()
        {
            @Override
            public void run()
            {
                int height =m_editTextControl.getHeight();
                scrollView.smoothScrollTo(0, ((topInScrollView + bottomInScrollView) / 2) - height);
                m_editTextControl.requestFocus();
            }
        });
    }
}).start();

Index of element in NumPy array

You can use the function numpy.nonzero(), or the nonzero() method of an array

import numpy as np

A = np.array([[2,4],
          [6,2]])
index= np.nonzero(A>1)
       OR
(A>1).nonzero()

Output:

(array([0, 1]), array([1, 0]))

First array in output depicts the row index and second array depicts the corresponding column index.

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Just answering the second part of your question about getting the name of the sheet where a table is:

Dim name as String

name = Range("Table1").Worksheet.Name

Edit:

To make things more clear: someone suggested that to use Range on a Sheet object. In this case, you need not; the Range where the table lives can be obtained using the table's name; this name is available throughout the book. So, calling Range alone works well.

jQuery trigger file input

Actually, I found out a really easy method for this, which is:

$('#fileinput').show().trigger('click').hide();   

This way, your file input field can have the css property display on none and still win the trade :)

Rails where condition using NOT NIL

For Rails4:

So, what you're wanting is an inner join, so you really should just use the joins predicate:

  Foo.joins(:bar)

  Select * from Foo Inner Join Bars ...

But, for the record, if you want a "NOT NULL" condition simply use the not predicate:

Foo.includes(:bar).where.not(bars: {id: nil})

Select * from Foo Left Outer Join Bars on .. WHERE bars.id IS NOT NULL

Note that this syntax reports a deprecation (it talks about a string SQL snippet, but I guess the hash condition is changed to string in the parser?), so be sure to add the references to the end:

Foo.includes(:bar).where.not(bars: {id: nil}).references(:bar)

DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: ....) that are referenced in a string SQL snippet. For example:

Post.includes(:comments).where("comments.title = 'foo'")

Currently, Active Record recognizes the table in the string, and knows to JOIN the comments table to the query, rather than loading comments in a separate query. However, doing this without writing a full-blown SQL parser is inherently flawed. Since we don't want to write an SQL parser, we are removing this functionality. From now on, you must explicitly tell Active Record when you are referencing a table from a string:

Post.includes(:comments).where("comments.title = 'foo'").references(:comments)

Why is my CSS style not being applied?

There could be an error earlier in the CSS file that is causing your (correct) CSS to not work.

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I ran into the same problem

Creating network "schemaregistry1_default" with the default driver
ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network

and nothing helped until I turned off the Cisco VPN. after that docker-compose up worked

Trying to SSH into an Amazon Ec2 instance - permission error

Checklist:

  1. Are you using the right private key .pem file?

  2. Are its permissions set correctly? (My Amazon-brand AMIs work with 644, but Red hat must be at least 600 or 400. Don't know about Ubuntu.)

  3. Are you using the right username in your ssh line? Amazon-branded = "ec2-user", Red Hat = "root", Ubuntu = "ubuntu". User can be specified as "ssh -i pem usename@hostname" OR "ssh -l username -i pem hostname"

ORA-01031: insufficient privileges when selecting view

Let me make a recap.

When you build a view containing object of different owners, those other owners have to grant "with grant option" to the owner of the view. So, the view owner can grant to other users or schemas....

Example: User_a is the owner of a table called mine_a User_b is the owner of a table called yours_b

Let's say user_b wants to create a view with a join of mine_a and yours_b

For the view to work fine, user_a has to give "grant select on mine_a to user_b with grant option"

Then user_b can grant select on that view to everybody.

How to set cookies in laravel 5 independently inside controller

You are going right way my friend.Now if you want retrive cookie anywhere in project just put this code $val = Cookie::get('COOKIE_NAME'); That's it! For more information how can this done click here

Line Break in XML?

If you use CDATA, you could embed the line breaks directly into the XML I think. Example:

<song>
    <title>Song Title</title>
    <lyric><![CDATA[Line 1
Line 2
Line 3]]></lyric>
</song>

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How to print the value of a Tensor object in TensorFlow?

No, you can not see the content of the tensor without running the graph (doing session.run()). The only things you can see are:

  • the dimensionality of the tensor (but I assume it is not hard to calculate it for the list of the operations that TF has)
  • type of the operation that will be used to generate the tensor (transpose_1:0, random_uniform:0)
  • type of elements in the tensor (float32)

I have not found this in documentation, but I believe that the values of the variables (and some of the constants are not calculated at the time of assignment).


Take a look at this example:

import tensorflow as tf
from datetime import datetime
dim = 7000

The first example where I just initiate a constant Tensor of random numbers run approximately the same time irrespectibly of dim (0:00:00.003261)

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
print datetime.now() - startTime

In the second case, where the constant is actually gets evaluated and the values are assigned, the time clearly depends on dim (0:00:01.244642)

startTime = datetime.now()
m1 = tf.truncated_normal([dim, dim], mean=0.0, stddev=0.02, dtype=tf.float32, seed=1)
sess = tf.Session()
sess.run(m1)
print datetime.now() - startTime

And you can make it more clear by calculating something (d = tf.matrix_determinant(m1), keeping in mind that the time will run in O(dim^2.8))

P.S. I found were it is explained in documentation:

A Tensor object is a symbolic handle to the result of an operation, but does not actually hold the values of the operation's output.

react-native :app:installDebug FAILED

on my android device, the problem was about the previous build versions of the application that I had installed on my phone before. the following steps solved my problem:

  1. removing any previous build of the application, including debugging version and signed apk version

  2. on the root directory of your project, run (on windows):

    cd android

    .\gradlew clean

    cd ..

    npm cache clean --force

  3. reboot your android device

hope this help you too.

How to show math equations in general github's markdown(not github's blog)

Mathcha is a sophisticated mathematics editor, but it can be used to render individual equations and save them as pure html, which you can then add to your documents as inline html OR you can save as SVG and insert as an image. https://www.mathcha.io/

Output an Image in PHP

You can use header to send the right Content-type :

header('Content-Type: ' . $type);

And readfile to output the content of the image :

readfile($file);


And maybe (probably not necessary, but, just in case) you'll have to send the Content-Length header too :

header('Content-Length: ' . filesize($file));


Note : make sure you don't output anything else than your image data (no white space, for instance), or it will no longer be a valid image.

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

Show div on scrollDown after 800px

You can also, do this.

$(window).on("scroll", function () {
   if ($(this).scrollTop() > 800) {
      #code here
   } else {
      #code here
   }
});

Get full path of a file with FileUpload Control

Check this post under FileUpload Control

Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.

Its an option under Internet security that can be enabled

How to "EXPIRE" the "HSET" child key in redis?

You could use the Redis Keyspace Notifications by using psubscribe and "__keyevent@<DB-INDEX>__:expired".

With that, each time that a key will expire, you will get a message published on your redis connection.

Regarding your question basically you create a temporary "normal" key using set with an expiration time in s/ms. It should match the name of the key that you wish to delete in your set.

As your temporary key will be published to your redis connection holding the "__keyevent@0__:expired" when it expired, you can easily delete your key from your original set as the message will have the name of the key.

A simple example in practice on that page : https://medium.com/@micah1powell/using-redis-keyspace-notifications-for-a-reminder-service-with-node-c05047befec3

doc : https://redis.io/topics/notifications ( look for the flag xE)

Make REST API call in Swift

Swift 5 & 4

let params = ["username":"john", "password":"123456"] as Dictionary<String, String>

var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
    print(response!)
    do {
        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
        print(json)
    } catch {
        print("error")
    }
})

task.resume()

Hide div if screen is smaller than a certain width

The problem with your code seems to be the elseif-statement which should be else if (Notice the space).

I rewrote and simplyfied the code to this:

$(document).ready(function () {

    if (screen.width < 1024) {
        $(".yourClass").hide();
    }
    else {

        $(".yourClass").show();
    }

});

How do you print in a Go test using the "testing" package?

For testing sometimes I do

fmt.Fprintln(os.Stdout, "hello")

Also, you can print to:

fmt.Fprintln(os.Stderr, "hello)

Django Forms: if not valid, show form with error message

@AamirAdnan's answer missing field.label; the other way to show the errors in few lines.

{% if form.errors %}
    <!-- Error messaging -->
    <div id="errors">
        <div class="inner">
            <p>There were some errors in the information you entered. Please correct the following:</p>
            <ul>
                {% for field in form %}
                    {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
    <!-- /Error messaging -->
{% endif %}

How do I call a non-static method from a static method in C#?

You have to create an instance of that class within the static method and then call it.

For example like this:

public class MyClass
{
   private void data1()
   {
   }
   private static void data2()
   {
     MyClass c = new MyClass();
     c.data1();
   }
}

How do I get JSON data from RESTful service using Python?

You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:

import httplib2 as http
import json

try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=UTF-8'
}

uri = 'http://yourservice.com'
path = '/path/to/resource/'

target = urlparse(uri+path)
method = 'GET'
body = ''

h = http.Http()

# If you need authentication some example:
if auth:
    h.add_credentials(auth.user, auth.password)

response, content = h.request(
        target.geturl(),
        method,
        body,
        headers)

# assume that content is a json reply
# parse content with the json module
data = json.loads(content)

remove objects from array by object property

findIndex works for modern browsers:

var myArr = [{id:'a'},{id:'myid'},{id:'c'}];
var index = myArr.findIndex(function(o){
  return o.id === 'myid';
})
if (index !== -1) myArr.splice(index, 1);

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

When you copy dependency from maven repository there is:

<scope>test</scope>

Try to remove it from dependencies in pom.xml like this.

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

This works for me. I hope it would be helpful for someone else.

Best way to "negate" an instanceof

Usually you don't want just an if but an else clause as well.

if(!(str instanceof String)) { /* do Something */ } 
else { /* do something else */ }

can be written as

if(str instanceof String) { /* do Something else */ } 
else { /* do something */ }

Or you can write the code so you don't need to know if its a String or not. e.g.

if(!(str instanceof String)) { str = str.toString(); } 

can be written as

str = str.toString();

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

c++ exception : throwing std::string

All these work:

#include <iostream>
using namespace std;

//Good, because manual memory management isn't needed and this uses
//less heap memory (or no heap memory) so this is safer if
//used in a low memory situation
void f() { throw string("foo"); }

//Valid, but avoid manual memory management if there's no reason to use it
void g() { throw new string("foo"); }

//Best.  Just a pointer to a string literal, so no allocation is needed,
//saving on cleanup, and removing a chance for an allocation to fail.
void h() { throw "foo"; }

int main() {
  try { f(); } catch (string s) { cout << s << endl; }
  try { g(); } catch (string* s) { cout << *s << endl; delete s; }
  try { h(); } catch (const char* s) { cout << s << endl; }
  return 0;
}

You should prefer h to f to g. Note that in the least preferable option you need to free the memory explicitly.

Git and nasty "error: cannot lock existing info/refs fatal"

In my case, it was connected with the branch name that I had already created.

To fix the issue I've created a branch with the name that for certain shouldn't exist, like:

git checkout -b some_unknown_branch

Then I've cleared all my other branches(not active) because they were just unnecessary garbage.

git branch | grep -v \* | grep -v master | xargs git branch -D

and then renamed my current branch with the name that I've intended, like:

git checkout -m my_desired_branch_name

How do I configure Maven for offline development?

Maven needs the dependencies in your local repository. The easiest way to get them is with internet access (or harder using other solutions provided here).

So assumed that you can get temporarily internet access you can prepare to go offline using the maven-dependency-plugin with its dependency:go-offline goal. This will download all your project dependencies to your local repository (of course changes in the dependencies / plugins will require new internet / central repository access).

Number of times a particular character appears in a string

Look at the length of the string after replacing the sequence

declare @s varchar(10) = 'aabaacaa'
select len(@s) - len(replace(@s, 'a', ''))
>>6

"commence before first target. Stop." error

This could also caused by mismatching brace/parenthesis.

$(TARGET}:
    do_something

Just use parenthesises and you'll be fine.

How can I escape latex code received through user input?

Python’s raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. “raw”.

This means the interpreting happens somewhere else. But if you know that it happens, why not escape the backslashes for whatever is interpreting it?

s = s.replace("\\", "\\\\")

(Note that you can't do r"\" as “a raw string cannot end in a single backslash”, but I could have used r"\\" as well for the second argument.)

If that doesn’t work, your user input is for some arcane reason interpreting the backslashes, so you’ll need a way to tell it to stop that.

How do I ZIP a file in C#, using no 3rd-party APIs?

I was in the same situation, wanting to .NET instead of a third party library. As another poster mentioned above, simply using the ZipPackage class (introduced in .NET 3.5) is not quite enough. There is an additional file that MUST be included in the archive in order for the ZipPackage to work. If this file is added, then the resulting ZIP package can be opened directly from Windows Explorer - no problem.

All you have to do is add the [Content_Types].xml file to the root of the archive with a "Default" node for every file extension you wish to include. Once added, I could browse the package from Windows Explorer or programmatically decompress and read its contents.

More information on the [Content_Types].xml file can be found here: http://msdn.microsoft.com/en-us/magazine/cc163372.aspx

Here is a sample of the [Content_Types].xml (must be named exactly) file:

<?xml version="1.0" encoding="utf-8" ?>
<Types xmlns=
    "http://schemas.openxmlformats.org/package/2006/content-types">
  <Default Extension="xml" ContentType="text/xml" /> 
  <Default Extension="htm" ContentType="text/html" /> 
  <Default Extension="html" ContentType="text/html" /> 
  <Default Extension="rels" ContentType=
    "application/vnd.openxmlformats-package.relationships+xml" /> 
  <Default Extension="jpg" ContentType="image/jpeg" /> 
  <Default Extension="png" ContentType="image/png" /> 
  <Default Extension="css" ContentType="text/css" /> 
</Types>

And the C# for creating a ZIP file:

var zipFilePath = "c:\\myfile.zip"; 
var tempFolderPath = "c:\\unzipped"; 

    using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read)) 
    { 
        foreach (PackagePart part in package.GetParts()) 
        { 
            var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/'))); 
            var targetDir = target.Remove(target.LastIndexOf('\\')); 

            if (!Directory.Exists(targetDir)) 
                Directory.CreateDirectory(targetDir); 

            using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read)) 
            { 
                source.CopyTo(File.OpenWrite(target)); 
            } 
        } 
    } 

Note:

Converting integer to binary in python

You can use just:

"{0:b}".format(n)

In my opinion this is the easiest way!

Call asynchronous method in constructor?

You could put the async calls in a separate method and call that method in the constructor. Although, this may lead to a situation where some variable values not being available at the time you expect them.

 public NewTravelPageVM(){
   GetVenues();              
 }

 async void  GetVenues(){
   var locator = CrossGeolocator.Current;
   var position = await locator.GetPositionAsync();
   Venues = await Venue.GetVenues(position.Latitude, position.Longitude);
 }

Converting 'ArrayList<String> to 'String[]' in Java

In Java 11, we can use the Collection.toArray(generator) method. The following code will create a new array of strings:

List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)

from java.base's java.util.Collection.toArray().

How to set the title of UIButton as left alignment?

UIButton *btn;
btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

Jquery Ajax Posting json to webservice

I have query,

$("#login-button").click(function(e){ alert("hiii");

        var username = $("#username-field").val();
        var password = $("#username-field").val();

        alert(username);
        alert("password" + password);



        var markers = { "userName" : "admin","password" : "admin123"};
        $.ajax({
            type: "POST",
            url: url,
            // The key needs to match your method's input parameter (case-sensitive).
            data: JSON.stringify(markers),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){alert("got the data"+data);},
            failure: function(errMsg) {
                alert(errMsg);
            }
        });

    });

I'm posting the the login details in json and getting a string as "Success",but I'm not getting the response.

Set Response Status Code

As written before, but for beginner like me don't forget to include the return.

$this->response->statusCode(200);
return $this->response;

Switch/toggle div (jQuery)

This is how I toggle two divs at the same time:

$('#login-form, #recover-password').toggle();

It works!

How to convert JSON string to array

You can change a string to JSON as follows and you can also trim, strip on string if wanted,

$str     = '[{"id":1, "value":"Comfort Stretch"}]';
//here is JSON object
$filters = json_decode($str);

foreach($filters as $obj){
   $filter_id[] = $obj->id;
}

//here is your array from that JSON
$filter_id;

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

How to start new activity on button click

Emmanuel,

I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);

Why javascript getTime() is not a function?

To use this function/method,you need an instance of the class Date .

This method is always used in conjunction with a Date object.

See the code below :

var d = new Date();
d.getTime();

Link : http://www.w3schools.com/jsref/jsref_getTime.asp

CSS /JS to prevent dragging of ghost image?

You can set the draggable attribute to false in either the markup or JavaScript code.

_x000D_
_x000D_
// As a jQuery method: $('#myImage').attr('draggable', false);_x000D_
document.getElementById('myImage').setAttribute('draggable', false);
_x000D_
<img id="myImage" src="http://placehold.it/150x150">
_x000D_
_x000D_
_x000D_

Use formula in custom calculated field in Pivot Table

Some of it is possible, specifically accessing subtotals:

"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)

enter image description here

  • And make sure the field in question is a number field that can be summed, it does not work for text fields for which only count is normally informative.

Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/

About catching ANY exception

try:
    whatever()
except:
    # this will catch any exception or error

It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.

Can I override and overload static methods in Java?

You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.

Make element fixed on scroll

Here you go, no frameworks, short and simple:

var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;

window.addEventListener('scroll', function(){
    if (document.documentElement.scrollTop > elTop){
        el.style.position = 'fixed';
        el.style.top = '0px';
    }
    else
    {
        el.style.position = 'static';
        el.style.top = 'auto';
    }
});

What is the PostgreSQL equivalent for ISNULL()

Create the following function

CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
    "is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'

And it'll work.

You may to create different versions with different parameter types.

Basic calculator in Java

import java.util.Scanner;
public class JavaApplication1 {


    public static void main(String[] args) {

         int x,
         int y;

         Scanner input=new Scanner(System.in);
         System.out.println("Enter Number 1");
         x=input.nextInt();
         System.out.println("Enter Number 2");
         y=input.nextInt();

         System.out.println("Please enter operation + - / or *");
         Scanner op=new Scanner(System.in);
         String operation = op.next();

         if (operation.equals("+")){
             System.out.println("Your Answer: " + (x+y));
         }
         if (operation.equals("-")){
             System.out.println("Your Answer: "+ (x-y));
         }
         if (operation.equals("/")){
             System.out.println("Your Answer: "+ (x/y));
         }
         if (operation.equals("*")){
            System.out.println("Your Answer: "+ (x*y));
         }
    }

}

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

After falling victim to this problem on centOS after updating php to php5.6 I found a solution that worked for me.

Get the correct directory for your certs to be placed by default with this

php -r 'print_r(openssl_get_cert_locations()["default_cert_file"]);'

Then use this to get the cert and put it in the default location found from the code above

wget http://curl.haxx.se/ca/cacert.pem -O <default location>

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

Unicode via CSS :before

Fileformat.info is a pretty good reference for this stuff. In your case, it's already in hex, so the hex value is f066. So you'd do:

content: "\f066";

constant pointer vs pointer on a constant value

To parse complicated types, you start at the variable, go left, and spiral outwards. If there aren't any arrays or functions to worry about (because these sit to the right of the variable name) this becomes a case of reading from right-to-left.

So with char *const a; you have a, which is a const pointer (*) to a char. In other words you can change the char which a is pointing at, but you can't make a point at anything different.

Conversely with const char* b; you have b, which is a pointer (*) to a char which is const. You can make b point at any char you like, but you cannot change the value of that char using *b = ...;.

You can also of course have both flavours of const-ness at one time: const char *const c;.

Retrieve CPU usage and memory usage of a single process on Linux?

This is a nice trick to follow one or more programs in real time while also watching some other tool's output: watch "top -bn1 -p$(pidof foo),$(pidof bar); tool"

Turn Pandas Multi-Index into column

This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

                         value
Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34 

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

                           value
Trial    measurement       

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34 

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

for-in statement

In Typescript 1.5 and later, you can use for..of as opposed to for..in

var numbers = [1, 2, 3];

for (var number of numbers) {
    console.log(number);
}

printing all contents of array in C#

I upvoted the extension method answer by Matthew Watson, but if you're migrating/visiting coming from Python, you may find such a method useful:

class Utils
{
    static void dump<T>(IEnumerable<T> list, string glue="\n")
    {
        Console.WriteLine(string.Join(glue, list.Select(x => x.ToString())));
    }
}

-> this will print any collection using the separator provided. It's quite limited (nested collections?).

For a script (i.e. a C# console application which only contains Program.cs, and most things happen in Program.Main) - this may be just fine.

`IF` statement with 3 possible answers each based on 3 different ranges

=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))

Explanation:

=IF(X2>=85,                  'If the value is in the highest bracket
      0.559,                 'Use the appropriate number
      IF(X2>=80,             'Otherwise, if the number is in the next highest bracket
           0.327,            'Use the appropriate number
           IF(X2>=75,        'Otherwise, if the number is in the next highest bracket
              0.255,         'Use the appropriate number
              -1             'Otherwise, we're not in any of the ranges (Error)
             )
        )
   )

Find nginx version?

Try running command 'whereis nginx'. It will give you the correct path of the nginx installation, in my case nginx is installed in '/usr/local/sbin', so I need to check if this path exists in output of command 'echo $PATH'. If you don't find the path in the output of this command, then you can add this.

Suppose the output of my 'echo $PATH' command is this:

  ~$ echo $PATH
/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin

Then I can append the path '/usr/local/sbin' in $PATH by following command:

~$ echo 'export PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/nginx/sbin"' >> $HOME/.bashrc

Please check your nginx installation path may differ from mine, but the steps for adding them are same.

How to add Class in <li> using wp_nav_menu() in Wordpress?

No need to create custom walker. Just use additional argument and set filter for nav_menu_css_class.

For example:

$args = array(
    'container'     => '',
    'theme_location'=> 'your-theme-loc',
    'depth'         => 1,
    'fallback_cb'   => false,
    'add_li_class'  => 'your-class-name1 your-class-name-2'
    );
wp_nav_menu($args);

Notice the new 'add_li_class' argument.

And set the filter on functions.php

function add_additional_class_on_li($classes, $item, $args) {
    if(isset($args->add_li_class)) {
        $classes[] = $args->add_li_class;
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

How to generate a random number in C++?

Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it's perfectly possible to get repeating numbers in a random sequence.

Try some C++11 features for better distribution:

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

See this question/answer for more info on C++11 random numbers. The above isn't the only way to do this, but is one way.

Property getters and setters

I don't know if it is good practice but you can do something like this:

class test_ancestor {
    var prop: Int = 0
}


class test: test_ancestor {
    override var prop: Int {
        get {
            return super.prop // reaching ancestor prop
        }
        set {
            super.prop = newValue * 2
        }
    }
}

var test_instance = test()
test_instance.prop = 10

print(test_instance.prop) // 20

Read more

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

Foreach value from POST from form

i wouldn't do it this way

I'd use name arrays in the form elements

so i'd get the layout

$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';

then you could do an array slice to get the amount you need

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

When stride is 1 (more typical with convolution than pooling), we can think of the following distinction:

  • "SAME": output size is the same as input size. This requires the filter window to slip outside input map, hence the need to pad.
  • "VALID": Filter window stays at valid position inside input map, so output size shrinks by filter_size - 1. No padding occurs.

Looping through list items with jquery

Try this:

listItems = $("#productList").find("li").each(function(){
   var product = $(this);
   // rest of code.
});

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

Get all messages from Whatsapp

You can get access to the WhatsApp data base located on the SD card only as a root user I think. if you open "\data\data\com.whatsapp" you will see that "databases" is linked to "\firstboot\sqlite\com.whatsapp\"

Convert Xml to DataTable

You can use this code(Recommended)

 MemoryStream objMS = new MemoryStream();
 DataTable oDT = new DataTable();//Your DataTable which you want to convert
 oDT.WriteXml(objMS);
 objMS.Position = 0;
 XPathDocument result = new XPathDocument(objMS);

This is another way but first ex. is recommended

StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try like this...

select CONVERT (varchar(10), getdate(), 103) AS [DD/MM/YYYY]

For more info : http://www.sql-server-helper.com/tips/date-formats.aspx

What is the difference between procedural programming and functional programming?

One thing I hadn't seen really emphasized here is that modern functional languages such as Haskell really more on first class functions for flow control than explicit recursion. You don't need to define factorial recursively in Haskell, as was done above. I think something like

fac n = foldr (*) 1 [1..n]

is a perfectly idiomatic construction, and much closer in spirit to using a loop than to using explicit recursion.

How to define a two-dimensional array?

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)] 

You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

java.lang.IllegalAccessError: tried to access method

I was getting this error on a Spring Boot application where a @RestController ApplicationInfoResource had a nested class ApplicationInfo.

It seems the Spring Boot Dev Tools was using a different class loader.

The exception I was getting

2017-05-01 17:47:39.588 WARN 1516 --- [nio-8080-exec-9] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.IllegalAccessError: tried to access class com.gt.web.rest.ApplicationInfo from class com.gt.web.rest.ApplicationInfoResource$$EnhancerBySpringCGLIB$$59ce500c

Solution

I moved the nested class ApplicationInfo to a separate .java file and got rid of the problem.

Java simple code: java.net.SocketException: Unexpected end of file from server

Most likely the headers you are setting is incorrect or not acceptable.

Example: connnection.setRequestProperty("content-type", "application/json");

How do I install g++ for Fedora?

Just make a sample 'Hello World' Program and try to compile it using "g++ sam.cpp" in terminal, and it will ask you if you wish to download the g++ package. Press y to install.

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

I had the mysql jdbc library in both $CATALINA_HOME/lib and WEB-INF/lib, still i got this error . I needed Class.forName("com.mysql.jdbc.Driver"); to make it work.

How to convert / cast long to String?

1.

long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);

//convert string to long
date = Long.valueOf(str);

2.

 //convert long to string just concat long with empty string
 String str = ""+date;
//convert string to long

date = Long.valueOf(str);

C# using streams

Stream is just an abstraction (or a wrapper) over a physical stream of bytes. This physical stream is called the base stream. So there is always a base stream over which a stream wrapper is created and thus the wrapper is named after the base stream type ie FileStream, MemoryStream etc.

The advantage of the stream wrapper is that you get a unified api to interact with streams of any underlying type usb, file etc.

Why would you treat data as stream - because data chunks are loaded on-demand, we can inspect/process the data as chunks rather than loading the entire data into memory. This is how most of the programs deal with big files, for eg encrypting an OS image file.

What is the bit size of long on 64-bit Windows?

This article on MSDN references a number of type aliases (available on Windows) that are a bit more explicit with respect to their width:

http://msdn.microsoft.com/en-us/library/aa505945.aspx

For instance, although you can use ULONGLONG to reference a 64-bit unsigned integral value, you can also use UINT64. (The same goes for ULONG and UINT32.) Perhaps these will be a bit clearer?

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

.apply() takes in a function as the first parameter; pass in the label_race function as so:

df['race_label'] = df.apply(label_race, axis=1)

You don't need to make a lambda function to pass in a function.

Is there possibility of sum of ArrayList without looping

Then write it yourself:

public int sum(List<Integer> list) {
     int sum = 0; 

     for (int i : list)
         sum = sum + i;

     return sum;
}

What do the terms "CPU bound" and "I/O bound" mean?

CPU Bound means the rate at which process progresses is limited by the speed of the CPU. A task that performs calculations on a small set of numbers, for example multiplying small matrices, is likely to be CPU bound.

I/O Bound means the rate at which a process progresses is limited by the speed of the I/O subsystem. A task that processes data from disk, for example, counting the number of lines in a file is likely to be I/O bound.

Memory bound means the rate at which a process progresses is limited by the amount memory available and the speed of that memory access. A task that processes large amounts of in memory data, for example multiplying large matrices, is likely to be Memory Bound.

Cache bound means the rate at which a process progress is limited by the amount and speed of the cache available. A task that simply processes more data than fits in the cache will be cache bound.

I/O Bound would be slower than Memory Bound would be slower than Cache Bound would be slower than CPU Bound.

The solution to being I/O bound isn't necessarily to get more Memory. In some situations, the access algorithm could be designed around the I/O, Memory or Cache limitations. See Cache Oblivious Algorithms.

How to check if a word is an English word with Python?

For a faster NLTK-based solution you could hash the set of words to avoid a linear search.

from nltk.corpus import words as nltk_words
def is_english_word(word):
    # creation of this dictionary would be done outside of 
    #     the function because you only need to do it once.
    dictionary = dict.fromkeys(nltk_words.words(), None)
    try:
        x = dictionary[word]
        return True
    except KeyError:
        return False

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

Convert string to Date in java

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

Efficient evaluation of a function at every cell of a NumPy array

A similar question is: Mapping a NumPy array in place. If you can find a ufunc for your f(), then you should use the out parameter.

Sorting dropdown alphabetically in AngularJS

Angular has an orderBy filter that can be used like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>

See this fiddle for an example.

It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>

Relational Database Design Patterns?

AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)

I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).

Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.

Write to .txt file?

FILE *fp;
char* str = "string";
int x = 10;

fp=fopen("test.txt", "w");
if(fp == NULL)
    exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

Mysql 1050 Error "Table already exists" when in fact, it does not

I had the same problem at Mac OS X and MySQL 5.1.40. I used eclipse to edit my SQL script and than I tried MySQLWorkbench 5.2.28. Probably it converted newline characters to Mac format. I had no idea about what's wrong with my script until I commented out the first line in file. After this this script was interpreted by mysql as a one single comment. I used build-in TextEdit Mac application to fix this. After line-breaks was converted to the correct format, the error 1050 gone.

Update for Eclipse users:

To set up default ending for new files created, across the entire workspace:

Window -> Preferences -> General -> Workspace -> New text file line delimiter.

To convert existing files, open file for editing and for the currently edited file, go to the menu:

File -> Convert Line Delimiters To

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

How do I center align horizontal <UL> menu?

I used the display:inline-block property: the solution consist in use a wrapper with fixed width. Inside, the ul block with the inline-block for display. Using this, the ul just take the width for the real content! and finally margin: 0 auto, to center this inline-block =)

/*ul wrapper*/
.gallery_wrapper{
        width:          958px;
        margin:         0 auto;
  }
/*ul list*/
ul.gallery_carrousel{
        display:        inline-block;
        margin:         0 auto;
}
.contenido_secundario li{
        float:          left;
}

URLEncoder not able to translate space character

Although quite old, nevertheless a quick response:

Spring provides UriUtils - with this you can specify how to encoded and which part is it related from an URI, e.g.

encodePathSegment
encodePort
encodeFragment
encodeUriVariables
....

I use them cause we already using Spring, i.e. no additonal library is required!

How to delete a file or folder?

My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.

In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...

It also wraps shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

What's the easiest way to escape HTML in Python?

cgi.escape extended

This version improves cgi.escape. It also preserves whitespace and newlines. Returns a unicode string.

def escape_html(text):
    """escape strings for display in HTML"""
    return cgi.escape(text, quote=True).\
           replace(u'\n', u'<br />').\
           replace(u'\t', u'&emsp;').\
           replace(u'  ', u' &nbsp;')

for example

>>> escape_html('<foo>\nfoo\t"bar"')
u'&lt;foo&gt;<br />foo&emsp;&quot;bar&quot;'

How to set $_GET variable

I know this is an old thread, but I wanted to post my 2 cents...

Using Javascript you can achieve this without using $_POST, and thus avoid reloading the page..

<script>
function ButtonPressed()
{
window.location='index.php?view=next'; //this will set $_GET['view']='next'
}
</script>

<button type='button' onClick='ButtonPressed()'>Click me!</button>

<?PHP
 if(isset($_GET['next']))
    {
          echo "This will display after pressing the 'Click Me' button!";
    }
 ?>

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Your json contains an array, but you're trying to parse it as an object. This error occurs because objects must start with {.

You have 2 options:

  1. You can get rid of the ShopContainer class and use Shop[] instead

    ShopContainer response  = restTemplate.getForObject(
        url, ShopContainer.class);
    

    replace with

    Shop[] response  = restTemplate.getForObject(url, Shop[].class);
    

    and then make your desired object from it.

  2. You can change your server to return an object instead of a list

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
    

    replace with

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
        new ShopContainer(list));
    

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

What Java ORM do you prefer, and why?

Hibernate, because it's basically the defacto standard in Java and was one of the driving forces in the creation of the JPA. It's got excellent support in Spring, and almost every Java framework supports it. Finally, GORM is a really cool wrapper around it doing dynamic finders and so on using Groovy.

It's even been ported to .NET (NHibernate) so you can use it there too.

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

If you want extended auto-completion for PHP (not only for the code in the current window or standard classes), try out the "ACCPC" plugin: https://github.com/StanDog/npp-phpautocompletion

Draw a connecting line between two elements

Joining lines with svgs was worth a shot for me, and it worked perfectly... first of all, Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. SVG images and their behaviors are defined in XML text files. you can create an svg in HTML using <svg> tag. Adobe Illustrator is one of the best software used to create an complex svgs using paths.

Procedure to join two divs using a line :

  1. create two divs and give them any position as you need

    <div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#e53935 ; position:absolute;"></div>
    <div id="div2" style="width: 100px; height: 100px; top:0; left:300px; background:#4527a0 ; position:absolute;"></div>
    

    (for the sake of explanation I am doing some inline styling but it is always good to make a separate css file for styling)

  2. <svg><line id="line1"/></svg>

    Line tag allows us to draw a line between two specified points(x1,y1) and (x2,y2). (for a reference visit w3schools.) we haven't specified them yet. because we will be using jQuery to edit the attributes (x1,y1,x2,y2) of line tag.

  3. in <script> tag write

    line1 = $('#line1');   
    div1 = $('#div1');   
    div2 = $('#div2');
    

    I used selectors to select the two divs and line...

    var pos1 = div1.position();
    var pos2 = div2.position();
    

    jQuery position() method allows us to obtain the current position of an element. For more information, visit https://api.jquery.com/position/ (you can use offset() method too)

Now as we have obtained all the positions we need we can draw line as follows...

line1
  .attr('x1', pos1.left)
  .attr('y1', pos1.top)
  .attr('x2', pos2.left)
  .attr('y2', pos2.top);

jQuery .attr() method is used to change attributes of the selected element.

All we did in above line is we changed attributes of line from

x1 = 0
y1 = 0
x2 = 0
y2 = 0

to

x1 = pos1.left
y1 = pos1.top
x2 = pos2.left
y2 = pos2.top

as position() returns two values, one 'left' and other 'top', we can easily access them using .top and .left using the objects (here pos1 and pos2) ...

Now line tag has two distinct co-ordinates to draw line between two points.

Tip: add event listeners as you need to divs

Tip: make sure you import jQuery library first before writing anything in script tag

After adding co-ordinates through JQuery ... It will look something like this

Following snippet is for demonstration purpose only, please follow steps above to get correct solution

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#e53935 ; position:absolute;"></div>_x000D_
<div id="div2" style="width: 100px; height: 100px; top:0; left:300px; background:#4527a0 ; position:absolute;"></div>_x000D_
<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="50" stroke="red"/></svg>
_x000D_
_x000D_
_x000D_

Setting the zoom level for a MKMapView

You can also zoom by using MKCoordinateRegion and setting its span latitude & longitude delta. Below is a quick reference and here is the iOS reference. It won't do anything fancy but should allow you to set zoom when it draws the map.


MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
mapView.region = region;

Edit 1:

MKCoordinateRegion region;
region.center.latitude = {desired lat};
region.center.longitude = {desired lng};
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:TRUE];

Click in OK button inside an Alert (Selenium IDE)

You might look into chooseOkOnNextConfirmation, although that should probably be the default behavior if I read the docs correctly.