Programs & Examples On #Filelist

Use this tag for questions related to the W3C File API's FileList interface.

How do I remove a file from the FileList

You may wish to create an array and use that instead of the read-only filelist.

var myReadWriteList = new Array();
// user selects files later...
// then as soon as convenient... 
myReadWriteList = FileListReadOnly;

After that point do your uploading against your list instead of the built in list. I am not sure of the context you are working in but I am working with a jquery plugin I found and what I had to do was take the plugin's source and put it in the page using <script> tags. Then above the source I added my array so that it can act as a global variable and the plugin could reference it.

Then it was just a matter of swapping out the references.

I think this would allow you to also add drag & drop as again, if the built in list is read-only then how else could you get the dropped files into the list?

:))

Styling JQuery UI Autocomplete

You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.

.ui-corner-all
{
border-radius: 0px !important;
}

Call static methods from regular ES6 class methods

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

Then accessing

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
    • some probably overridden instance method/getter:
      • impossible by design
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • impossible by design
  • from instance method/getter of Foo
    • some probably overridden static method/getter:
      • this.constructor.method()
      • this.constructor.property
    • some probably overridden instance method/getter:
      • this.method()
      • this.property
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • not possible by intention unless using some workaround:
        • Foo.prototype.method.call( this )
        • Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);

Keep in mind that using this isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

Background

  • When in context of an instance's method or getter
    • this is referring to current instance.
    • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).
    • definition of instance's class used on creating it is available per this.constructor.
  • When in context of a static method or getter there is no "current instance" by intention and so
    • this is available to refer to the definition of current class directly.
    • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

Conclusion

Try this code:

_x000D_
_x000D_
class A {_x000D_
  constructor( input ) {_x000D_
    this.loose = this.constructor.getResult( input );_x000D_
    this.tight = A.getResult( input );_x000D_
    console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
  }_x000D_
_x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 100;_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return input * this.scale;_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
    this.tight = B.getResult( input ) + " (of B)";_x000D_
  }_x000D_
  _x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 10000;_x000D_
  }_x000D_
_x000D_
  static get scale() {_x000D_
    return 4;_x000D_
  }_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return super.getResult( input ) + " (overridden)";_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 10;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
_x000D_
_x000D_

ORA-30926: unable to get a stable set of rows in the source tables

Had the error today on a 12c and none of the existing answers fit (no duplicates, no non-deterministic expressions in the WHERE clause). My case was related to that other possible cause of the error, according to Oracle's message text (emphasis below):

ORA-30926: unable to get a stable set of rows in the source tables
Cause: A stable set of rows could not be got because of large dml activity or a non-deterministic where clause.

The merge was part of a larger batch, and was executed on a live database with many concurrent users. There was no need to change the statement. I just committed the transaction before the merge, then ran the merge separately, and committed again. So the solution was found in the suggested action of the message:

Action: Remove any non-deterministic where clauses and reissue the dml.

Installed Java 7 on Mac OS X but Terminal is still using version 6

vi ~/.bash_profile

add

export JAVA_HOME=`/usr/libexec/java_home -v 1.7`

This tells your /usr/bin/java link target to use the latest Java 7 Package installed in

/Library/Java/JavaVirtualMachines/

So for JDK 1.7.0_17 JAVA_HOME would be:

/Library/Java/JavaVirtualMachines/jdk1.7.0_17.jdk/Contents/Home

Note: There were a lot of change in this area recently to move Mac OS X from Appels own System integrated Java packages to Oracle based Java Packages. The above solution is working fine as of Mac OS X 10.8.2

How can I select rows by range?

Use the LIMIT clause:

/* rows x- y numbers */
SELECT * FROM tbl LIMIT x,y;

refer : http://dev.mysql.com/doc/refman/5.0/en/select.html

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

If your service is defined in the same file as a component (that consumes it) and the service is defined after the component in the file you may get this error. This is due to the same 'forwardRef' issue others have mentioned. At this time VSCode isn't great about showing you this error and the build compiles successfully.

Running the build with --aot can mask this problem due to the way the compiler works (probably related to tree shaking).

Solution: Make sure the service is defined in another file or before the component definition. (I'm not sure if forwardRef can be used in this case, but it seems clumsy to do so).

If I have a very simple service that is very strongly tied to a component (sort of like a view model) - eg. ImageCarouselComponent, I may name it ImageCarouselComponent.service.ts so it doesn't get all mixed up with my other services.

How do I create JavaScript array (JSON format) dynamically?

var accounting = [];
var employees = {};

for(var i in someData) {

    var item = someData[i];

   accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

employees.accounting = accounting;

What is process.env.PORT in Node.js?

In some scenarios, port can only be designated by the environment and is saved in a user environment variable. Below is how node.js apps work with it.

The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require().

The process.env property returns an object containing the user environment.

An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}

For example,

terminal: set a new user environment variable, not permanently

export MY_TEST_PORT=9999

app.js: read the new environment variable from node app

console.log(process.env.MY_TEST_PORT)

terminal: run the node app and get the value

$ node app.js
9999

What is the best way to implement a "timer"?

It's not clear what type of application you're going to develop (desktop, web, console...)

The general answer, if you're developing Windows.Forms application, is use of

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

What exactly is a Context in Java?

since you capitalized the word, I assume you are referring to the interface javax.naming.Context. A few classes implement this interface, and at its simplest description, it (generically) is a set of name/object pairs.

Superscript in CSS only?

try

.aftersup {
 font-size: 1em;
 margin: left;
 vertical-align: .7em;
}

or plain "after"

.after {
 font-size: 1em;
 margin: left;
 vertical-align: .7em;
}

".a.external:after" could be simplified

or

.after {
 font-size: 50%;
 margin: left;
 vertical-align: .7em;
}

using "font size 50%" - 50% of what size? this might not work well if not used within some tag defining text size previous to superscript...

if you use "font-size: 1em;" then the font size is set for sure, without reference to a tag that defines link text size, unless link text is set at 100% and superscript is 50% of that 100%.

Using "font-size: 1em;" actually sets font size baseline.

Set "vertical-align" size smaller, if you want superscript font to be smaller than link text

Set "vertical-align" size same as font size, if you want superscript font to be same size as link text

To align with link text, you need to set "margin" same as link text (left, center, right, justified).

.text {
  font-size: 1em;
  margin: left;
}
.aftersup {
  font-size: 1em;
  margin: left;
  vertical-align: .7em;
}

It should be something like below example links with superscript

<p class="text"><a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only</a><aftersup>+</aftersup></p>

or

<p class="text"><a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only</a><aftersup>You got this</aftersup></p>

or

<a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only</a><aftersup>+</aftersup>

or

<a href="url">https://stackoverflow.com/questions/501671/superscript-in-css-only<aftersup>You got this</aftersup>

As in...

Superscript in CSS only?+

or

Superscript in CSS only?You got this

JNI and Gradle in Android Studio

My issue on OSX it was gradle version. Gradle was ignoring my Android.mk. So, in order to override this option, and use my make instead, I have entered this line:

sourceSets.main.jni.srcDirs = []

inside of the android tag in build.gradle.

I have wasted lot of time on this!

How to add colored border on cardview?

I think this solution may not be efficient but it serves the purpose and adds flexibility with the border width.

 <android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="40dp"
    android:layout_gravity="center"
    card_view:cardBackgroundColor="@color/some_color"
    card_view:cardCornerRadius="20dp"
    card_view:contentPadding="5dp"> <!-- Change it to customize the border width -->

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        card_view:cardCornerRadius="20dp"
        card_view:contentPadding="5dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

         <!-- Add your UI elements -->

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</android.support.v7.widget.CardView>

No Network Security Config specified, using platform default - Android Log

I have a same problem, with volley, but this is my solution:

  1. In Android Manifiest, in tag application add:

    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"
    
  2. create in folder xml this file network_security_config.xml and write this:

    <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
      </network-security-config>
    
  3. inside tag application add this tag:

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    

Android. WebView and loadData

 String strWebData="html...." //**Your html string**

 WebView webDetail=(WebView) findViewById(R.id.webView1);

 WebSettings websetting = webDetail.getSettings();

 websetting.setDefaultTextEncodingName("utf-8");

 webDetail.loadData(strWebData, "text/html; charset=utf-8", null);

How to get list of all installed packages along with version in composer?

List installed dependencies:

  • Flat: composer show -i
  • Tree: composer show -i -t

-i short for --installed.

-t short for --tree.

ref: https://getcomposer.org/doc/03-cli.md#show

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

How do you kill all current connections to a SQL Server 2005 database?

ALTER DATABASE [Test]
SET OFFLINE WITH ROLLBACK IMMEDIATE

ALTER DATABASE [Test]
SET ONLINE

How to get the Parent's parent directory in Powershell?

If you want to use $PSScriptRoot you can do

Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve

Android Support Design TabLayout: Gravity Center and Mode Scrollable

I think a better approach will be to set app:tabMode="auto" and app:tabGravity="fill" because setting tabMode to fixed can make headings congested and cause headings to occupy multiple lines on the other side setting it to scrollable could make them leave spaces at the end in some screen sizes. manually setting tabMode would give a problem when dealing with multiple screen sizes

    <com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"       
    app:tabGravity="fill"
    android:textAlignment="center"
    app:tabMode="auto"
    />

Convert hexadecimal string (hex) to a binary string

With all zeroes:

static String hexToBin(String s) {
    String preBin = new BigInteger(s, 16).toString(2);
    Integer length = preBin.length();
    if (length < 8) {
        for (int i = 0; i < 8 - length; i++) {
            preBin = "0" + preBin;
        }
    }
    return preBin;
}

What's the best way to iterate an Android Cursor?

if (cursor.getCount() == 0)
  return;

cursor.moveToFirst();

while (!cursor.isAfterLast())
{
  // do something
  cursor.moveToNext();
}

cursor.close();

How to obtain image size using standard Python class (without using external library)?

Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer

And another solution (the quick way) for those who can afford running 'file' command within python, run:

import os
info = os.popen("file foo.jpg").read()
print info

Output:

foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3

All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.

Java Thread Example?

Here is a simple example:

ThreadTest.java

public class ThreadTest
{
   public static void main(String [] args)
   {
      MyThread t1 = new MyThread(0, 3, 300);
      MyThread t2 = new MyThread(1, 3, 300);
      MyThread t3 = new MyThread(2, 3, 300);

      t1.start();
      t2.start();
      t3.start();
   }
}

MyThread.java

public class MyThread extends Thread
{
   private int startIdx, nThreads, maxIdx;

   public MyThread(int s, int n, int m)
   {
      this.startIdx = s;
      this.nThreads = n;
      this.maxIdx = m;
   }

   @Override
   public void run()
   {
      for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
      {
         System.out.println("[ID " + this.getId() + "] " + i);
      }
   }
}

And some output:

[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23

An explanation - Each MyThread object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1 does index 0, 3, 6, 9, etc.

Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:

MyThread.java

System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();

And the output:

[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7

Now you can see each thread executing, giving up control early, and the next executing.

How do I concatenate strings and variables in PowerShell?

Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"

See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.

Python: How to create a unique file name?

This can be done using the unique function in ufp.path module.

import ufp.path
ufp.path.unique('./test.ext')

if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.

How can I protect my .NET assemblies from decompilation?

If someone has to steal your code, it likely means your business model is not working. What do I mean by that? For example, I buy your product and then I ask for support. You're too busy or believe my request is not valid and a waste of your time. I decode your product in order to support my relative business. Your product becomes more valuable to me and I prioritize my time in a way to resolve the business model for leveraging your product. I recode and re-brand your product and then go out and make the money that you decided to leave on the table. There are reasons for protecting code, but most likely you are looking at the problem from the wrong perspective. Of course you are. You're the "coder", and I'm the business man. ;-) Cheers!

ps. I'm also a developer. i.e. "coder"

Nexus 5 USB driver

Nexus 5 with Win7 x64

-USB computer connection : Uncheck MTP and PTP

-Use a 2.0 USB port.

-Try to use the original USB cable.

Now device manager will detect nexus 5 as an androide device with ADB driver.

Rename a file using Java

As far as I know, renaming a file will not append its contents to that of an existing file with the target name.

About renaming a file in Java, see the documentation for the renameTo() method in class File.

How to convert string to integer in PowerShell

You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):

$string = "1654"
$integer = [int]$string

$string + 1
# Outputs 16541

$integer + 1
# Outputs 1655

As an example, the following snippet adds, to each object in $fileList, an IntVal property with the integer value of the Name property, then sorts $fileList on this new property (the default is ascending), takes the last (highest IntVal) object's IntVal value, increments it and finally creates a folder named after it:

# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null

$highest = $fileList |
    Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
    Sort-Object IntVal |
    Select-Object -Last 1

$newName = $highest.IntVal + 1

New-Item $newName -ItemType Directory

Sort-Object IntVal is not needed so you can remove it if you prefer.

[int]::MaxValue = 2147483647 so you need to use the [long] type beyond this value ([long]::MaxValue = 9223372036854775807).

Show/Hide the console window of a C# console application

Why do you need a console application if you want to hide console itself? =)

I recommend setting Project Output type to Windows Application instead of Console application. It will not show you console window, but execute all actions, like Console application do.

What is the correct way to represent null XML elements?

You use xsi:nil when your schema semantics indicate that an element has a default value, and that the default value should be used if the element isn't present. I have to assume that there are smart people to whom the preceding sentence is not a self-evidently terrible idea, but it sounds like nine kinds of bad to me. Every XML format I've ever worked with represents null values by omitting the element. (Or attribute, and good luck marking an attribute with xsi:nil.)

Reason to Pass a Pointer by Reference in C++?

One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.

In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.

Activate a virtualenv with a Python script

If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:

import subprocess

# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"

# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"

subprocess.Popen([python_bin, script_file])

However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:

# Doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

execfile(activate_this_file, dict(__file__=activate_this_file))

Find what 2 numbers add to something and multiply to something

That's basically a set of 2 simultaneous equations:

x*y = a
X+y = b

(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).

But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

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

Here is the way you can do with Javascript Promise.

const getBase64 = (file) => new Promise(function (resolve, reject) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject('Error: ', error);
})

Now, use it in event handler.

const _changeImg = (e) => {
        const file = e.target.files[0];
        let encoded;
        getBase64(file)
          .then((result) => {
            encoded = result;
           })
          .catch(e => console.log(e))
    }

golang why don't we have a set datastructure

Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...

The other reason is, that it's not clear at all what the "right" implementation of a set is:

  1. There is a functional approach:

    func IsInEvenNumbers(n int) bool {
        if n % 2 == 0 {
            return true
        }
       return false
    }
    

This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.

  1. Or you do a has-like approach like Dali showed.

A map does not have that problem, since you store something associated with the value.

How can I convert an HTML table to CSV?

This method is not really a library OR a program, but for ad hoc conversions you can

  • put the HTML for a table in a text file called something.xls
  • open it with a spreadsheet
  • save it as CSV.

I know this works with Excel, and I believe I've done it with the OpenOffice spreadsheet.

But you probably would prefer a Perl or Ruby script...

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

In your giant elif chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:

...
elif x == 90:
    return 6
else:
    raise ValueError(x)

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

Is there an alternative sleep function in C to milliseconds?

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

How can I get session id in php and show it?

if(isset($_POST['submit']))
   {  
 if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
    {
     $uname = $_POST['login_username'];
     $pass = $_POST['login_password'];
     $res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and  password='$pass' ";
$query=mysql_query($res)or die (mysql_error());  

list($result,$uname,$role) = mysql_fetch_row($query);   
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
 if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
 {
 if($result>0)
      {
       header ('Location:Dashboard.php');
      }
      else
      {
         header ('Location:loginform.php');
      }
 }

Calculating average of an array list?

Correct and fast way compute average for List<Integer>:

private double calculateAverage(List<Integer> marks) {
    long sum = 0;
    for (Integer mark : marks) {
        sum += mark;
    }
    return marks.isEmpty()? 0: 1.0*sum/marks.size();
}

This solution take into account:

  • Handle overflow
  • Do not allocate memory like Java8 stream
  • Do not use slow BigDecimal

It works coorectly for List, because any list contains less that 2^31 int, and it is possible to use long as accumulator.

PS

Actually foreach allocate memory - you should use old style for() cycle in mission critical parts

What is setBounds and how do I use it?

This is a method of the java.awt.Component class. It is used to set the position and size of a component:

setBounds

public void setBounds(int x,
                  int y,
                  int width,
                  int height) 

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. Parameters:

  • x - the new x-coordinate of this component
  • y - the new y-coordinate of this component
  • width - the new width of this component
  • height - the new height of this component

x and y as above correspond to the upper left corner in most (all?) cases.

It is a shortcut for setLocation and setSize.

This generally only works if the layout/layout manager are non-existent, i.e. null.

C# How to determine if a number is a multiple of another?

Use the modulus (%) operator:

6 % 3 == 0
7 % 3 == 1

How to make Excel VBA variables available to multiple macros?

Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.

SQL Server: How to check if CLR is enabled?

select *
from sys.configurations
where name = 'clr enabled'

How do I compile and run a program in Java on my Mac?

Other solutions are good enough to answer your query. However, if you are looking for just one command to do that for you -

Create a file name "run", in directory where your Java files are. And save this in your file -

javac "$1.java"
if [ $? -eq 0 ]; then
  echo "--------Run output-------"
  java "$1"
fi

give this file run permission by running -

chmod 777 

Now you can run any of your files by merely running -

./run <yourfilename> (don't add .java in filename)

How to remove all .svn directories from my application directories

What you wrote sends a list of newline separated file names (and paths) to rm, but rm doesn't know what to do with that input. It's only expecting command line parameters.

xargs takes input, usually separated by newlines, and places them on the command line, so adding xargs makes what you had work:

find . -name .svn | xargs rm -fr

xargs is intelligent enough that it will only pass as many arguments to rm as it can accept. Thus, if you had a million files, it might run rm 1,000,000/65,000 times (if your shell could accept 65,002 arguments on the command line {65k files + 1 for rm + 1 for -fr}).

As persons have adeptly pointed out, the following also work:

find . -name .svn -exec rm -rf {} \;
find . -depth -name .svn -exec rm -fr {} \;
find . -type d -name .svn -print0|xargs -0 rm -rf

The first two -exec forms both call rm for each folder being deleted, so if you had 1,000,000 folders, rm would be invoked 1,000,000 times. This is certainly less than ideal. Newer implementations of rm allow you to conclude the command with a + indicating that rm will accept as many arguments as possible:

find . -name .svn -exec rm -rf {} +

The last find/xargs version uses print0, which makes find generate output that uses \0 as a terminator rather than a newline. Since POSIX systems allow any character but \0 in the filename, this is truly the safest way to make sure that the arguments are correctly passed to rm or the application being executed.

In addition, there's a -execdir that will execute rm from the directory in which the file was found, rather than at the base directory and a -depth that will start depth first.

How to Extract Year from DATE in POSTGRESQL

You may try to_char(now()::date, 'yyyy')
If text, you've to cast your text to date to_char('2018-01-01'::date, 'yyyy')

See the PostgreSQL Documentation Data Type Formatting Functions

#include errors detected in vscode

1.Install Mingw-w64

2.Then Edit environment variables for your account "C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin"

3.Reload

  • For MAC

    1.Open search ,command + shift +P, and run this code “c/c++ edit configurations (ui)”

    2.open file c_cpp_properties.json and update the includePath from "${workspaceFolder}/**" to "${workspaceFolder}/inc"

Easy way to password-protect php page

This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.

First prepare your password salts file:

hash_generate.php:

 <?php

 $user = "Username"; // please replace with your user
 $pass = "Password"; // please replace with your passwd
 // two ; was missing

 $useroptions = ['cost' => 8,];
 $userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions);
 $pwoptions   = ['cost' => 8,];
 $passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);

 echo $userhash;
 echo "<br />";
 echo $passhash;

 ?>

Take your output $userhash and $passhash and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"

.htaccess

 deny from all

Now no one can peek into the hash. Next up is your index.php:

index.php:

<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
    $user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
    $pass = $_POST['pass'];
}    

$useroptions = ['cost' => 8,]; // all up to you
$pwoptions   = ['cost' => 8,]; // all up to you
$userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);  // hash entered pw
$hasheduser  = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass  = file_get_contents("stuff/pass.txt"); // and our stored password


if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {

    // the password verify is how we actually login here
    // the $userhash and $passhash are the hashed user-entered credentials
    // password verify now compares our stored user and pw with entered user and pw

    include "pass-protected.php";

} else { 
    // if it was invalid it'll just display the form, if there was never a $_POST
    // then it'll also display the form. that's why I set $user to "" instead of a $_POST
    // this is the right place for comments, not inside html
    ?>  
    <form method="POST" action="index.php">
    User <input type="text" name="user"></input><br/>
    Pass <input type="password" name="pass"></input><br/>
    <input type="submit" name="submit" value="Go"></input>
    </form>
    <?php 
} 

Add a background image to shape in XML Android

This is a circle shape with icon inside:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ok_icon"/>
    <item>
        <shape
                android:shape="oval">
            <solid android:color="@color/transparent"/>
            <stroke android:width="2dp" android:color="@color/button_grey"/>
        </shape>
    </item>
</layer-list>

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

How should I tackle --secure-file-priv in MySQL?

I solved it using the LOCAL option in the command:

LOAD DATA LOCAL INFILE "text.txt" INTO TABLE mytable;

You can find more info here.

If LOCAL is specified, the file is read by the client program on the client host and sent to the server. The file can be given as a full path name to specify its exact location. If given as a relative path name, the name is interpreted relative to the directory in which the client program was started.

Creating a JSON Array in node js

This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });

Send Message in C#

You are almost there. (note change in the return value of FindWindow declaration). I'd recommend using RegisterWindowMessage in this case so you don't have to worry about the ins and outs of WM_USER.

[DllImport("user32.dll")]    
public static extern IntPtr FindWindow(string lpClassName, String lpWindowName);    
[DllImport("user32.dll")]    
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);    
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);

public void button1_Click(object sender, EventArgs e)   
{        
     // this would likely go in a constructor because you only need to call it 
     // once per process to get the id - multiple calls in the same instance 
     // of a windows session return the same value for a given string
     uint id = RegisterWindowMessage("MyUniqueMessageIdentifier");
     IntPtr WindowToFind = FindWindow(null, "Form1");    
     Debug.Assert(WindowToFind != IntPtr.Zero);
     SendMessage(WindowToFind, id, IntPtr.Zero, IntPtr.Zero);
}

And then in your Form1 class:

class Form1 : Form
{
    [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
    static extern uint RegisterWindowMessage(string lpString);

    private uint _messageId = RegisterWindowMessage("MyUniqueMessageIdentifier");

    protected override void WndProc(ref Message m)
    {
       if (m.Msg == _messageId)
       {
           // do stuff

       }
       base.WndProc(ref m);
    }
}

Bear in mind I haven't compiled any of the above so some tweaking may be necessary. Also bear in mind that other answers warning you away from SendMessage are spot on. It's not the preferred way of inter module communication nowadays and genrally speaking overriding the WndProc and using SendMessage/PostMessage implies a good understanding of how the Win32 message infrastructure works.

But if you want/need to go this route I think the above will get you going in the right direction.

How can I auto hide alert box after it showing it?

tldr; jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
 var el = document.createElement("div");
 el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
 el.innerHTML = msg;
 setTimeout(function(){
  el.parentNode.removeChild(el);
 },duration);
 document.body.appendChild(el);
}

Use this like this:

tempAlert("close",5000);

Detect browser or tab closing

If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in Javascript to detect that kind of stuffs are onunload & onbeforeunload events.

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

html div onclick event

You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway

Test the click on the div and examine the target

Live Demo

$(".expandable-panel-heading").on("click",function (e) {
    if (e.target.id =="ancherComplaint") { // or test the tag
        e.preventDefault(); // or e.stopPropagation()
        markActiveLink(e.target);
    }    
    else alert('123');
});
function markActiveLink(el) {   
    alert(el.id);
} 

How to compare two dates in php

The date_diff() function returns the difference between two DateTime objects.

If the first date is before the second date a positive number of days will be returned; otherwise a negative number of days:

<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>

output will be "+272 days" ;

changing $date1 = "2014-03-15"

 <?php
    $date1=date_create("2014-03-15");
    $date2=date_create("2013-12-12");
    $diff=date_diff($date1,$date2);
    echo $diff->format("%R%a days");
    ?>

Output will be "-93 days"

Java command not found on Linux

  1. Execute: vi ~/.bashrc OR vi ~/.bash_profile

(if above command will not allow to update the .bashrc file then you can open this file in notepad by writing command at terminal i.e. "leafpad ~/.bashrc")

  1. add line : export JAVA_HOME=/usr/java/jre1.6.0_24
  2. save the file (by using shift + Z + Z)
  3. source ~/.bashrc OR source ~/.bash_profile
  4. Execute : echo $JAVA_HOME (Output should print the path)

Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

How can I send an HTTP POST request to a server from Excel using VBA?

In addition to the anwser of Bill the Lizard:

Most of the backends parse the raw post data. In PHP for example, you will have an array $_POST in which individual variables within the post data will be stored. In this case you have to use an additional header "Content-type: application/x-www-form-urlencoded":

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")

Otherwise you have to read the raw post data on the variable "$HTTP_RAW_POST_DATA".

What is a None value?

largest=none
smallest =none 
While True :
          num =raw_input ('enter a number ') 
          if num =="done ": break 
          try :
           inp =int (inp) 
          except:
              Print'Invalid input' 
           if largest is none :
               largest=inp
           elif inp>largest:
                largest =none 
           print 'maximum', largest

          if smallest is none:
               smallest =none
          elif inp<smallest :
               smallest =inp
          print 'minimum', smallest 

print 'maximum, minimum, largest, smallest 

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

My answer might not be solution to your question but it will surely help others looking for similar issue like this one: javax.net.ssl.SSLHandshakeException: Chain validation failed

You just need to check your Android Device's Date and Time, it should be fix the issue. This resoled my problem.

Copying from one text file to another using Python

readlines() reads the entire input file into a list and is not a good performer. Just iterate through the lines in the file. I used 'with' on output.txt so that it is automatically closed when done. That's not needed on 'list1.txt' because it will be closed when the for loop ends.

#!/usr/bin/env python
with open('output.txt', 'a') as f1:
    for line in open('list1.txt'):
        if 'tests/file/myword' in line:
            f1.write(line)

Javascript : array.length returns undefined

Objects don't have a .length property.

A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:

Object.keys(data).length;

If you have to support IE 8 or lower, you'll have to use a loop, instead:

var length= 0;
for(var key in data) {
    if(data.hasOwnProperty(key)){
        length++;
    }
}

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

Visual Studio Code open tab in new window

When I want to split the screens I usually do one of the following:

  1. open new window with: Ctrl+Shift+N
    and after that I drag the current file I want to the new window.
  2. on the File explorer - I hit Ctrl+Enter on the file I want - and then this file and the other file open together in the same screen but in split mode, so you can see the two files together. If the screen is wide enough this is not a bad solution at all that you can get used to.

Change border-bottom color using jquery?

If you have this in your CSS file:

.myApp
{
    border-bottom-color:#FF0000;
}

and a div for instance of:

<div id="myDiv">test text</div>

you can use:

$("#myDiv").addClass('myApp');// to add the style

$("#myDiv").removeClass('myApp');// to remove the style

or you can just use

$("#myDiv").css( 'border-bottom-color','#FF0000');

I prefer the first example, keeping all the CSS related items in the CSS files.

Fastest way to convert a dict's keys & values from `unicode` to `str`?

To make it all inline (non-recursive):

{str(k):(str(v) if isinstance(v, unicode) else v) for k,v in my_dict.items()}

sql query to find the duplicate records

You can do it in a single query:

Select t.Id, t.title, z.dupCount
From yourtable T
Join
   (select title, Count (*) dupCount
    from yourtable 
    group By title
    Having Count(*) > 1) z
   On z.title = t.Title
order By dupCount Desc

Fatal error: Call to undefined function sqlsrv_connect()

First check that the extension is properly loaded in phpinfo(); (something like sqlsrv should appear). If not, the extension isn't properly loaded. You also need to restart apache after installing an extension.

How to run a program in Atom Editor?

I find the Script package useful for this. You can download it here.

Once installed you can run scripts in many languages directly from Atom using cmd-i on Mac or shift-ctrl-b on Windows or Linux.

How to position the div popup dialog to the center of browser screen?

Here, this ones working. :)

http://jsfiddle.net/nDNXc/1/

upd: Just in case jsfiddle is not responding here is the code...
CSS:

.holder{        
    width:100%;
    display:block;
}
.content{
    background:#fff;
    padding: 28px 26px 33px 25px;
}
.popup{
    border-radius: 7px;
    background:#6b6a63;
    margin:30px auto 0;
    padding:6px;  
    // here it comes
    position:absolute;
    width:800px;
    top: 50%;
    left: 50%;
    margin-left: -400px; // 1/2 width
    margin-top: -40px; // 1/2 height
}

HTML:

<div class="holder">     
    <div id="popup" class="popup">            
        <div class="content">some lengthy text</div>
    </div>
</div>

How can I repeat a character in Bash?

Most existing solutions all depend on {1..10} syntax support of the shell, which is bash- and zsh- specific, and doesn't work in tcsh or OpenBSD's ksh and most non-bash sh.

The following should work on OS X and all *BSD systems in any shell; in fact, it can be used to generate a whole matrix of various types of decorative space:

$ printf '=%.0s' `jot 64` | fold -16
================
================
================
================$ 

Sadly, we don't get a trailing newline; which can be fixed by an extra printf '\n' after the fold:

$ printf "=%.0s" `jot 64` | fold -16 ; printf "\n"
================
================
================
================
$ 

References:

How do I concatenate two strings in Java?

First method: You could use "+" sign for concatenating strings, but this always happens in print. Another way: The String class includes a method for concatenating two strings: string1.concat(string2);

How to do while loops with multiple conditions

while not condition1 or not condition2 or val == -1:

But there was nothing wrong with your original of using an if inside of a while True.

Selecting distinct values from a JSON

I would use one Object and one Array, if you want to save some cycle:

var lookup = {};
var items = json.DATA;
var result = [];

for (var item, i = 0; item = items[i++];) {
  var name = item.name;

  if (!(name in lookup)) {
    lookup[name] = 1;
    result.push(name);
  }
}

In this way you're basically avoiding the indexOf / inArray call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty.

Of course if you're fine with just an Object you can avoid the check and the result.push at all, and in case get the array using Object.keys(lookup), but it won't be faster than that.

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

I think JAVA_HOME is the best you can do. The command-line tools like java and javac will respect that environment variable, you can use /usr/libexec/java_home -v '1.7*' to give you a suitable value to put into JAVA_HOME in order to make command line tools use Java 7.

export JAVA_HOME="`/usr/libexec/java_home -v '1.7*'`"

But standard double-clickable application bundles don't use JDKs installed under /Library/Java at all. Old-style .app bundles using Apple's JavaApplicationStub will use Apple Java 6 from /System/Library/Frameworks, and new-style ones built with AppBundler without a bundled JRE will use the "public" JRE in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home - that's hard-coded in the stub code and can't be changed, and you can't have two different public JREs installed at the same time.


Edit: I've had a look at VisualVM specifically, assuming you're using the "application bundle" version from the download page, and this particular app is not an AppBundler application, instead its main executable is a shell script that calls a number of other shell scripts and reads various configuration files. It defaults to picking the newest JDK from /Library/Java as long as that is 7u10 or later, or uses Java 6 if your Java 7 installation is update 9 or earlier. But unravelling the logic in the shell scripts it looks to me like you can specify a particular JDK using a configuration file.

Create a text file ~/Library/Application Support/VisualVM/1.3.6/etc/visualvm.conf (replace 1.3.6 with whatever version of VisualVM you're using) containing the line

visualvm_jdkhome="`/usr/libexec/java_home -v '1.7*'`"

and this will force it to choose Java 7 instead of 8.

What is referencedColumnName used for in JPA?

It is there to specify another column as the default id column of the other table, e.g. consider the following

TableA
  id int identity
  tableb_key varchar


TableB
  id int identity
  key varchar unique

// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")

JavaScript by reference vs. by value

Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.

An example:

function changeParam(x, y, z) {
  x = 3;
  y = "new string";
  z["key2"] = "new";
  z["key3"] = "newer";

  z = {"new" : "object"};
}

var a = 1,
    b = "something",
    c = {"key1" : "whatever", "key2" : "original value"};

changeParam(a, b, c);

// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...

How can I remount my Android/system as read-write in a bash script using adb?

mount -o rw,remount $(mount | grep /dev/root | awk '{print $3}')

this does the job for me, and should work for any android version.

Java Immutable Collections

Collection<String> c1 = new ArrayList<String>();
c1.add("foo");
Collection<String> c2 = Collections.unmodifiableList(c1);

c1 is mutable (i.e. neither unmodifiable nor immutable).
c2 is unmodifiable: it can't be changed itself, but if later on I change c1 then that change will be visible in c2.

This is because c2 is simply a wrapper around c1 and not really an independent copy. Guava provides the ImmutableList interface and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).

Regarding your second question:

The mutability/immutability of a collection does not depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does not count as a "modification of the collection" for this description. Of course if you need a immutable collection, you usually also want it to contain immutable objects.

How can I submit a POST form using the <a href="..."> tag?

You need to use javascript for this.

<form id="form1" action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>
</form>

How can I make one python file run another?

It may be called abc.py from the main script as below:

#!/usr/bin/python
import abc

abc.py may be something like this:

print'abc'

SelectSingleNode returning null for known good xml node path using XPath

Just to build upon solving the namespace issues, in my case I've been running into documents with multiple namespaces and needed to handle namespaces properly. I wrote the function below to get a namespace manager to deal with any namespace in the document:

private XmlNamespaceManager GetNameSpaceManager(XmlDocument xDoc)
    {
        XmlNamespaceManager nsm = new XmlNamespaceManager(xDoc.NameTable);
        XPathNavigator RootNode = xDoc.CreateNavigator();
        RootNode.MoveToFollowing(XPathNodeType.Element);
        IDictionary<string, string> NameSpaces = RootNode.GetNamespacesInScope(XmlNamespaceScope.All);

        foreach (KeyValuePair<string, string> kvp in NameSpaces)
        {
            nsm.AddNamespace(kvp.Key, kvp.Value);
        }

        return nsm;
    }

"Unable to acquire application service" error while launching Eclipse

I tried all the answers above, but none of them worked for me, so I was forced to try something else. I just removed the whole package with settings org.eclipse.Java and it worked fine, starts again like before and even keeps all settings like color themes and others. Worked like charm.

On Linux or Mac go to /home/{your_user_name}/.var/app and run the following command:

 rm -r org.eclipse.Java

On Windows just find the same directory and move it to Trash.

After this is done, the settings and the errors are deleted, so Eclipse will start and re-create them with the proper settings.

When Eclipse starts it will ask for the workspace directory. When specified, everything works like before.

Checking if an Android application is running in the background

In my opinion, many answers introduce a heavy load of code and bring lots of complexity and non-readability.

When people ask on SO how to communicate between a Service and a Activity, I usually advice to use the LocalBroadcastManager.


Why?

Well, by quoting the docs:

  • You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.

  • It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.

  • It is more efficient than sending a global broadcast through the system.

Not in the the docs:

  • It does not require external libraries
  • The code is minimal
  • It's fast to implement and understand
  • No custom self-implemented callbacks / ultra-singleton / intra-process pattern whatsoever...
  • No strong references on Activity, Application, ...

Description

So, you want to check if any of the Activity is currently in the foreground. You usually do that in a Service, or your Application class.

This means, your Activity objects become the sender of a signal (I'm on / I'm off). Your Service, on the other hand, becomes the Receiver.

There are two moments in which your Activity tells you if it's going in the foreground or in the background (yes only two... not 6).

When the Activity goes into the foreground, the onResume() method is triggered (also called after onCreate()).

When the Activity goes in the back, onPause() is called.

These are the moments in which your Activity should send the signal to your Service to describe its state.

In case of multiple Activity's, remember the an Activity goes into the background first, then another one comes into the foreground.

So the situation would be:*

Activity1 -- send --> Signal:OFF
Activity2 -- send --> Signal:ON

The Service / Application will simply keep listening for those signals and act accordingly.


Code (TLDR)

Your Service must implement a BroadcastReceiver in order to listen for signals.

this.localBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // received data if Activity is on / off
    }
}

public static final IntentFilter SIGNAL_FILTER = new IntentFilter("com.you.yourapp.MY_SIGNAL") 

Register the Receiver in Service::onCreate()

@Override
protected void onCreate() {
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(this.localBroadcastReceiver, SIGNAL_FILTER);
}

Un-register it in Service::onDestroy()

@Override
protected void onDestroy() {
    // I'm dead, no need to listen to anything anymore.
    LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(this.localBroadcastReceiver);
}

Now your Activity's must communicated their state.

In Activity::onResume()

Intent intent = new Intent();
intent.setAction(SomeActivity.SIGNAL_FILTER); // put ON boolean in intent    
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

In Activity::onPause()

Intent intent = new Intent();
intent.setAction(SomeActivity.SIGNAL_FILTER); // put OFF boolean in intent    
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

A very, very common situation

Developer: I want to send data from my Service and update the Activity. How do I check if the Activity is in the foreground?

There is usually no need to check if the Activity is in the foreground or not. Just send the data via LocalBroadcastManager from your Service. If the Activity is on, then it will respond and act.

For this very common situation, the Service becomes the sender, and the Activity implements the BroadcastReceiver.

So, create a Receiver in your Activity. Register it in onResume() and un-register it in onPause(). There is no need to use the other life-cycle methods.

Define the Receiver behavior in onReceive() (update ListView, do this, do that, ...).

This way the Activity will listen only if it's in the foreground and nothing will happen if it's in the back or is destroyed.

In case of multiple Activity's, whichever Activity is on will respond (if they also implement the Receiver).

If all are in the background, nobody will respond and the signal will simply get lost.

Send the data from the Service via Intent (see code above) by specifying the signal ID.


JS jQuery - check if value is in array

The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Does java have a int.tryparse that doesn't throw an exception for bad data?

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

For something like $x from chrome command line api (to select multiple elements) try:

var xpath = function(xpathToExecute){
  var result = [];
  var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
  for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ){
    result.push( nodesSnapshot.snapshotItem(i) );
  }
  return result;
}

This MDN overview helped: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript

CSS background-image - What is the correct usage?

The path can either be full or relative (of course if the image is from another domain it must be full).

You don't need to use quotes in the URI; the syntax can either be:

background-image: url(image.jpg);

Or

background-image: url("image.jpg");

However, from W3:

Some characters appearing in an unquoted URI, such as parentheses, white space characters, single quotes (') and double quotes ("), must be escaped with a backslash so that the resulting URI value is a URI token: '\(', '\)'.

So in instances such as these it is either necessary to use quotes or double quotes, or escape the characters.

Angular 2: import external js file into component

1) First Insert JS file path in an index.html file :

<script src="assets/video.js" type="text/javascript"></script>

2) Import JS file and declare the variable in component.ts :

  • import './../../../assets/video.js';
  • declare var RunPlayer: any;

    NOTE: Variable name should be same as the name of a function in js file

3) Call the js method in the component

ngAfterViewInit(){

    setTimeout(() => {
        new RunPlayer();
    });

}

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

I encountered this error when I had a row.names="id" (per the tutorial) with a column named "id".

Find all paths between two graph nodes

I suppose you want to find 'simple' paths (a path is simple if no node appears in it more than once, except maybe the 1st and the last one).

Since the problem is NP-hard, you might want to do a variant of depth-first search.

Basically, generate all possible paths from A and check whether they end up in G.

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

Downloading images with node.js

if you want progress download try this:

var fs = require('fs');
var request = require('request');
var progress = require('request-progress');

module.exports = function (uri, path, onProgress, onResponse, onError, onEnd) {
    progress(request(uri))
    .on('progress', onProgress)
    .on('response', onResponse)
    .on('error', onError)
    .on('end', onEnd)
    .pipe(fs.createWriteStream(path))
};

how to use:

  var download = require('../lib/download');
  download("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png", "~/download/logo.png", function (state) {
            console.log("progress", state);
        }, function (response) {
            console.log("status code", response.statusCode);
        }, function (error) {
            console.log("error", error);
        }, function () {
            console.log("done");
        });

note: you should install both request & request-progress modules using:

npm install request request-progress --save

Expected response code 220 but got code "", with message "" in Laravel

i was facing this problem and i checked all the answers and nothing worked for me, but then i reset mail.php and didn't touch it and set the mail server from .env file and it worked perfectly, hope this will save the time for someone :).

How to check for an empty object in an AngularJS view

please try this way with filter

angular.module('myApp')
    .filter('isEmpty', function () {
        var bar;
        return function (obj) {
            for (bar in obj) {
                if (obj.hasOwnProperty(bar)) {
                    return false;
                }
            }
            return true;
        };
    });

usage:

 <p ng-hide="items | isEmpty">Some Content</p>

Via from : Checking if object is empty, works with ng-show but not from controller?

Tomcat 8 Maven Plugin for Java 8

An other solution (if possible) would be to use TomEE instead of Tomcat, which has a working maven plugin:

<plugin>
    <groupId>org.apache.tomee.maven</groupId>
    <artifactId>tomee-maven-plugin</artifactId>
    <version>7.1.1</version>
</plugin>

Version 7.1.1 wraps a Tomcat 8.5.41

How to check Elasticsearch cluster health?

PROBLEM :-

Sometimes, Localhost may not get resolved. So it tends to return an output as seen below :

# curl -XGET localhost:9200/_cluster/health?pretty

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

# curl -XGET localhost:9200/_cat/indices

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>

<p>The system returned: <i>(111) Connection refused</i></p>

<p>The remote host or network may be down.  Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&amp;body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>

<br>   
<hr> 
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>

SOLUTION :-

Guess, this error is most probably returned by Local Squid deployed in the server.

So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.

How to detect my browser version and operating system using JavaScript?

To get the new Microsoft Edge based on a Mozilla core add:

else if ((verOffset=nAgt.indexOf("Edg"))!=-1) {
 browserName = "Microsoft Edge";
 fullVersion = nAgt.substring(verOffset+5);
}

before

// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}

jQuery function after .append

I encountered this issue while coding HTML5 for mobile devices. Some browser/device combinations caused errors because .append() method did not reflect the changes in the DOM immediatly (causing the JS to fail).

By quick-and-dirty solution for this situation was:

var appint = setInterval(function(){
    if ( $('#foobar').length > 0 ) {
        //now you can be sure append is ready
        //$('#foobar').remove(); if elem is just for checking
        //clearInterval(appint)
    }
}, 100);
$(body).append('<div>...</div><div id="foobar"></div>');

Keep values selected after form submission

<form method="get" action="">
 <select name="name" value="<?php echo $_GET['name'];?>">
   <option value="a">a</option>
   <option value="b">b</option>
 </select>
 <select name="location" value="<?php echo $_GET['location'];?>">
   <option value="x">x</option>
   <option value="y">y</option>
 </select>
   <input type="submit" value="Submit" class="submit" />
</form>

Rails :include vs. :joins

.joins works as database join and it joins two or more table and fetch selected data from backend(database).

.includes work as left join of database. It loaded all the records of left side, does not have relevance of right hand side model. It is used to eager loading because it load all associated object in memory. If we call associations on include query result then it does not fire a query on database, It simply return data from memory because it have already loaded data in memory.

In C#, can a class inherit from another class and an interface?

Unrelated to the question (Mehrdad's answer should get you going), and I hope this isn't taken as nitpicky: classes don't inherit interfaces, they implement them.

.NET does not support multiple-inheritance, so keeping the terms straight can help in communication. A class can inherit from one superclass and can implement as many interfaces as it wishes.


In response to Eric's comment... I had a discussion with another developer about whether or not interfaces "inherit", "implement", "require", or "bring along" interfaces with a declaration like:

public interface ITwo : IOne

The technical answer is that ITwo does inherit IOne for a few reasons:

  • Interfaces never have an implementation, so arguing that ITwo implements IOne is flat wrong
  • ITwo inherits IOne methods, if MethodOne() exists on IOne then it is also accesible from ITwo. i.e: ((ITwo)someObject).MethodOne()) is valid, even though ITwo does not explicitly contain a definition for MethodOne()
  • ...because the runtime says so! typeof(IOne).IsAssignableFrom(typeof(ITwo)) returns true

We finally agreed that interfaces support true/full inheritance. The missing inheritance features (such as overrides, abstract/virtual accessors, etc) are missing from interfaces, not from interface inheritance. It still doesn't make the concept simple or clear, but it helps understand what's really going on under the hood in Eric's world :-)

jquery to validate phone number

This one is work for me:-

/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.

Not only explicit, but also implicit conversions are possible.

C# language doesn't permit such conversion operators, but you can still write them using pure C# and they work. Note that the class which defines the implicit conversion operator (Derived) and the class which uses the operator (Program) must be defined in separate assemblies (e.g. the Derived class is in a library.dll which is referenced by program.exe containing the Program class).

//In library.dll:
public class Base { }

public class Derived {
    [System.Runtime.CompilerServices.SpecialName]
    public static Derived op_Implicit(Base a) {
        return new Derived(a); //Write some Base -> Derived conversion code here
    }

    [System.Runtime.CompilerServices.SpecialName]
    public static Derived op_Explicit(Base a) {
        return new Derived(a); //Write some Base -> Derived conversion code here
    }
}

//In program.exe:
class Program {
    static void Main(string[] args) {
        Derived z = new Base(); //Visual Studio can show squiggles here, but it compiles just fine.
    }
}

When you reference the library using the Project Reference in Visual Studio, VS shows squiggles when you use the implicit conversion, but it compiles just fine. If you just reference the library.dll, there are no squiggles.

remove duplicates from sql union

Using UNION automatically removes duplicate rows unless you specify UNION ALL: http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx

Find most frequent value in SQL column

For use with SQL Server.

As there is no limit command support in that.

Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)

SELECT top1 
    `value`,
    COUNT(`value`) AS `value_occurrence` 
FROM     
    `my_table`
GROUP BY 
    `value`
ORDER BY 
    `value_occurrence` DESC;

How do I retrieve an HTML element's actual width and height?

You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.

var width = document.getElementById('foo').offsetWidth;

Function .getBoundingClientRect() returns dimensions and location of element as floating-point numbers after performing CSS transforms.

> console.log(document.getElementById('id').getBoundingClientRect())
DOMRect {
    bottom: 177,
    height: 54.7,
    left: 278.5,?
    right: 909.5,
    top: 122.3,
    width: 631,
    x: 278.5,
    y: 122.3,
}

CSS rule to apply only if element has BOTH classes

If you need a progmatic solution this should work in jQuery:

$(".abc.xyz").css("width", 200);

How to detect the currently pressed key?

In WinForms:

if( Form.ModifierKeys == Keys.Shift )

It sounds like a duplicate of Stack Overflow question Detect Shift key is pressed without using events in Windows Forms?.

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

Use stored procedure to insert some data into a table

if you want to populate a table in SQL SERVER you can use while statement as follows:

declare @llenandoTabla INT = 0;
while @llenandoTabla < 10000
begin
insert into employeestable // Name of my table
(ID, FIRSTNAME, LASTNAME, GENDER, SALARY) // Parameters of my table
VALUES 
(555, 'isaias', 'perez', 'male', '12220') //values
set @llenandoTabla = @llenandoTabla + 1;
end

Hope it helps.

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is environment variable used by tomcat in its startup/shutdown script to configure params.

You can set it in linux by

export JAVA_OPTS="-Djava.awt.headless=true" 

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

Filter items which array contains any of given values

Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:

A term query can be used to find the exact term specified in the reverse index:

{
  "query": {
   "term" : { "tags" : "a" }
} 

From the documenation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

Alternatively you can use a terms query, which will match all documents with any of the items specified in the given array:

{
  "query": {
   "terms" : { "tags" : ["a", "c"]}
} 

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html

One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text type then Elasticsearch will perform a full text search (i.e using an analyzed string).

If you've indexed the field as a keyword then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (https://www.elastic.co/guide/en/elasticsearch/guide/master/term-vs-full-text.html)

To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (https://www.elastic.co/blog/strings-are-dead-long-live-strings)

FormsAuthentication.SignOut() does not log the user out

Sounds to me like you don't have your web.config authorization section set up properly within . See below for an example.

<authentication mode="Forms">
  <forms name="MyCookie" loginUrl="Login.aspx" protection="All" timeout="90" slidingExpiration="true"></forms>
</authentication>
<authorization>
  <deny users="?" />
</authorization>

Changing the URL in react-router v4 without using Redirect or Link

Try this,

this.props.router.push('/foo')

warning works for versions prior to v4

and

this.props.history.push('/foo')

for v4 and above

Angular and Typescript: Can't find names - Error: cannot find name

There is a work-around mentioned in the changelog for 2.0.0-beta.6 (2016-02-11) (listed under breaking changes):

If you use --target=es5, you will need to add a line somewhere in your application (for example, at the top of the .ts file where you call bootstrap):

///<reference path="node_modules/angular2/typings/browser.d.ts"/>

(Note that if your file is not in the same directory as node_modules, you'll need to add one or more ../ to the start of that path.)

make sure you have the correct reference path, i needed to add ../ to the start to get this working.

Stop floating divs from wrapping

The only way I've managed to do this is by using overflow: visible; and width: 20000px; on the parent element. There is no way to do this with CSS level 1 that I'm aware of and I refused to think I'd have to go all gung-ho with CSS level 3. The example below has 18 menus that extend beyond my 1920x1200 resolution LCD, if your screen is larger just duplicate the first tier menu elements or just resize the browser. Alternatively and with slightly lower levels of browser compatibility you could use CSS3 media queries.

Here is a full copy/paste example demonstration...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>XHTML5 Menu Demonstration</title>
<style type="text/css">
* {border: 0; box-sizing: content-box; color: #f0f; font-size: 10px; margin: 0; padding: 0; transition-property: background-color, background-image, border, box-shadow, color, float, opacity, text-align, text-shadow; transition-duration: 0.5s; white-space: nowrap;}
a:link {color: #79b; text-decoration: none;}
a:visited {color: #579;}
a:focus, a:hover {color: #fff; text-decoration: underline;}
body {background-color: #444; overflow-x: hidden;}
body > header {background-color: #000; height: 64px; left: 0; position: absolute; right: 0; z-index: 2;}
body > header > nav {height: 32px; margin-left: 16px;}
body > header > nav a {font-size: 24px;}
main {border-color: transparent; border-style: solid; border-width: 64px 0 0; bottom: 0px; left: 0; overflow-x: hidden !important; overflow-y: auto; position: absolute; right: 0; top: 0; z-index: 1;}
main > * > * {background-color: #000;}
main > section {float: left; margin-top: 16px; width: 100%;}
nav[id='menu'] {overflow: visible; width: 20000px;}
nav[id='menu'] > ul {height: 32px;}
nav[id='menu'] > ul > li {float: left; width: 140px;}
nav[id='menu'] > ul > li > ul {background-color: rgba(0, 0, 0, 0.8); display: none; margin-left: -50px; width: 240px;}
nav[id='menu'] a {display: block; height: 32px; line-height: 32px; text-align: center; white-space: nowrap;}
nav[id='menu'] > ul {float: left; list-style:none;}
nav[id='menu'] ul li:hover ul {display: block;}
p, p *, span, span * {color: #fff;}
p {font-size: 20px; margin: 0 14px 0 14px; padding-bottom: 14px; text-indent: 1.5em;}
.hidden {display: none;}
.width_100 {width: 100%;}
</style>
</head>

<body>

<main>
<section style="height: 2000px;"><p>Hover the first menu at the top-left.</p></section>
</main>

<header>
<nav id="location"><a href="">Example</a><span> - </span><a href="">Blog</a><span> - </span><a href="">Browser Market Share</a></nav>
<nav id="menu">
<ul>
<li><a href="" tabindex="2">Menu 1 - Hover</a>
<ul>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
</ul>
</li>
<li><a href="" tabindex="2">Menu 2</a></li>
<li><a href="" tabindex="2">Menu 3</a></li>
<li><a href="" tabindex="2">Menu 4</a></li>
<li><a href="" tabindex="2">Menu 5</a></li>
<li><a href="" tabindex="2">Menu 6</a></li>
<li><a href="" tabindex="2">Menu 7</a></li>
<li><a href="" tabindex="2">Menu 8</a></li>
<li><a href="" tabindex="2">Menu 9</a></li>
<li><a href="" tabindex="2">Menu 10</a></li>
<li><a href="" tabindex="2">Menu 11</a></li>
<li><a href="" tabindex="2">Menu 12</a></li>
<li><a href="" tabindex="2">Menu 13</a></li>
<li><a href="" tabindex="2">Menu 14</a></li>
<li><a href="" tabindex="2">Menu 15</a></li>
<li><a href="" tabindex="2">Menu 16</a></li>
<li><a href="" tabindex="2">Menu 17</a></li>
<li><a href="" tabindex="2">Menu 18</a></li>
</ul>
</nav>
</header>

</body>
</html>

Check mySQL version on Mac 10.8.5

Or just call mysql command with --version option.

mysql --version

Maven: The packaging for this project did not assign a file to the build artifact

This error shows up when using the maven-install-plugin version 3.0.0-M1 (or similar)

As already mentioned above and also here the following plug-in version works:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.5.2</version>
    </plugin>

Python Progress Bar

@Massagran: It works well in my programs. Furthermore, we need to add a counter to indicate the loop times. This counter plays as the argument of the method update. For example: read all lines of a test file and treat them on something. Suppose that the function dosth() do not concern in the variable i.

lines = open(sys.argv[1]).readlines()
i = 0
widgets=[Percentage(), Bar()]
pbar = ProgressBar(widgets=widgets,maxval=len(lines)).start()
pbar.start()
for line in lines:<pre>
    dosth();
    i += 1
    pbar.update(i)</pre>
pbar.finish()

The variable i controls the status of pbar via the method update

How can I check which version of Angular I'm using?

Same like above answer, you can check in browser by inspecting element, if it is AngularJS we can see something like below.

The ng-app directive tells AngularJS that this is the root element of the AngularJS application.

All AngularJS applications must have a root element.

How to make a phone call using intent in Android?

    final public void Call(View view){

    try {

        EditText editt=(EditText)findViewById(R.id.ed1);
        String str=editt.getText().toString();
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+str));
        startActivity(intent);
    }
    catch (android.content.ActivityNotFoundException e){

        Toast.makeText(getApplicationContext(),"App failed",Toast.LENGTH_LONG).show();
    }

Mocking a class: Mock() or patch()?

mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:

>>> class MyClass(object):
...   def __init__(self):
...     print 'Created MyClass@{0}'.format(id(self))
... 
>>> def create_instance():
...   return MyClass()
... 
>>> x = create_instance()
Created MyClass@4299548304
>>> 
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
...   MyClass.return_value = 'foo'
...   return create_instance()
... 
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
...   print MyClass
...   return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>

patch replaces MyClass in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.

mock.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClass instead of receiving an instance as a parameter, then mock.patch would be appropriate here.

Should IBOutlets be strong or weak under ARC?

WARNING, OUTDATED ANSWER: this answer is not up to date as per WWDC 2015, for the correct answer refer to the accepted answer (Daniel Hall) above. This answer will stay for record.


Summarized from the developer library:

From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because:

  • Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.

  • The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).

    @property (weak) IBOutlet MyView *viewContainerSubview;
    @property (strong) IBOutlet MyOtherClass *topLevelObject;
    

How to create a file in a directory in java?

String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
    File f = new File(path);
    File f1 = new File(fname);

    f.mkdirs() ;
    try {
        f1.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

This should create a new file inside a directory

How to check if a string "StartsWith" another string?

Since this is so popular I think it is worth pointing out that there is an implementation for this method in ECMA 6 and in preparation for that one should use the 'official' polyfill in order to prevent future problems and tears.

Luckily the experts at Mozilla provide us with one:

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position) {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
    };
}

Please note that this has the advantage of getting gracefully ignored on transition to ECMA 6.

How to show android checkbox at right side?

The following link demonstrates how to render seveveral Standard Android view objects with an animated checkbox on the right by setting the right drawable.

Set the background to get a ripple effect.

[link to website with example checkbox on right and left side.][1] http://landenlabs.com/android/uicomponents/uicomponents.html#checkbox

         <Button
            android:id="@+id/p2Button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="Button"
            android:textAllCaps="false"

            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/p2Button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="AppCompatButton"
            android:textAllCaps="false"

            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <TextView
            android:id="@+id/p2TextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:hapticFeedbackEnabled="true"

            android:text="TextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/p2TextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@drawable/transparent_ripple"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:hapticFeedbackEnabled="true"

            android:text="AppCompatTextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/white" />

        <CheckBox
            android:id="@+id/p2Checkbox1"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:button="@null"
            android:checked="true"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="CheckBox"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/p2Checkbox2"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:button="@null"
            android:checked="true"
            android:drawableRight="@drawable/checkline"
            android:gravity="left|center_vertical"
            android:text="AppCompatCheckBox"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <android.support.v7.widget.AppCompatCheckedTextView
            android:id="@+id/p2Checkbox3"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checkMark="@drawable/checkline"
            android:checked="true"
            android:gravity="left|center_vertical"
            android:text="AppCompatCheckedTextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <!--  android:checkMark="?android:attr/listChoiceIndicatorMultiple" -->
        <CheckedTextView
            android:id="@+id/p2Checkbox4"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checkMark="@drawable/checkline"
            android:checked="true"
            android:gravity="left|center_vertical"
            android:text="CheckedTextView"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <CheckBox
            android:id="@+id/p2Checkbox5"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checked="true"
            android:gravity="center_vertical|end"
            android:text="CheckBox"
            android:textColor="@android:color/white"
            android:textSize="@dimen/buttonTextSize" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/white" />


        <ToggleButton
            android:id="@+id/p2ToggleButton1"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checked="true"
            android:drawableRight="@drawable/checkline"
            android:gravity="center_vertical|left"
            android:textAllCaps="false"
            android:textColor="@android:color/white"

            android:textOff="ToggleButtonOff"

            android:textOn="ToggleButtonOn"
            android:textSize="@dimen/buttonTextSize" />

        <ToggleButton
            android:id="@+id/p2ToggleButton2"
            android:layout_width="match_parent"
            android:layout_height="@dimen/buttonHeight"
            android:background="@drawable/transparent_ripple"
            android:checked="true"
            android:drawableRight="@drawable/btn_check_material_anim"
            android:gravity="center_vertical|left"
            android:textAllCaps="false"

            android:textColor="@android:color/white"
            android:textOff="ToggleBtnnAnimOff"
            android:textOn="ToggleBtnnAnimOn"
            android:textSize="@dimen/buttonTextSize" />

Sample checkline.xml (in drawable, see link for animated version in drawable-v21)

Sample transparent_ripple.xml (in drawable-v21)

<!-- Limit ripple to view object, can also use shape such as oval -->
<item android:id="@android:id/mask" android:drawable="@android:color/white" />

<item>
    <selector xmlns:android="http://schemas.android.com/apk/res/android"
        android:enterFadeDuration="200"
        android:exitFadeDuration="200">

        <item android:state_pressed="true">
            <shape android:shape="rectangle">
                <solid android:color="#80c0c000" />
            </shape>
        </item>
    </selector>
</item>


Sample transparent_ripple.xml (in drawable, highlight only no ripple available

<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <solid android:color="#80c0c000" />
    </shape>
</item>
<item>
    <shape android:shape="rectangle">
        <solid android:color="@android:color/transparent" />
    </shape>
</item>

Difference between rake db:migrate db:reset and db:schema:load

TLDR

Use

  • rake db:migrate If you wanna make changes to the schema
  • rake db:reset If you wanna drop the database, reload the schema from schema.rb, and reseed the database
  • rake db:schema:load If you wanna reset database to schema as provided in schema.rb (This will delete all data)

Explanations

rake db:schema:load will set up the schema as provided in schema.rb file. This is useful for a fresh install of app as it doesn't take as much time as db:migrate

Important note, db:schema:load will delete data on server.

rake db:migrate makes changes to the existing schema. Its like creating versions of schema. db:migrate will look in db/migrate/ for any ruby files and execute the migrations that aren't run yet starting with the oldest. Rails knows which file is the oldest by looking at the timestamp at the beginning of the migration filename. db:migrate comes with a benefit that data can also be put in the database. This is actually not a good practice. Its better to use rake db:seed to add data.

rake db:migrate provides tasks up, down etc which enables commands like rake db:rollback and makes it the most useful command.

rake db:reset does a db:drop and db:setup
It drops the database, create it again, loads the schema, and initializes with the seed data

Relevant part of the commands from databases.rake


namespace :schema do
  desc 'Creates a db/schema.rb file that is portable against any DB supported by Active Record'
  task :dump => [:environment, :load_config] do
    require 'active_record/schema_dumper'
    filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb')
    File.open(filename, "w:utf-8") do |file|
      ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
    end
    db_namespace['schema:dump'].reenable
  end

  desc 'Loads a schema.rb file into the database'
  task :load => [:environment, :load_config, :check_protected_environments] do
    ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV['SCHEMA'])
  end

  # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
  task :reset => [ 'db:drop', 'db:setup' ]

namespace :migrate do
  # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
  task :redo => [:environment, :load_config] do
    if ENV['VERSION']
      db_namespace['migrate:down'].invoke
      db_namespace['migrate:up'].invoke
    else
      db_namespace['rollback'].invoke
      db_namespace['migrate'].invoke
    end
  end

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

CSS: how do I create a gap between rows in a table?

This is the way (I was thinking it's impossible):

First give the table only vertical border-spacing (for example 5px) and set it's horizontal border-spacing to 0. Then you should give proper borders to each row cell. For example the right-most cell in each row should have border on top, bottom and right. The left-most cells should have border on top, bottom and left. And the other cells between these 2 should only have border on top and bottom. Like this example:

<table style="border-spacing:0 5px; color:black">
    <tr>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-left:thin black solid;">left-most cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-right:thin black solid;">right-most cell</td>
    </tr>
    <tr>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-left:thin black solid;">left-most cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-right:thin black solid;">right-most cell</td>
    </tr>
    <tr>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-left:thin black solid;">left-most cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid;">other cell</td>
        <td style="border-bottom:thin black solid; border-top:thin black solid; border-right:thin black solid;">right-most cell</td>
    </tr>
</table>

Apply CSS rules to a nested class inside a div

You use

#main_text .title {
  /* Properties */
}

If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:

#main_text > .title {
  /* Properties */
}

Either will work in this case, but the first is more typically used.

Hibernate Auto Increment ID

FYI

Using netbeans New Entity Classes from Database with a mysql *auto_increment* column, creates you an attribute with the following annotations:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
@NotNull
private Integer id;

This was getting me the same an error saying the column must not be null, so i simply removed the @NotNull anotation leaving the attribute null, and it works!

How to parse JSON array in jQuery?

Do NOT eval. use a real parser, i.e., from json.org

How to open/run .jar file (double-click not working)?

I had this problem a while back and the solution was really easy.

Just uninstall the current version of Java, download an older one, then uninstall the older and install the latest again.

For example: Java 8 Update 73 current install Java 7 Update 95.

How it works: Java's registry keys were messed up, and when you install the older version they get fixed.

Definition of a Balanced Tree

Balanced tree is a tree whose height is of order of log(number of elements in the tree).

height = O(log(n))
O, as in asymptotic notation i.e. height should have same or lower asymptotic
growth rate than log(n)
n: number of elements in the tree

The definition given "a tree is balanced of each sub-tree is balanced and the height of the two sub-trees differ by at most one" is followed by AVL trees.

Since, AVL trees are balanced but not all balanced trees are AVL trees, balanced trees don't hold this definition and internal nodes can be unbalanced in them. However, AVL trees require all internal nodes to be balanced.

How to check if activity is in foreground or in visible background?

I used to do like,

if the activity is not in the foreground

getIntent()

will return null. :=P

How to say no to all "do you want to overwrite" prompts in a batch file copy?

Adding the switches for subdirectories and verification work just fine. echo n | xcopy/-Y/s/e/v c:\source*.* c:\Dest\

How to set a default value for an existing column

cannot use alter column for that, use add instead

ALTER TABLE Employee 
ADD DEFAULT('SANDNES') FOR CityBorn

Git list of staged files

You can Try using :- git ls-files -s

SQL - select distinct only on one column

You will use the following query:

SELECT * FROM [table] GROUP BY NUMBER;

Where [table] is the name of the table.

This provides a unique listing for the NUMBER column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.

SQL exclude a column using SELECT * [except columnA] FROM tableA?

I do not know of any database that supports this (SQL Server, MySQL, Oracle, PostgreSQL). It is definitely not part of the SQL standards so I think you have to specify only the columns you want.

You could of course build your SQL statement dynamically and have the server execute it. But this opens up the possibility for SQL injection..

How to set UITextField height?

A UITextField's height is not adjustable in Attributes Inspector only when it has the default rounded corners border style, but adding a height constraint (plus any other constraints which are required to satisfy the autolayout system - often by simply using Add Missing Constraints) to it and adjusting the constraint will adjust the textfield's height. If you don't want constraints, the constraints can be removed (Clear Constraints) and the textfield will remain at the adjusted height.

Works like a charm.

How do I debug Windows services in Visual Studio?

Use the following code in service OnStart method:

System.Diagnostics.Debugger.Launch();

Choose the Visual Studio option from the pop up message.

Note: To use it in only Debug mode, a #if DEBUG compiler directive can be used, as follows. This will prevent accidental or debugging in release mode on a production server.

#if DEBUG
    System.Diagnostics.Debugger.Launch();
#endif

Return rows in random order

This is the simplest solution:

SELECT quote FROM quotes ORDER BY RAND() 

Although it is not the most efficient. This one is a better solution.

How to make a stable two column layout in HTML/CSS

Here you go:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Cols</title>_x000D_
  <style>_x000D_
    #left {_x000D_
      width: 200px;_x000D_
      float: left;_x000D_
    }_x000D_
    #right {_x000D_
      margin-left: 200px;_x000D_
      /* Change this to whatever the width of your left column is*/_x000D_
    }_x000D_
    .clear {_x000D_
      clear: both;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="container">_x000D_
    <div id="left">_x000D_
      Hello_x000D_
    </div>_x000D_
    <div id="right">_x000D_
      <div style="background-color: red; height: 10px;">Hello</div>_x000D_
    </div>_x000D_
    <div class="clear"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

See it in action here: http://jsfiddle.net/FVLMX/

Difference between Relative path and absolute path in javascript

What is the difference between Relative path and absolute path?

One has to be calculated with respect to another URI. The other does not.

Is there any performance issues occures for using these paths?

Nothing significant.

We will get any secure for the sites ?

No

Is there any way to converting absolute path to relative

In really simplified terms: Working from left to right, try to match the scheme, hostname, then path segments with the URI you are trying to be relative to. Stop when you have a match.

How to revert a "git rm -r ."?

Get list commit

git log  --oneline

For example, Stable commit has hash: 45ff319c360cd7bd5442c0fbbe14202d20ccdf81

git reset --hard 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git push -ff origin master

The application was unable to start correctly (0xc000007b)

It is a missing dll. Possibly, your dll that works with com ports have an unresolved dll dependence. You can use dependency walker and windows debugger. Check all of the mfc library, for example. Also, you can use nrCommlib - it is great components to work with com ports.

What are the options for storing hierarchical data in a relational database?

I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:

CREATE FUNCTION nomen_tree() RETURNS trigger
    LANGUAGE plpgsql
    AS $_$
DECLARE
  old_parent INTEGER;
  new_parent INTEGER;
  id_nom INTEGER;
  txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
    IF TG_OP = 'INSERT' THEN
    EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT $1.id,$1.id,0 UNION ALL
      SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
    ELSE                                                           
    -- EXECUTE does not support conditional statements inside
    EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
    IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
      EXECUTE '
      -- prevent cycles in the tree
      UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
        || ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
        || TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
      -- first remove edges between all old parents of node and its descendants
      DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
        (SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
        AND ancestor_id IN
        (SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
      -- then add edges for all new parents ...
      INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT child_id,ancestor_id,d_c+d_a FROM
        (SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
        CROSS JOIN
        (SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.' 
        || TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
    END IF;
  END IF;
  RETURN NULL;
END;
$_$;

Then for each table where I have a hierarchy, I create a trigger

CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');

For populating a closure table from existing hierarchy I use this stored procedure:

CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    EXECUTE 'TRUNCATE ' || tbl_closure || ';
    INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth) 
        WITH RECURSIVE tree AS
      (
        SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
        UNION ALL 
        SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
        JOIN tree ON child_id = ' || fld_parent || '
      )
      SELECT * FROM tree;';
END;
$$;

Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:

-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;

Python integer incrementing with ++

Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.

Fortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().

READ_EXTERNAL_STORAGE permission for Android

Please Check below code that using that You can find all Music Files from sdcard :

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animations);
    getAllSongsFromSDCARD();

}

public void getAllSongsFromSDCARD() {
    String[] STAR = { "*" };
    Cursor cursor;
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    cursor = managedQuery(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String song_name = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                int song_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media._ID));

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String album_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                int album_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artist_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                System.out.println("sonng name"+fullpath);
            } while (cursor.moveToNext());

        }
        cursor.close();
    }
}


}

I have also added following line in the AndroidManifest.xml file as below:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How can I view the source code for a function?

UseMethod("t") is telling you that t() is a (S3) generic function that has methods for different object classes.

The S3 method dispatch system

For S3 classes, you can use the methods function to list the methods for a particular generic function or class.

> methods(t)
[1] t.data.frame t.default    t.ts*       

   Non-visible functions are asterisked
> methods(class="ts")
 [1] aggregate.ts     as.data.frame.ts cbind.ts*        cycle.ts*       
 [5] diffinv.ts*      diff.ts          kernapply.ts*    lines.ts        
 [9] monthplot.ts*    na.omit.ts*      Ops.ts*          plot.ts         
[13] print.ts         time.ts*         [<-.ts*          [.ts*           
[17] t.ts*            window<-.ts*     window.ts*      

   Non-visible functions are asterisked

"Non-visible functions are asterisked" means the function is not exported from its package's namespace. You can still view its source code via the ::: function (i.e. stats:::t.ts), or by using getAnywhere(). getAnywhere() is useful because you don't have to know which package the function came from.

> getAnywhere(t.ts)
A single object matching ‘t.ts’ was found
It was found in the following places
  registered S3 method for t from namespace stats
  namespace:stats
with value

function (x) 
{
    cl <- oldClass(x)
    other <- !(cl %in% c("ts", "mts"))
    class(x) <- if (any(other)) 
        cl[other]
    attr(x, "tsp") <- NULL
    t(x)
}
<bytecode: 0x294e410>
<environment: namespace:stats>

The S4 method dispatch system

The S4 system is a newer method dispatch system and is an alternative to the S3 system. Here is an example of an S4 function:

> library(Matrix)
Loading required package: lattice
> chol2inv
standardGeneric for "chol2inv" defined from package "base"

function (x, ...) 
standardGeneric("chol2inv")
<bytecode: 0x000000000eafd790>
<environment: 0x000000000eb06f10>
Methods may be defined for arguments: x
Use  showMethods("chol2inv")  for currently available ones.

The output already offers a lot of information. standardGeneric is an indicator of an S4 function. The method to see defined S4 methods is offered helpfully:

> showMethods(chol2inv)
Function: chol2inv (package base)
x="ANY"
x="CHMfactor"
x="denseMatrix"
x="diagonalMatrix"
x="dtrMatrix"
x="sparseMatrix"

getMethod can be used to see the source code of one of the methods:

> getMethod("chol2inv", "diagonalMatrix")
Method Definition:

function (x, ...) 
{
    chk.s(...)
    tcrossprod(solve(x))
}
<bytecode: 0x000000000ea2cc70>
<environment: namespace:Matrix>

Signatures:
        x               
target  "diagonalMatrix"
defined "diagonalMatrix"

There are also methods with more complex signatures for each method, for example

require(raster)
showMethods(extract)
Function: extract (package raster)
x="Raster", y="data.frame"
x="Raster", y="Extent"
x="Raster", y="matrix"
x="Raster", y="SpatialLines"
x="Raster", y="SpatialPoints"
x="Raster", y="SpatialPolygons"
x="Raster", y="vector"

To see the source code for one of these methods the entire signature must be supplied, e.g.

getMethod("extract" , signature = c( x = "Raster" , y = "SpatialPolygons") )

It will not suffice to supply the partial signature

getMethod("extract",signature="SpatialPolygons")
#Error in getMethod("extract", signature = "SpatialPolygons") : 
#  No method found for function "extract" and signature SpatialPolygons

Functions that call unexported functions

In the case of ts.union, .cbindts and .makeNamesTs are unexported functions from the stats namespace. You can view the source code of unexported functions by using the ::: operator or getAnywhere.

> stats:::.makeNamesTs
function (...) 
{
    l <- as.list(substitute(list(...)))[-1L]
    nm <- names(l)
    fixup <- if (is.null(nm)) 
        seq_along(l)
    else nm == ""
    dep <- sapply(l[fixup], function(x) deparse(x)[1L])
    if (is.null(nm)) 
        return(dep)
    if (any(fixup)) 
        nm[fixup] <- dep
    nm
}
<bytecode: 0x38140d0>
<environment: namespace:stats>

Functions that call compiled code

Note that "compiled" does not refer to byte-compiled R code as created by the compiler package. The <bytecode: 0x294e410> line in the above output indicates that the function is byte-compiled, and you can still view the source from the R command line.

Functions that call .C, .Call, .Fortran, .External, .Internal, or .Primitive are calling entry points in compiled code, so you will have to look at sources of the compiled code if you want to fully understand the function. This GitHub mirror of the R source code is a decent place to start. The function pryr::show_c_source can be a useful tool as it will take you directly to a GitHub page for .Internal and .Primitive calls. Packages may use .C, .Call, .Fortran, and .External; but not .Internal or .Primitive, because these are used to call functions built into the R interpreter.

Calls to some of the above functions may use an object instead of a character string to reference the compiled function. In those cases, the object is of class "NativeSymbolInfo", "RegisteredNativeSymbol", or "NativeSymbol"; and printing the object yields useful information. For example, optim calls .External2(C_optimhess, res$par, fn1, gr1, con) (note that's C_optimhess, not "C_optimhess"). optim is in the stats package, so you can type stats:::C_optimhess to see information about the compiled function being called.

Compiled code in a package

If you want to view compiled code in a package, you will need to download/unpack the package source. The installed binaries are not sufficient. A package's source code is available from the same CRAN (or CRAN compatible) repository that the package was originally installed from. The download.packages() function can get the package source for you.

download.packages(pkgs = "Matrix", 
                  destdir = ".",
                  type = "source")

This will download the source version of the Matrix package and save the corresponding .tar.gz file in the current directory. Source code for compiled functions can be found in the src directory of the uncompressed and untared file. The uncompressing and untaring step can be done outside of R, or from within R using the untar() function. It is possible to combine the download and expansion step into a single call (note that only one package at a time can be downloaded and unpacked in this way):

untar(download.packages(pkgs = "Matrix",
                        destdir = ".",
                        type = "source")[,2])

Alternatively, if the package development is hosted publicly (e.g. via GitHub, R-Forge, or RForge.net), you can probably browse the source code online.

Compiled code in a base package

Certain packages are considered "base" packages. These packages ship with R and their version is locked to the version of R. Examples include base, compiler, stats, and utils. As such, they are not available as separate downloadable packages on CRAN as described above. Rather, they are part of the R source tree in individual package directories under /src/library/. How to access the R source is described in the next section.

Compiled code built into the R interpreter

If you want to view the code built-in to the R interpreter, you will need to download/unpack the R sources; or you can view the sources online via the R Subversion repository or Winston Chang's github mirror.

Uwe Ligges's R news article (PDF) (p. 43) is a good general reference of how to view the source code for .Internal and .Primitive functions. The basic steps are to first look for the function name in src/main/names.c and then search for the "C-entry" name in the files in src/main/*.

Outline radius?

You're looking for something like this, I think.

div {
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    border: 1px solid black;
    background-color: #CCC;
    height: 100px;
    width: 160px;
}

Edit

There is a Firefox-only -moz-outline-radius properly, but that won't work on IE/Chrome/Safari/Opera/etc. So, it looks like the most cross-browser-compatible way* to get a curved line around a border is to use a wrapper div:

_x000D_
_x000D_
div.inner {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  border: 1px solid black;
  background-color: #CCC;
  height: 100px;
  width: 160px;
}

div.outer {
  display: inline-block;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
  border: 1px solid red;
}
_x000D_
<div class="outer">
  <div class="inner"></div>
</div>
_x000D_
_x000D_
_x000D_


*aside from using images

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

Fixed positioned div within a relative parent div

An easy solution that doesn't involve resorting to JavaScript and will not break CSS transforms is to simply have a non-scrolling element, the same size as your scrolling element, absolute-positioned over it.

The basic HTML structure would be

CSS

<style>
    .parent-to-position-by {
        position: relative;
        top: 40px; /* just to show it's relative positioned */
    }
    .scrolling-contents {
        display: inline-block;
        width: 100%;
        height: 200px;
        line-height: 20px;
        white-space: nowrap;
        background-color: #CCC;
        overflow: scroll;
    }
    .fixed-elements {
        display: inline-block;
        position: absolute;
        top: 0;
        left: 0;
    }
    .fixed {
        position: absolute; /* effectively fixed */
        top: 20px;
        left: 20px;
        background-color: #F00;
        width: 200px;
        height: 20px;
    }
</style>

HTML

<div class="parent-to-position-by">
    <div class="fixed-elements">
        <div class="fixed">
            I am &quot;fixed positioned&quot;
        </div>
    </div>
    <div class="scrolling-contents">
        Lots of contents which may be scrolled.
    </div>
</div>
  • parent-to-position-by would be the relative div to position something fixed with respect to.
  • scrolling-contents would span the size of this div and contain its main contents
  • fixed-elements is just an absolute-positioned div spanning the same space over top of the scrolling-contents div.
  • by absolute-positioning the div with the fixed class, it achieves the same effect as if it were fixed-positioned with respect to the parent div. (or the scrolling contents, as they span that full space)

Here's a js-fiddle with a working example

creating list of objects in Javascript

dynamically build list of objects

var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    listOfObjects.push(singleObj);
});

here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output

Aligning textviews on the left and right edges in Android layout

Use a RelativeLayout with layout_alignParentLeft and layout_alignParentRight:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout01" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:padding="10dp">

    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" 
        android:id="@+id/mytextview1"/>

    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentRight="true" 
        android:id="@+id/mytextview2"/>

</RelativeLayout>

Also, you should probably be using dip (or dp) rather than sp in your layout. sp reflect text settings as well as screen density so they're usually only for sizing text items.

How to change workspace and build record Root Directory on Jenkins?

If you go into Configure under Home there is a "Help" note on how to:

Home directory /var/lib/jenkins Help for feature: Home directory

By default, Jenkins stores all of its data in this directory on the file system.

There are a few ways to change the Jenkins home directory:

Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
Use your web container's admin tool to set the JENKINS_HOME environment variable.
Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended. 

This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.

A server with the specified hostname could not be found

I received A server with the specified hostname could not be found.. I figured out my MacOS app had turned on App Sandboxing. The easiest way to avoid problem is to turn off Sandbox.

Pretty-Printing JSON with PHP

This function will take JSON string and indent it very readable. It also should be convergent,

prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )

Input

{"key1":[1,2,3],"key2":"value"}

Output

{
    "key1": [
        1,
        2,
        3
    ],
    "key2": "value"
}

Code

function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
            switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
        }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;
}

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

They are the same when used for output, e.g. with printf.

However, these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal (if preceded by 0).

So 033 would be 27 with %i but 33 with %d.

C# - How to get Program Files (x86) on Windows 64 bit

Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)

How to implement a Map with multiple keys?

A dirty and a simple solution, if you use the maps just for sorting lets say, is to add a very small value to a key until the value does not exist, but do not add the minimum (for example Double.MIN_VALUE) because it will cause a bug. Like I said, this is a very dirty solution but it makes the code simpler.

How much should a function trust another function

If it is in the same class it is fine to trust the method.

It is very common to do this. It is good practice to check null values in constructor's and method's arguments to make sure that nobody is passing null values into them (if it is not allowed). Then if you implement your methods in a way that they never set the "start" graph to null, don't check for nulls there.

It is also good practice to implement unit tests for your methods and make sure that they are correctly implemented, so you can trust them.

Can a CSV file have a comment?

No, CSV doesn't specify any way of tagging comments - they will just be loaded by programs like Excel as additional cells containing text.

The closest you can manage (with CSV being imported into a specific application such as Excel) is to define a special way of tagging comments that Excel will ignore. For Excel, you can "hide" the comment (to a limited degree) by embedding it into a formula. For example, try importing the following csv file into Excel:

=N("This is a comment and will appear as a simple zero value in excel")
John, Doe, 24

You still end up with a cell in the spreadsheet that displays the number 0, but the comment is hidden.

Alternatively, you can hide the text by simply padding it out with spaces so that it isn't displayed in the visible part of cell:

                              This is a sort-of hidden comment!,
John, Doe, 24

Note that you need to follow the comment text with a comma so that Excel fills the following cell and thus hides any part of the text that doesn't fit in the cell.

Nasty hacks, which will only work with Excel, but they may suffice to make your output look a little bit tidier after importing.

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

"Cannot update paths and switch to branch at the same time"

You can use these commands: git remote update, git fetch, git checkout -b branch_nameA origin:branch_nameB

I think maybe it's because of your local branch can not track remote branch

TypeError: $.ajax(...) is not a function?

There is a syntax error as you have placed parenthesis after ajax function and another set of parenthesis to define the argument list:-

As you have written:-

$.ajax() ({
    type: 'POST',
    url: url,
    data: postedData,
    dataType: 'json',
    success: callback
});

The parenthesis around ajax has to be removed it should be:-

$.ajax({
    type: 'POST',
    url: url,
    data: postedData,
    dataType: 'json',
    success: callback
});

Python Error: "ValueError: need more than 1 value to unpack"

You should run your code in a following manner in order get your output,

python file_name.py user_name

remove url parameters with javascript or jquery

Example: http://jsfiddle.net/SjrqF/

var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';

url = url.slice( 0, url.indexOf('&') );

or:

Example: http://jsfiddle.net/SjrqF/1/

var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';

url = url.split( '&' )[0];

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

How to launch html using Chrome at "--allow-file-access-from-files" mode?

REM Kill all existing instance of chrome 
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files

save above lines as .bat file

How to enable production mode?

When I built a new project using angular-cli. A file was included called environment.ts. Inside this file is a variable like so.

export const environment = {
  production: true
};

Then in main.ts you have this.

import './polyfills.ts';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

You could add this to a non angular-cli project, I would assume, because enableProdMode() is being imported from @angular/core.

How to center a Window in Java?

This should work in all versions of Java

public static void centreWindow(Window frame) {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, y);
}

In Oracle SQL: How do you insert the current date + time into a table?

You may try with below query :

INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );

To view the result of it:

SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss') 
FROM errortable 
    WHERE table1id = 1083;

get string from right hand side

the pattern maybe looks like this :

substr(STRING, ( length(STRING) - (TOTAL_GET_LENGTH - 1) ),TOTAL_GET_LENGTH)

in your case , it will like this :

substr('299123456789', (length('299123456789')-(9 - 1)),9)

substr('299123456789', (12-8),9)

substr('299123456789', 4,9)

the result ? of course '123456789'

the length is dynamic , voila :)

Set min-width in HTML table's <td>

<table style="min-width:50px; max-width:150px;">
    <tr>
        <td style="min-width:50px">one</td>
        <td style="min-width:100px">two</td>
    </tr>
</table>

This works for me using an email script.

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

Find nginx version?

Make sure that you have permissions to run the following commands.

If you check the man page of nginx from a terminal

man nginx

you can find this:

-V             Print the nginx version, compiler version, and configure script parameters.

-v             Print the nginx version.

Then type in terminal

nginx -v
nginx version: nginx/1.14.0

nginx -V
nginx version: nginx/1.14.0
built with OpenSSL 1.1.0g  2 Nov 2017
TLS SNI support enabled

If nginx is not installed in your system man nginx command can not find man page, so make sure you have installed nginx.

You can also find the version using this command:

Use one of the command to find the path of nginx

ps aux | grep nginx
ps -ef | grep nginx

root       883  0.0  0.3  44524  3388 ?        Ss   Dec07   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on

Then run from terminal:

/usr/sbin/nginx -v

nginx version: nginx/1.14.0

JSON Structure for List of Objects

As others mentioned, Justin's answer was close, but not quite right. I tested this using Visual Studio's "Paste JSON as C# Classes"

{
    "foos" : [
        {
            "prop1":"value1",
            "prop2":"value2"
        },
        {
            "prop1":"value3", 
            "prop2":"value4"
        }
    ]
}

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

Calling the base class constructor from the derived class constructor

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

Unzip files programmatically in .net

Free, and no external DLL files. Everything is in one CS file. One download is just the CS file, another download is a very easy to understand example. Just tried it today and I can't believe how simple the setup was. It worked on first try, no errors, no nothing.

https://github.com/jaime-olivares/zipstorer

Excel VBA For Each Worksheet Loop

You need to put the worksheet identifier in your range statements as shown below ...

 Option Explicit
 Dim ws As Worksheet, a As Range

Sub forEachWs()

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next

End Sub

Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

You will find newest version of the chromedriver here: http://chromedriver.storage.googleapis.com/index.html - there is a 64bit version for linux.

How to set JVM parameters for Junit Unit Tests?

In Maven you can configure the surefire plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <argLine>-Xmx256M</argLine>
    </configuration>
</plugin>

If you use Maven for builds then this configuration will be carried in the source tree and applied when tests are carried out. See the Maven Surefire Plugin documentation.

JavaScript: changing the value of onclick with or without jQuery

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

You also said:

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors