Programs & Examples On #Android mediascanner

The MediaScannerConnection class provides a way for applications to pass a newly created or downloaded media file to the media scanner service

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

How to change the background color of the options menu?

For Android 2.3 this can be done with some very heavy hacking:

The root cause for the issues with Android 2.3 is that in LayoutInflater the mConstructorArgs[0] = mContext is only set during running calls to

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.3_r1/android/view/LayoutInflater.java/#352

protected void setMenuBackground(){

    getLayoutInflater().setFactory( new Factory() {

        @Override
        public View onCreateView (final String name, final Context context, final AttributeSet attrs ) {

            if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {

                try { // Ask our inflater to create the view
                    final LayoutInflater f = getLayoutInflater();
                    final View[] view = new View[1]:
                    try {
                        view[0] = f.createView( name, null, attrs );
                    } catch (InflateException e) {
                        hackAndroid23(name, attrs, f, view);
                    }
                    // Kind of apply our own background
                    new Handler().post( new Runnable() {
                        public void run () {
                            view.setBackgroundResource( R.drawable.gray_gradient_background);
                        }
                    } );
                    return view;
                }
                catch ( InflateException e ) {
                }
                catch ( ClassNotFoundException e ) {
                }
            }
            return null;
        }
    });
}

static void hackAndroid23(final String name,
    final android.util.AttributeSet attrs, final LayoutInflater f,
    final TextView[] view) {
    // mConstructorArgs[0] is only non-null during a running call to inflate()
    // so we make a call to inflate() and inside that call our dully XmlPullParser get's called
    // and inside that it will work to call "f.createView( name, null, attrs );"!
    try {
        f.inflate(new XmlPullParser() {
            @Override
            public int next() throws XmlPullParserException, IOException {
                try {
                    view[0] = (TextView) f.createView( name, null, attrs );
                } catch (InflateException e) {
                } catch (ClassNotFoundException e) {
                }
                throw new XmlPullParserException("exit");
            }   
        }, null, false);
    } catch (InflateException e1) {
        // "exit" ignored
    }
}

I tested it to work on Android 2.3 and to still work on earlier versions. If anything breaks again in later Android versions you'll simply see the default menu-style instead

How to update record using Entity Framework Core?

public async Task<bool> Update(MyObject item)
{
    Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
    return (await Context.SaveChangesAsync()) > 0;
}

How do I install a Python package with a .whl file?

I am in the same boat as the OP.

Using a Windows command prompt, from directory:

C:\Python34\Scripts>
pip install wheel

seemed to work.

Changing directory to where the whl was located, it just tells me 'pip is not recognized'. Going back to C:\Python34\Scripts>, then using the full command above to provide the 'where/its/downloaded' location, it says Requirement 'scikit_image-...-win32.whl' looks like a filename, but the filename does not exist.

So I dropped a copy of the .whl in Python34/Scripts, ran the exact same command over again (with the --find-links= still going to the other folder), and this time it worked.

How to decrypt an encrypted Apple iTunes iPhone backup?

Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.

You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.

Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.

I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.

Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.

I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.

In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.

Good luck!

Is it possible to specify a different ssh port when using rsync?

Your command line should look like this:

rsync -rvz -e 'ssh -p 2222' --progress ./dir user@host:/path

this works fine - I use it all the time without needing any new firewall rules - just note the SSH command itself is enclosed in quotes.

Remove an entire column from a data.frame in R

To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset() syntax. E.g. for the data-frame

df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)

to remove just the a column you could do

Data <- subset( Data, select = -a )

and to remove the b and d columns you could do

Data <- subset( Data, select = -c(d, b ) )

You can remove all columns between d and b with:

Data <- subset( Data, select = -c( d : b )

As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset documentation:

Warning:

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.

Best way to make a shell script daemon?

Like many answers this one is not a "real" daemonization but rather an alternative to nohup approach.

echo "script.sh" | at now

There are obviously differences from using nohup. For one there is no detaching from the parent in the first place. Also "script.sh" doesn't inherit parent's environment.

By no means this is a better alternative. It is simply a different (and somewhat lazy) way of launching processes in background.

P.S. I personally upvoted carlo's answer as it seems to be the most elegant and works both from terminal and inside scripts

CSS selector for a checked radio button's label

I forget where I first saw it mentioned but you can actually embed your labels in a container elsewhere as long as you have the for= attribute set. So, let's check out a sample on SO:

_x000D_
_x000D_
* {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
  background-color: #262626;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
.radio-button {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
#filter {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.filter-label {_x000D_
  display: inline-block;_x000D_
  border: 4px solid green;_x000D_
  padding: 10px 20px;_x000D_
  font-size: 1.4em;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
main {_x000D_
  clear: left;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  padding: 3% 10%;_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  font-size: 2em;_x000D_
}_x000D_
_x000D_
.date {_x000D_
  padding: 5px 30px;_x000D_
  font-style: italic;_x000D_
}_x000D_
_x000D_
.filter-label:hover {_x000D_
  background-color: #505050;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~#filter .featured,_x000D_
#personal-radio:checked~#filter .personal,_x000D_
#tech-radio:checked~#filter .tech {_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~main .featured {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#personal-radio:checked~main .personal {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#tech-radio:checked~main .tech {_x000D_
  display: block;_x000D_
}
_x000D_
<input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">_x000D_
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">_x000D_
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">_x000D_
_x000D_
<header id="filter">_x000D_
  <label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>_x000D_
  <label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>_x000D_
  <label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>_x000D_
</header>_x000D_
_x000D_
<main>_x000D_
  <article class="content featured tech">_x000D_
    <header>_x000D_
      <h1>Cool Stuff</h1>_x000D_
      <h3 class="date">Today</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      I'm showing cool stuff in this article!_x000D_
    </p>_x000D_
  </article>_x000D_
_x000D_
  <article class="content personal">_x000D_
    <header>_x000D_
      <h1>Not As Cool</h1>_x000D_
      <h3 class="date">Tuesday</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      This stuff isn't nearly as cool for some reason :(;_x000D_
    </p>_x000D_
  </article>_x000D_
_x000D_
  <article class="content tech">_x000D_
    <header>_x000D_
      <h1>Cool Tech Article</h1>_x000D_
      <h3 class="date">Last Monday</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      This article has awesome stuff all over it!_x000D_
    </p>_x000D_
  </article>_x000D_
_x000D_
  <article class="content featured personal">_x000D_
    <header>_x000D_
      <h1>Cool Personal Article</h1>_x000D_
      <h3 class="date">Two Fridays Ago</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      This article talks about how I got a job at a cool startup because I rock!_x000D_
    </p>_x000D_
  </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Whew. That was a lot for a "sample" but I feel it really drives home the effect and point: we can certainly select a label for a checked input control without it being a sibling. The secret lies in keeping the input tags a child to only what they need to be (in this case - only the body element).

Since the label element doesn't actually utilize the :checked pseudo selector, it doesn't matter that the labels are stored in the header. It does have the added benefit that since the header is a sibling element we can use the ~ generic sibling selector to move from the input[type=radio]:checked DOM element to the header container and then use descendant/child selectors to access the labels themselves, allowing the ability to style them when their respective radio boxes/checkboxes are selected.

Not only can we style the labels, but also style other content that may be descendants of a sibling container relative to all of the inputs. And now for the moment you've all been waiting for, the JSFIDDLE! Go there, play with it, make it work for you, find out why it works, break it, do what you do!

Hopefully that all makes sense and fully answers the question and possibly any follow ups that may crop up.

To find first N prime numbers in python

Here's a simple recursive version:

import datetime
import math

def is_prime(n, div=2):
    if div> int(math.sqrt(n)): return True
    if n% div == 0:
        return False
    else:
        div+=1
        return is_prime(n,div)


now = datetime.datetime.now()

until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)

primelist=[]
i=1;
while len(primelist)<until:
    if is_prime(i):
        primelist.insert(0,i)
        i+=1
    else: i+=1



print "++++++++++++++++++++"
print primelist
finish = datetime.datetime.now()
print "It took your computer", finish - now , "secs to calculate it"

Here's a version using a recursive function with memory!:

import datetime
import math

def is_prime(n, div=2):
    global primelist
    if div> int(math.sqrt(n)): return True
    if div < primelist[0]:
        div = primelist[0]
        for x in primelist:
            if x ==0 or x==1: continue
            if n % x == 0:
                return False
    if n% div == 0:
        return False
    else:
        div+=1
        return is_prime(n,div)


now = datetime.datetime.now()
print 'time and date:',now

until = raw_input("How many prime numbers my lord desires??? ")
until = int(until)

primelist=[]
i=1;
while len(primelist)<until:
    if is_prime(i):
        primelist.insert(0,i)
        i+=1
    else: i+=1



print "Here you go!"
print primelist

finish = datetime.datetime.now()
print "It took your computer", finish - now , " to calculate it"

Hope it helps :)

Convert an ArrayList to an object array

Convert an ArrayList to an object array

ArrayList has a constructor that takes a Collection, so the common idiom is:

List<T> list = new ArrayList<T>(Arrays.asList(array));

Which constructs a copy of the list created by the array.

now, Arrays.asList(array) will wrap the array, so changes to the list will affect the array, and visa versa. Although you can't add or remove

elements from such a list.

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Try this,

string FilePath=@"C:\mydir\myfile.ext";
string Result=Path.GetFileName(FilePath);//With Extension
string Result=Path.GetFileNameWithoutExtension(FilePath);//Without Extension

Convert negative data into positive data in SQL Server

The best solution is: from positive to negative or from negative to positive

For negative:

SELECT ABS(a) * -1 AS AbsoluteA, ABS(b) * -1 AS AbsoluteB
FROM YourTable

For positive:

SELECT ABS(a) AS AbsoluteA, ABS(b)  AS AbsoluteB
FROM YourTable

Error running android: Gradle project sync failed. Please fix your project and try again

I encountered this in a unique situation: had refactored the word "time" to "distance" for one of my variables. And when I did the refactor, accidentally had it change the name of one of my gradle dependencies / implementations.

This is a rare cause of the error, but a possibility. So make sure all your dependencies are properly implemented in build.gradle

proper hibernate annotation for byte[]

I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:

@Entity
public class ConfigAttribute {
  @Lob
  public byte[] getValueBuffer() {
    return m_valueBuffer;
  }
}

as Oracle has no trouble with that, and for Postgres I'm using custom dialect:

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
}

the advantage of this solution I consider, that I can keep hibernate jars untouched.

For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.

Default value in an asp.net mvc view model

Create a base class for your ViewModels with the following constructor code which will apply the DefaultValueAttributeswhen any inheriting model is created.

public abstract class BaseViewModel
{
    protected BaseViewModel()
    {
        // apply any DefaultValueAttribute settings to their properties
        var propertyInfos = this.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (attributes.Any())
            {
                var attribute = (DefaultValueAttribute) attributes[0];
                propertyInfo.SetValue(this, attribute.Value, null);
            }
        }
    }
}

And inherit from this in your ViewModels:

public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".

Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.

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

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

Most efficient way to get table row count

I'm not sure why no one has suggested the following. This will get the auto_increment value using just SQL (no need for using PHP's mysql_fetch_array):

SELECT AUTO_INCREMENT FROM information_schema.tables WHERE TABLE_NAME = 'table'

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

Another solution would be to use Empty.

msdn extract:

Returns an empty IEnumerable that has the specified type argument.

IEnumerable<object> a = Enumerable.Empty<object>();

There is a thread on SO about it: Is it better to use Enumerable.Empty() as opposed to new List to initialize an IEnumerable?

If you use an empty array or empty list, those are objects and they are stored in memory. The Garbage Collector has to take care of them. If you are dealing with a high throughput application, it could be a noticeable impact.

Enumerable.Empty does not create an object per call thus putting less load on the GC.

Deny direct access to all .php files except index.php

Are you sure, you want to do that? Even css and js files and images and ...?

OK, first check if mod_access in installed to apache, then add the following to your .htaccess:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

<Files /index.php>
    Order Allow,Deny
    Allow from all
</Files>

The first directive forbids access to any files except from localhost, because of Order Deny,Allow, Allow gets applied later, the second directive only affects index.php.

Caveat: No space after the comma in the Order line.

To allow access to files matching *.css or *.js use this directive:

<FilesMatch ".*\.(css|js)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

You cannot use directives for <Location> or <Directory> inside .htaccess files, though.

Your option would be to use <FilesMatch ".*\.php$"> around the first allow,deny group and then explicitely allow access to index.php.

Update for Apache 2.4: This answer is correct for Apache 2.2. In Apache 2.4 the access control paradigm has changed, and the correct syntax is to use Require all denied.

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

The following method will allow you to lighten or darken the exposure value of a Hexadecimal (Hex) color string:

private static string GetHexFromRGB(byte r, byte g, byte b, double exposure)
{
    exposure = Math.Max(Math.Min(exposure, 1.0), -1.0);
    if (exposure >= 0)
    {
        return "#"
            + ((byte)(r + ((byte.MaxValue - r) * exposure))).ToString("X2")
            + ((byte)(g + ((byte.MaxValue - g) * exposure))).ToString("X2")
            + ((byte)(b + ((byte.MaxValue - b) * exposure))).ToString("X2");
    }
    else
    {
        return "#"
            + ((byte)(r + (r * exposure))).ToString("X2")
            + ((byte)(g + (g * exposure))).ToString("X2")
            + ((byte)(b + (b * exposure))).ToString("X2");
    }

}

For the last parameter value in GetHexFromRGB(), Pass in a double value somewhere between -1 and 1 (-1 is black, 0 is unchanged, 1 is white):

// split color (#e04006) into three strings
var r = Convert.ToByte("e0", 16);
var g = Convert.ToByte("40", 16);
var b = Convert.ToByte("06", 16);

GetHexFromRGB(r, g, b, 0.25);  // Lighten by 25%;

IndentationError: unexpected indent error

As the error says you have not correctly indented code, check_exists_sql is not aligned with line above it cursor = db.cursor() .

Also use 4 spaces for indentation.

Read this http://diveintopython.net/getting_to_know_python/indenting_code.html

Converting a UNIX Timestamp to Formatted Date String

It is very important to set a default timezone to get the correct result

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

// timestamp
$timestamp = 1307595105;

// output
echo date('d M Y H:i:s Z',$timestamp);
echo date('c',$timestamp);
?> 

Online conversion help: http://freeonlinetools24.com/timestamp

How would you make two <div>s overlap?

With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:

div#logo {
  position: absolute;
  left: 100px; // or whatever
}

Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.

How to disable the parent form when a child form is active?

Have you tried using Form.ShowDialog() instead of Form.Show()?

ShowDialog shows your window as modal, which means you cannot interact with the parent form until it closes.

How can I sort a List alphabetically?

descending alphabet:

List<String> list;
...
Collections.sort(list);
Collections.reverse(list);

Regex to replace multiple spaces with a single space

Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':

string = string.replace(/\s\s+/g, ' ');

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

Conditional Replace Pandas

I would use lambda function on a Series of a DataFrame like this:

f = lambda x: 0 if x>100 else 1
df['my_column'] = df['my_column'].map(f)

I do not assert that this is an efficient way, but it works fine.

What is the correct way to represent null XML elements?

The documentation in the w3 link

http://www.w3.org/TR/REC-xml/#sec-starttags

says that this are the recomended forms.

<test></test>
<test/>

The attribute mentioned in the other answer is validation mechanism and not a representation of state. Please refer to the http://www.w3.org/TR/xmlschema-1/#xsi_nil

XML Schema: Structures introduces a mechanism for signaling that an element should be accepted as ·valid· when it has no content despite a content type which does not require or even necessarily allow empty content. An element may be ·valid· without content if it has the attribute xsi:nil with the value true. An element so labeled must be empty, but can carry attributes if permitted by the corresponding complex type.

To clarify this answer: Content

  <Book>
    <!--Invalid construct since the element attribute xsi:nil="true" signal that the element must be empty-->
    <BuildAttributes HardCover="true" Glued="true" xsi:nil="true">
      <anotherAttribute name="Color">Blue</anotherAttribute>
    </BuildAttributes>
    <Index></Index>
    <pages>
      <page pageNumber="1">Content</page>            
    </pages>
    <!--Missing ISBN number could be confusing and misguiding since its not present-->
  </Book>
</Books>

Run Excel Macro from Outside Excel Using VBScript From Command Line

If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:

Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here

oExcel.DisplayAlerts = False


For Each oFile In oFSO.GetFolder("C:\Location\").Files
    If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
        With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)



            oExcel.Run wb2.Name & "!modForm"


            For Each oSheet In .Worksheets



                oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6


            Next
            .Close False, , False
        End With
    End If



Next
oExcel.Quit
oShell.Popup "Conversion complete", 10

So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.

Python + Django page redirect

There's actually a simpler way than having a view for each redirect - you can do it directly in urls.py:

from django.http import HttpResponsePermanentRedirect

urlpatterns = patterns(
    '',
    # ...normal patterns here...
    (r'^bad-old-link\.php',
     lambda request: HttpResponsePermanentRedirect('/nice-link')),
)

A target can be a callable as well as a string, which is what I'm using here.

Disable submit button ONLY after submit

I faced the same problem. Customers could submit a form and then multiple e-mail addresses will receive a mail message. If the response of the page takes too long, sometimes the button was pushed twice or even more times..

I tried disable the button in the onsubmit handler, but the form wasn't submitted at all. Above solutions work probably fine, but for me it was a little bit too tricky, so I decided to try something else.

To the left side of the submit button, I placed a second button, which is not displayed and is disabled at start up:

<button disabled class="btn btn-primary" type=button id="btnverzenden2" style="display: none"><span class="glyphicon glyphicon-refresh"></span> Sending mail</button>   
<button class="btn btn-primary" type=submit name=verzenden id="btnverzenden">Send</button>

In the onsubmit handler attached to the form, the 'real' submit is hidden and the 'fake' submit is shown with a message that the messages are being sent.

function checkinput // submit handler
{
    ..
    ...
    $("#btnverzenden").hide(); <= real submit button will be hidden
    $("#btnverzenden2").show(); <= fake submit button gets visible
    ...
    ..
}

This worked for us. I hope it will help you.

How do I undo 'git add' before commit?

You can undo git add before commit with

git reset <file>

which will remove it from the current index (the "about to be committed" list) without changing anything else.

You can use

git reset

without any file name to unstage all due changes. This can come in handy when there are too many files to be listed one by one in a reasonable amount of time.

In old versions of Git, the above commands are equivalent to git reset HEAD <file> and git reset HEAD respectively, and will fail if HEAD is undefined (because you haven't yet made any commits in your repository) or ambiguous (because you created a branch called HEAD, which is a stupid thing that you shouldn't do). This was changed in Git 1.8.2, though, so in modern versions of Git you can use the commands above even prior to making your first commit:

"git reset" (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).

Documentation: git reset

HTML5 Number Input - Always show 2 decimal places

My preferred approach, which uses data attributes to hold the state of the number:

<input type='number' step='0.01'/>

// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)

// react to keys
el.addEventListener('onkeyup', ev => {

    // user cleared field
    if (!ev.target.value) ev.target.dataset.val = ''

    // non num input
    if (isNaN(ev.key)) {

        // deleting
        if (ev.keyCode == 8)

            ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)

    // num input
    } else ev.target.dataset.val += ev.key

    ev.target.value = parseFloat(ev.target.dataset.val) / 100

})

Sublime Text 2 - View whitespace characters

I use Unicode Character Highlighter, can show whitespaces and some other special characters.

Add this by, Package Control

Install packages, unicode ...

How to access the first property of a Javascript object?

A one-rule version:

var val = example[function() { for (var k in example) return k }()];

What is JavaScript garbage collection?

Eric Lippert wrote a detailed blog post about this subject a while back (additionally comparing it to VBScript). More accurately, he wrote about JScript, which is Microsoft's own implementation of ECMAScript, although very similar to JavaScript. I would imagine that you can assume the vast majority of behaviour would be the same for the JavaScript engine of Internet Explorer. Of course, the implementation will vary from browser to browser, though I suspect you could take a number of the common principles and apply them to other browsers.

Quoted from that page:

JScript uses a nongenerational mark-and-sweep garbage collector. It works like this:

  • Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.

  • Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)

  • Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the bits on the nonscavenger, and on everything that it refers to. (I am using the word "closure" in a different sense than in my earlier post.)

  • At this point we know that all the memory still marked is allocated memory which cannot be reached by any path from any in-scope variable. All of those objects are instructed to tear themselves down, which destroys any circular references.

The main purpose of garbage collection is to allow the programmer not to worry about memory management of the objects they create and use, though of course there's no avoiding it sometimes - it is always beneficial to have at least a rough idea of how garbage collection works.

Historical note: an earlier revision of the answer had an incorrect reference to the delete operator. In JavaScript the delete operator removes a property from an object, and is wholly different to delete in C/C++.

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

Best way to parse command line arguments in C#?

There is a command line argument parser at http://www.codeplex.com/commonlibrarynet

It can parse arguments using
1. attributes
2. explicit calls
3. single line of multiple arguments OR string array

It can handle things like the following:

-config:Qa -startdate:${today} -region:'New York' Settings01

It's very easy to use.

jQuery checkbox event handling

Use the change event.

$('#myform :checkbox').change(function() {
    // this represents the checkbox that was checked
    // do something with it
});

jQuery - trapping tab select event

it seems the old's version's of jquery ui don't support select event anymore.

This code will work with new versions:

$('.selector').tabs({
                    activate: function(event ,ui){
                        //console.log(event);
                        console.log(ui.newTab.index());
                    }
});

Check if a div exists with jquery

As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

How to add a .dll reference to a project in Visual Studio

Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference dialog.
Be sure that the new reference has the Copy Local = True.
The Add Reference dialog could be opened right-clicking on the References item in your project in Solution Explorer

UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)

Read about NuGet here

How do I find out which computer is the domain controller in Windows programmatically?

With the most simple programming language: DOS batch

echo %LOGONSERVER%

Place API key in Headers or URL

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.

How do you performance test JavaScript code?

Quick answer

On jQuery (more specifically on Sizzle), we use this (checkout master and open speed/index.html on your browser), which in turn uses benchmark.js. This is used to performance test the library.

Long answer

If the reader doesn't know the difference between benchmark, workload and profilers, first read some performance testing foundations on the "readme 1st" section of spec.org. This is for system testing, but understanding this foundations will help JS perf testing as well. Some highlights:

What is a benchmark?

A benchmark is "a standard of measurement or evaluation" (Webster’s II Dictionary). A computer benchmark is typically a computer program that performs a strictly defined set of operations - a workload - and returns some form of result - a metric - describing how the tested computer performed. Computer benchmark metrics usually measure speed: how fast was the workload completed; or throughput: how many workload units per unit time were completed. Running the same computer benchmark on multiple computers allows a comparison to be made.

Should I benchmark my own application?

Ideally, the best comparison test for systems would be your own application with your own workload. Unfortunately, it is often impractical to get a wide base of reliable, repeatable and comparable measurements for different systems using your own application with your own workload. Problems might include generation of a good test case, confidentiality concerns, difficulty ensuring comparable conditions, time, money, or other constraints.

If not my own application, then what?

You may wish to consider using standardized benchmarks as a reference point. Ideally, a standardized benchmark will be portable, and may already have been run on the platforms that you are interested in. However, before you consider the results you need to be sure that you understand the correlation between your application/computing needs and what the benchmark is measuring. Are the benchmarks similar to the kinds of applications you run? Do the workloads have similar characteristics? Based on your answers to these questions, you can begin to see how the benchmark may approximate your reality.

Note: A standardized benchmark can serve as reference point. Nevertheless, when you are doing vendor or product selection, SPEC does not claim that any standardized benchmark can replace benchmarking your own actual application.

Performance testing JS

Ideally, the best perf test would be using your own application with your own workload switching what you need to test: different libraries, machines, etc.

If this is not feasible (and usually it is not). The first important step: define your workload. It should reflect your application's workload. In this talk, Vyacheslav Egorov talks about shitty workloads you should avoid.

Then, you could use tools like benchmark.js to assist you collect metrics, usually speed or throughput. On Sizzle, we're interested in comparing how fixes or changes affect the systemic performance of the library.

If something is performing really bad, your next step is to look for bottlenecks.

How do I find bottlenecks? Profilers

What is the best way to profile javascript execution?

How to hide collapsible Bootstrap 4 navbar on click

You can use a simply bind on click and close, like this: (click)="drawer.close()

<a class="nav-link" [routerLink]="navItem.link" routerLinkActive="selected" (click)="drawer.close()">

Java Array Sort descending?

Simple method to sort an int array descending:

private static int[] descendingArray(int[] array) {
    Arrays.sort(array);
    int[] descArray = new int[array.length];
    for(int i=0; i<array.length; i++) {
        descArray[i] = array[(array.length-1)-i];
    }
    return descArray;
}

Make Bootstrap 3 Tabs Responsive

The solution is just 3 lines:

@media only screen and (max-width: 479px) {
   .nav-tabs > li {
      width: 100%;
   }
}

..but you have to accept the idea of tabs that wrap to more lines in other dimensions.

Of course you can achieve a horizontal scrolling area with white-space: nowrap trick but the scrollbars look ugly on desktops so you have to write js code and the whole thing starts becoming no trivial at all!

Instantiating a generic class in Java

From https://stackoverflow.com/a/2434094/848072. You need a default constructor for T class.


import java.lang.reflect.ParameterizedType;

class Foo {

  public bar() {
    ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
    Class type = (Class) superClass.getActualTypeArguments()[0];
    try {
      T t = type.newInstance();
      //Do whatever with t
    } catch (Exception e) {
      // Oops, no default constructor
      throw new RuntimeException(e);
    } 
  }
}

C# DataTable.Select() - How do I format the filter criteria to include null?

try this:

var result = from r in myDataTable.AsEnumerable()  
            where r.Field<string>("Name") != "n/a" &&  
                  r.Field<string>("Name") != "" select r;  
DataTable dtResult = result.CopyToDataTable();  

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

How to subtract date/time in JavaScript?

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns:android This is start tag for define android namespace in Android. This is standerd convention define by android google developer. when you are using and layout default or custom, then must use this namespace.

Defines the Android namespace. This attribute should always be set to "http://schemas.android.com/apk/res/android".

From the <manifest> element documentation.

jQuery’s .bind() vs. .on()

As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.

jQuery API documentation for .bind()

Today's Date in Perl in MM/DD/YYYY format

You can do it fast, only using one POSIX function. If you have bunch of tasks with dates, see the module DateTime.

use POSIX qw(strftime);

my $date = strftime "%m/%d/%Y", localtime;
print $date;

Java regex capturing groups indexes

For The Rest Of Us

Here is a simple and clear example of how this works

Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)

String: "!* UserName10 John Smith 01123 *!"

group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):  
group(3): John Smith
group(4):  
group(5): 01123

As you can see, I have created FIVE groups which are each enclosed in parentheses.

I included the !* and *! on either side to make it clearer. Note that none of those characters are in the RegEx and therefore will not be produced in the results. Group(0) merely gives you the entire matched string (all of my search criteria in one single line). Group 1 stops right before the first space because the space character was not included in the search criteria. Groups 2 and 4 are simply the white space, which in this case is literally a space character, but could also be a tab or a line feed etc. Group 3 includes the space because I put it in the search criteria ... etc.

Hope this makes sense.

How to replace a string in an existing file in Perl?

$_='~s/blue/red/g';

Uh, what??

Just

s/blue/red/g;

or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

$_ =~ s/blue/red/g;

How to sort with lambda in Python

lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)

It will print as following:

[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]

Javascript reduce() on Object

If handled as an array is much easier

Return the total amount of fruits:

let fruits = [{ name: 'banana', id: 0, quantity: 9 }, { name: 'strawberry', id: 1, quantity: 1 }, { name: 'kiwi', id: 2, quantity: 2 }, { name: 'apple', id: 3, quantity: 4 }]

let total = fruits.reduce((sum, f) => sum + f.quantity, 0);

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

i am not sure but, I think you can use @ResponseEntity and @ResponseBody and send 2 different one is Success and second is error message like :

@RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
Book bookInfo2() {
    Book book = new Book();
    book.setBookName("Ramcharitmanas");
    book.setWriter("TulasiDas");
    return book;
}

@RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE )
public ResponseEntity<Book> bookInfo3() {
    Book book = new Book();
    book.setBookName("Ramayan");
    book.setWriter("Valmiki");
    return ResponseEntity.accepted().body(book);
}

For more detail refer to this: http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity

How to measure height, width and distance of object using camera?

For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.

This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.

So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.

If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.

I have found some links using Google, they may help.

  1. http://forestjohnson.blogspot.com/2010/01/how-to-measure-size-of-object-using.html
  2. http://gigaom.com/mobile/how_to_measure_/
  3. http://www.iphonelife.com/blog/5/cameasure-use-your-camera-measure-size-or-distance

They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.

One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.

See these links as well:

  1. http://iopscience.iop.org/1742-6596/48/1/074/pdf/1742-6596_48_1_074.pdf
  2. http://www.optical-metrology-centre.com/Downloads/Papers/Photogrammetric%20Record%201994%20Automated%203-D%20measurement.pdf

Copy files on Windows Command Line with Progress

robocopy:

Robocopy, or "Robust File Copy", is a command-line directory and/or file replication command. Robocopy functionally replaces Xcopy, with more options. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was first introduced as a standard feature in Windows Vista and Windows Server 2008. The command is robocopy...

How to convert string to char array in C++?

Simplest way I can think of doing it is:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

For safety, you might prefer:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

or could be in this fashion:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());

assign function return value to some variable using javascript

You could simply return a value from the function:

var response = 0;

function doSomething() {
    // some code
    return 10;
}
response = doSomething();

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

How do you remove an array element in a foreach loop?

Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:

$result=array_search($unwantedValue,$array,true);
if($result !== false) {
  unset($array[$result]);   
}

The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.

Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:

$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
  unset($array[$key]);
}

Check http://php.net/manual/en/function.array-search.php for more information.

Generate random integers between 0 and 9

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

HTTP Error 503, the service is unavailable

I ran into the same issue, but it was an issue with the actual site settings in IIS.

Select Advanced Settings... for your site/application and then look at the Enabled Protocols value. For whatever reson the value was blank for my site and caused the following error:

HTTP Error 503. The service is unavailable.

The fix was to add in http and select OK. The site was then functional again.

How do I upload a file to an SFTP server in C# (.NET)?

Maybe you can script/control winscp?

Update: winscp now has a .NET library available as a nuget package that supports SFTP, SCP, and FTPS

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

It turns out that I had attempted to restore from a backup incorrectly.

Initially I created a new database and then attempted to restore the backup here. What I should have done, and what worked in the end, was to bring up the restore dialog and type the name of the new database in the destination field.

So, in short, restoring from a backup did the trick.

Thanks for all the feedback and suggestions guys

How to access Spring MVC model object in javascript file?

in controller:

JSONObject jsonobject=new JSONObject();
jsonobject.put("error","Invalid username");
response.getWriter().write(jsonobject.toString());

in javascript:

f(data!=success){



 var errorMessage=jQuery.parseJson(data);
  alert(errorMessage.error);
}

c# why can't a nullable int be assigned null as a value

What Harry S says is exactly right, but

int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));

would also do the trick. (We Resharper users can always spot each other in crowds...)

Why does git revert complain about a missing -m option?

By default git revert refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD is in fact a merge commit.

If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.

Often this will be parent number one, for example if you were on master and did git merge unwanted and then decided to revert the merge of unwanted. The first parent would be your pre-merge master branch and the second parent would be the tip of unwanted.

In this case you could do:

git revert -m 1 HEAD

Removing duplicate rows in Notepad++

If you don't care about row order (which I don't think you do), then you can use a Linux/FreeBSD/Mac OS X/Cygwin box and do:

$ cat yourfile | sort | uniq > yourfile_nodups

Then open the file again in Notepad++.

Setting the number of map tasks and reduce tasks

As Praveen mentions above, when using the basic FileInputFormat classes is just the number of input splits that constitute the data. The number of reducers is controlled by mapred.reduce.tasks specified in the way you have it: -D mapred.reduce.tasks=10 would specify 10 reducers. Note that the space after -D is required; if you omit the space, the configuration property is passed along to the relevant JVM, not to Hadoop.

Are you specifying 0 because there is no reduce work to do? In that case, if you're having trouble with the run-time parameter, you can also set the value directly in code. Given a JobConf instance job, call

job.setNumReduceTasks(0);

inside, say, your implementation of Tool.run. That should produce output directly from the mappers. If your job actually produces no output whatsoever (because you're using the framework just for side-effects like network calls or image processing, or if the results are entirely accounted for in Counter values), you can disable output by also calling

job.setOutputFormat(NullOutputFormat.class);

How to run vi on docker container?

Add the following line in your Dockerfile then rebuild the docker image.

RUN apt-get update && apt-get install -y vim

how to do "press enter to exit" in batch

My guess is that rake is a batch program. When you invoke it without call, then control doesn't return to your build.bat. Try:

@echo off
cls
CALL rake
pause

Examples of good gotos in C or C++

My gripe about this is that you lose block scoping; any local variables declared between the gotos remains in force if the loop is ever broken out of. (Maybe you're assuming the loop runs forever; I don't think that's what the original question writer was asking, though.)

The problem of scoping is more of an issue with C++, as some objects may be depending on their dtor being called at appropriate times.

For me, the best reason to use goto is during a multi-step initialization process where the it's vital that all inits are backed out of if one fails, a la:

if(!foo_init())
  goto bye;

if(!bar_init())
  goto foo_bye;

if(!xyzzy_init())
  goto bar_bye;

return TRUE;

bar_bye:
 bar_terminate();

foo_bye:
  foo_terminate();

bye:
  return FALSE;

How to get previous month and year relative to today, using strtotime and date?

Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime. Something like:

$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02

Reset all changes after last commit in git

How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?

  1. You can undo changes to tracked files with:

    git reset HEAD --hard
    
  2. You can remove untracked files with:

    git clean -f
    
  3. You can remove untracked files and directories with:

    git clean -fd
    

    but you can't undo change to untracked files.

  4. You can remove ignored and untracked files and directories

    git clean -fdx
    

    but you can't undo change to ignored files.

You can also set clean.requireForce to false:

git config --global --add clean.requireForce false

to avoid using -f (--force) when you use git clean.

Selecting the first "n" items with jQuery

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

What's the fastest way to loop through an array in JavaScript?

It's just 2018 so an update could be nice...

And I really have to disagree with the accepted answer. It defers on different browsers. some do forEach faster, some for-loop, and some while here is a benchmark on all method http://jsben.ch/mW36e

arr.forEach( a => {
  // ...
}

and since you can see alot of for-loop like for(a = 0; ... ) then worth to mention that without 'var' variables will be define globally and this can dramatically affects on speed so it'll get slow.

Duff's device run faster on opera but not in firefox

_x000D_
_x000D_
var arr = arr = new Array(11111111).fill(255);_x000D_
var benches =     _x000D_
[ [ "empty", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++);_x000D_
}]_x000D_
, ["for-loop", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; ++a)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop++", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop - arr.length", () => {_x000D_
  for(var a = 0; a < arr.length; ++a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["reverse for-loop", () => {_x000D_
  for(var a = arr.length - 1; a >= 0; --a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
,["while-loop", () => {_x000D_
  var a = 0, l = arr.length;_x000D_
  while( a < l ) {_x000D_
    var b = arr[a] + 1;_x000D_
    ++a;_x000D_
  }_x000D_
}]_x000D_
, ["reverse-do-while-loop", () => {_x000D_
  var a = arr.length - 1; // CAREFUL_x000D_
  do {_x000D_
    var b = arr[a] + 1;_x000D_
  } while(a--);   _x000D_
}]_x000D_
, ["forEach", () => {_x000D_
  arr.forEach( a => {_x000D_
    var b = a + 1;_x000D_
  });_x000D_
}]_x000D_
, ["for const..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( const a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for let..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( let a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for var..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( var a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["Duff's device", () => {_x000D_
  var len = arr.length;_x000D_
  var i, n = len % 8 - 1;_x000D_
_x000D_
  if (n > 0) {_x000D_
    do {_x000D_
      var b = arr[len-n] + 1;_x000D_
    } while (--n); // n must be greater than 0 here_x000D_
  }_x000D_
  n = (len * 0.125) ^ 0;_x000D_
  if (n > 0) { _x000D_
    do {_x000D_
      i = --n <<3;_x000D_
      var b = arr[i] + 1;_x000D_
      var c = arr[i+1] + 1;_x000D_
      var d = arr[i+2] + 1;_x000D_
      var e = arr[i+3] + 1;_x000D_
      var f = arr[i+4] + 1;_x000D_
      var g = arr[i+5] + 1;_x000D_
      var h = arr[i+6] + 1;_x000D_
      var k = arr[i+7] + 1;_x000D_
    }_x000D_
    while (n); // n must be greater than 0 here also_x000D_
  }_x000D_
}]];_x000D_
function bench(title, f) {_x000D_
  var t0 = performance.now();_x000D_
  var res = f();_x000D_
  return performance.now() - t0; // console.log(`${title} took ${t1-t0} msec`);_x000D_
}_x000D_
var globalVarTime = bench( "for-loop without 'var'", () => {_x000D_
  // Here if you forget to put 'var' so variables'll be global_x000D_
  for(a = 0, l = arr.length; a < l; ++a)_x000D_
     var b = arr[a] + 1;_x000D_
});_x000D_
var times = benches.map( function(a) {_x000D_
                      arr = new Array(11111111).fill(255);_x000D_
                      return [a[0], bench(...a)]_x000D_
                     }).sort( (a,b) => a[1]-b[1] );_x000D_
var max = times[times.length-1][1];_x000D_
times = times.map( a => {a[2] = (a[1]/max)*100; return a; } );_x000D_
var template = (title, time, n) =>_x000D_
  `<div>` +_x000D_
    `<span>${title} &nbsp;</span>` +_x000D_
    `<span style="width:${3+n/2}%">&nbsp;${Number(time.toFixed(3))}msec</span>` +_x000D_
  `</div>`;_x000D_
_x000D_
var strRes = times.map( t => template(...t) ).join("\n") + _x000D_
            `<br><br>for-loop without 'var' ${globalVarTime} msec.`;_x000D_
var $container = document.getElementById("container");_x000D_
$container.innerHTML = strRes;
_x000D_
body { color:#fff; background:#333; font-family:helvetica; }_x000D_
body > div > div {  clear:both   }_x000D_
body > div > div > span {_x000D_
  float:left;_x000D_
  width:43%;_x000D_
  margin:3px 0;_x000D_
  text-align:right;_x000D_
}_x000D_
body > div > div > span:nth-child(2) {_x000D_
  text-align:left;_x000D_
  background:darkorange;_x000D_
  animation:showup .37s .111s;_x000D_
  -webkit-animation:showup .37s .111s;_x000D_
}_x000D_
@keyframes showup { from { width:0; } }_x000D_
@-webkit-keyframes showup { from { width:0; } }
_x000D_
<div id="container"> </div>
_x000D_
_x000D_
_x000D_

Pie chart with jQuery

Tons of great suggestions here, just going to throw ZingChart onto the stack for good measure. We recently released a jQuery wrapper for the library that makes it even easier to build and customize charts. The CDN links are in the demo below.

I'm on the ZingChart team and we're here to answer any questions any of you might have!

_x000D_
_x000D_
$('#pie-chart').zingchart({_x000D_
  "data": {_x000D_
    "type": "pie",_x000D_
    "legend": {},_x000D_
    "series": [{_x000D_
      "values": [5]_x000D_
    }, {_x000D_
      "values": [10]_x000D_
    }, {_x000D_
      "values": [15]_x000D_
    }]_x000D_
  }_x000D_
});
_x000D_
<script src="http://cdn.zingchart.com/zingchart.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://cdn.zingchart.com/zingchart.jquery.min.js"></script>_x000D_
_x000D_
<div id="pie-chart"></div>
_x000D_
_x000D_
_x000D_

How can I get the SQL of a PreparedStatement?

I'm using Java 8, JDBC driver with MySQL connector v. 5.1.31.

I may get real SQL string using this method:

// 1. make connection somehow, it's conn variable
// 2. make prepered statement template
PreparedStatement stmt = conn.prepareStatement(
    "INSERT INTO oc_manufacturer" +
    " SET" +
    " manufacturer_id = ?," +
    " name = ?," +
    " sort_order=0;"
);
// 3. fill template
stmt.setInt(1, 23);
stmt.setString(2, 'Google');
// 4. print sql string
System.out.println(((JDBC4PreparedStatement)stmt).asSql());

So it returns smth like this:

INSERT INTO oc_manufacturer SET manufacturer_id = 23, name = 'Google', sort_order=0;

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

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

How to configure log4j.properties for SpringJUnit4ClassRunner?

I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.

Can an abstract class have a constructor?

Yes, an Abstract Class can have a Constructor. You Can Overload as many Constructor as you want in an Abstract Class. These Contractors Can be used to Initialized the initial state of the Objects Extending the Abstract Class. As we know we can't make an object of an Abstract Class because Objects are Created by the "new" keywords and not by the constructors...they are there for only initializing the state of the subclass Objects.

Installing NumPy via Anaconda in Windows

The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy

React-router v4 this.props.history.push(...) not working

You can try to load the child component with history. to do so, pass 'history' through props. Something like that:

  return (
  <div>
    <Login history={this.props.history} />
    <br/>
    <Register/>
  </div>
)

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

//Call .noConflict() to restore JQuery reference.

jQuery.noConflict(); OR  $.noConflict();

//Do something with jQuery.

jQuery( "div.class" ).hide(); OR $( "div.class" ).show();

Android global variable

import android.app.Application;

public class Globals extends Application
{
    private static Globals instance = null;
    private static int RecentCompaignID;
    private static int EmailClick;
    private static String LoginPassword;
    static String loginMemberID;
    private static String CompaignName = "";
    private static int listget=0;
    //MailingDetails
    private static String FromEmailadd="";
    private static String FromName="";
    private static String ReplyEmailAdd="";
    private static String CompaignSubject="";
    private static int TempId=0;
    private static int ListIds=0;

    private static String HTMLContent="";
    @Override
    public void onCreate() 
    {
        super.onCreate();
        instance = this;
    }

    public static Globals getInstance()
    {
        return instance;
    }

    public void setRecentCompaignID(int objRecentCompaignID)
    {
        RecentCompaignID = objRecentCompaignID;
    }

    public int getRecentCompaignID() 
    {
        return RecentCompaignID;
    }

    public void setLoginMemberID(String objloginMemberID) 
    {
        loginMemberID = objloginMemberID;
    }

    public String getLoginMemberID() 
    {
        return loginMemberID;
    }

    public void setLoginMemberPassword(String objLoginPassword)
    {
        LoginPassword = objLoginPassword;
    }

    public String getLoginMemberPassword()
    {
        return LoginPassword;
    }

    public void setEmailclick(int id)
    {
        EmailClick = id;
    }

    public int getEmailClick() 
    {
        return EmailClick;
    }
    public void setCompaignName(String objCompaignName)
    {
        CompaignName=objCompaignName;
    }
    public String getCompaignName()
    {
        return CompaignName;
    }
    public void setlistgetvalue(int objlistget)
    {
        listget=objlistget;
    }
    public int getlistvalue()
    {
        return listget;
    }
    public void setCompaignSubject(String objCompaignSubject)
    {
         CompaignSubject=objCompaignSubject;
    }
    public String getCompaignSubject()
    {
        return CompaignSubject;
    }
    public void setHTMLContent(String objHTMLContent)
    {
        HTMLContent=objHTMLContent;
    }
    public String getHTMLContent()
    {
        return HTMLContent;
    }
    public void setListIds(int objListIds)
    {
        ListIds=objListIds;
    }
    public int getListIds()
    {
        return ListIds;
    }
    public void setReplyEmailAdd(String objReplyEmailAdd)
    {
        ReplyEmailAdd=objReplyEmailAdd;
    }
    public String getReplyEmailAdd()
    {
        return ReplyEmailAdd;
    }
    public void setFromName(String objFromName)
    {
        FromName=objFromName;
    }
    public String getFromName()
    {
        return FromName;
    }
    public void setFromEmailadd(String objFromEmailadd)
    {
        FromEmailadd=objFromEmailadd;
    }
    public String getFromEmailadd()
    {
        return FromEmailadd;
    }
}

Filter dataframe rows if value in column is in a set list of values

isin() is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the str.contains method and regular expressions.

For example, if we want to return a DataFrame where all of the stock IDs which begin with '600' and then are followed by any three digits:

>>> rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')] # ^ means start of string
...   STK_ID   ...                                    # [0-9]{3} means any three digits
...  '600809'  ...                                    # $ means end of string
...  '600141'  ...
...  '600329'  ...
...      ...   ...

Suppose now we have a list of strings which we want the values in 'STK_ID' to end with, e.g.

endstrings = ['01$', '02$', '05$']

We can join these strings with the regex 'or' character | and pass the string to str.contains to filter the DataFrame:

>>> rpt[rpt['STK_ID'].str.contains('|'.join(endstrings)]
...   STK_ID   ...
...  '155905'  ...
...  '633101'  ...
...  '210302'  ...
...      ...   ...

Finally, contains can ignore case (by setting case=False), allowing you to be more general when specifying the strings you want to match.

For example,

str.contains('pandas', case=False)

would match PANDAS, PanDAs, paNdAs123, and so on.

Find something in column A then show the value of B for that row in Excel 2010

I note you suggested this formula

=IF(ISNUMBER(FIND("RuhrP";F9));LOOKUP(A9;Ruhrpumpen!A$5:A$100;Ruhrpumpen!I$5:I$100);"")

.....but LOOKUP isn't appropriate here because I assume you want an exact match (LOOKUP won't guarantee that and also data in lookup range has to be sorted), so VLOOKUP or INDEX/MATCH would be better....and you can also use IFERROR to avoid the IF function, i.e

=IFERROR(VLOOKUP(A9;Ruhrpumpen!A$5:Z$100;9;0);"")

Note: VLOOKUP always looks up the lookup value (A9) in the first column of the "table array" and returns a value from the nth column of the "table array" where n is defined by col_index_num, in this case 9

INDEX/MATCH is sometimes more flexible because you can explicitly define the lookup column and the return column (and return column can be to the left of the lookup column which can't be the case in VLOOKUP), so that would look like this:

=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH(A9;Ruhrpumpen!A$5:A$100;0));"")

INDEX/MATCH also allows you to more easily return multiple values from different columns, e.g. by using $ signs in front of A9 and the lookup range Ruhrpumpen!A$5:A$100, i.e.

=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH($A9;Ruhrpumpen!$A$5:$A$100;0));"")

this version can be dragged across to get successive values from column I, column J, column K etc.....

How to count number of records per day?

select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded

"Unable to acquire application service" error while launching Eclipse

I got this problem with Mac OS Lion, after transfer OS/Data from an older machine to a new one.

Solved deleting the old eclipse folder (which I have in Applications folder) and copy eclipse folder again (same version, same unpacked zip file, no changes).

Overlapping Views in Android

Also, take a look at FrameLayout, that's how the Camera's Gallery application implements the Zoom buttons overlay.

UIScrollView Scrollable Content Size Ambiguity

Vertical Scrolling

  1. Add a UIScrollView with constraints 0,0,0,0 to superview.
  2. Add a UIView in ScrollView, with constraints 0,0,0,0 to superview.
  3. Add same width constraint for UIView to UIScrollView.
  4. Add Height to UIView.
  5. Add elements with constraints to the UIView.
  6. For the element closest to the bottom, make sure it has a constraint to the bottom of UIView.

SQL Server: Cannot insert an explicit value into a timestamp column

Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.

This fails with the timestamp error:

Insert Into Table2
Select Table1.A, Table1.B, Table1.TimeStamp From Table1

This works:

Insert Into Table2
Select Table1.A, Table1.B, null From Table1

Setting the correct encoding when piping stdout in Python

Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself.

A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send.

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between.

import sys
for line in sys.stdin:
    # Decode what you receive:
    line = line.decode('iso8859-1')

    # Work with Unicode internally:
    line = line.upper()

    # Encode what you send:
    line = line.encode('utf-8')
    sys.stdout.write(line)

Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don't do it.

How to get the absolute path to the public_html folder?

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

How to get raw text from pdf file using java

Extracting all keywords from PDF(from a web page) file on your local machine or Base64 encoded string:

import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WebPagePdfExtractor {

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();

        System.out.println("From file:   " + webPagePdfExtractor.processRecord(createByteArray()).get("text"));

        System.out.println("From string: " + webPagePdfExtractor.processRecord(getArrayFromBase64EncodedString()).get("text"));
    }

    public Map<String, Object> processRecord(byte[] byteArray) {
        Map<String, Object> map = new HashMap<>();
        try {
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(false);
            stripper.setShouldSeparateByBeads(true);

            PDDocument document = PDDocument.load(byteArray);
            String text = stripper.getText(document);
            map.put("text", text.replaceAll("\n|\r|\t", " "));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    private static byte[] getArrayFromBase64EncodedString() {
        String encodedContent = "data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9GbGF0ZURlY29kZSA+PgpzdHJlYW0KeAGF0E0OgjAQBeA9p3hL3UCHlha2Gg9A0sS1AepPxIDl/rFFErVESDddvPlm8nqU6EFpzARjBCVkLHNkipBzPBsc8UCyt4TKgmCr/9HI+GDqg2x8Luzk8UtfYwX5DVWLnQaLmd+qHTsF3V5QEekWidZuDNpgc7L1FvqGg35fOzPlqslFYJrzZdnkq6YI77TXtrs3GBo7oKvNss9mfhT0IAV+e6CUL5pSTWb0t1tVBKbI5McsXxNmciYKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjE4NQplbmRvYmoKMiAwIG9iago8PCAvVHlwZSAvUGFnZSAvUGFyZW50IDMgMCBSIC9SZXNvdXJjZXMgNiAwIFIgL0NvbnRlbnRzIDQgMCBSIC9NZWRpYUJveCBbMCAwIDU5NSA4NDJdC" +
                "j4+CmVuZG9iago2IDAgb2JqCjw8IC9Qcm9jU2V0IFsgL1BERiAvVGV4dCBdIC9Db2xvclNwYWNlIDw8IC9DczEgNyAwIFIgL0NzMiA4IDAgUiA+PiAvRm9udCA8PAovVFQxIDkgMCBSID4+ID4+CmVuZG9iagoxMCAwIG9iago8PCAvTGVuZ3RoIDExIDAgUiAvTiAxIC9BbHRlcm5hdGUgL0RldmljZUdyYXkgL0ZpbHRlciAvRmxhdGVEZWNvZGUgPj4Kc3RyZWFtCngBhVVdaBxVFD67c2cDEgcftA0ttIM/bQnpMolWE4u12026SRO362ZTmyrKdHY2O81kZpyZ3SahT6XgmxYE6augPsaCCLYqNi/2paXFkko1DwoRWowgKH1S8Dsz22R2QTLDnfnuueeee8537rmXqOtv3fPstEo054R+oZybPjl9Su26TWlSqJvw6Ebg5UqlCcaO65j8b38e3qUUS+7sZ1vtY1v25KoZGNC6huZWA2OOKKURZWqG54dEXZcgHzwbeoxvAz85WynngdeAldZcQHqqYDqmbxlqwdcX1JLv1i" +
                "w76etW42xjy2fObrCv/OxG6w5mJ8fx74XPF0xnahJ4H/CSoY8w7gO+27ROFGOcTnvhkXKsn842ZqdyLfnJmn90qiW/UG+MMs4SpZcW65U3gJ8AXnVOF4+39Ndn3XG200Mk9RhB/hTws8Ba3RzjPKnAFd8tsz7Lw6o5PAL8MvAlKxyrAMO+9EPQnGQ5sKDFep79xFoie0Y/VgLeBnzItAu8FuyIiheW2OYg8LxjF3ktxC4um0EUL2IXP4X1ymisL6dDv8JznyaS99Sso2PA4EQerfujLIc/cujZ0d56EXjJb5Q59j3Aa7o/UgCGzcxjVX2YeX4BeIBOpHQyyaXT+Brk0L+INyCLmhHyyMdYDX2bCtBw0Hz0DGgVgHRaAColtEz0WCeeo1IVPZVmollBhNjK/ahvUH7Xp9SAtE7rkNaBXqNfIsk8/Upz6OchbWBspsNuHl44tAgP2BO2+aBl0xXbhSaeRzsoJsQrYlAMkSpeFYfFITEM6ZA4GM2JvU/6zn4+2LD0LtZN+r4MDkKsZ8MzB6xwNAE8+AfrzkaaCbYu7mjs87yP3j/vv2MZtz74s429APoxJ7/BogtrJiXmXj/3TU/CQ3VFfPXWne7r5+h4MktR3qqdWZLX5PvyCr735NWkDflneRXvvbZcPcoL/5O5zSFGO5LNQc48m1G0ccYbwCG4qUVz9rdZTLLptmK0YMlClJ2ruP/LCfPDPLexUnMu7vC8tz9jNs33ig+LdL5Pu6y" +
                "ta59oP2p/aCvax0C/Sx9KX0rfSlekq9INUqVr0rL0nfS99Ln0NXpfQLosXenYSXHsG7sHfsZ71mjtMGaGsxQQ88LazApLH/F3BmOb+TOh1V4Dnbt/Yy3liLJTeUYZVnYrzykTSq9yQDmsbFcG0PqVUWUvRnZusGRjPc6AhX+SZ4umI67iPLFXdbDnw0sd76ZfXMPWhjXYST0Ontnapg6vEVe/FVVjvDtdnAY6TSFii84ich86nB8nqv7O2VyTODVSb+KUsMQu0S/GWjWYEwdQheNt9TjIVZoZyQxncqRmejNDmf7MMcZRrNH5ktmL0SF8RxLeM8sx/5s1xGcY7x3mqAlso4dbKzTncd8R5V1vwbdm6qE6oGkvqTlcr6Y65hjZPlW3bTUaClTfDEy/aVazxHc3zyP66/XoTk5tu2E0/GYso1TqJtF/t4+TNAplbmRzdHJlYW0KZW5kb2JqCjExIDAgb2JqCjExMTYKZW5kb2JqCjcgMCBvYmoKWyAvSUNDQmFzZWQgMTAgMCBSIF0KZW5kb2JqCjEyIDAgb2JqCjw8IC9MZW5ndGgg" +
                "MTMgMCBSIC9OIDMgL0FsdGVybmF0ZSAvRGV2aWNlUkdCIC9GaWx0ZXIgL0ZsYXRlRGVjb2RlID4+CnN0cmVhbQp4AYVVW4gbVRj+kznJCrvO09rVLaRDvXQpu0u2Fd2ltJpbk7RrGrLZ1RZBs5OTZMzsJM5M0gt9KoLii6u+SUG8vS0IgtJ6wdYH+1KpUFZ36yIoPrR4QSj0RbfxO5NkJllqm2XPfPP93/lv558ZooG1Qr2u+xWiJcM2c8mo8tzRY8rAOvnpIRqkURosqFY9ks3OEn5CK679v1s/kE8wVyfubO9Xb7kbLHJLJfLdB75WtNQl4BNEgbNq3bSJBobBTx+36wKLHIZNJAj8osDlNoaNhhfb+DVHk8/FoDkLLKuVQhF4BXh8sYcv9+B2DlDAT5Ib3NRURfQia9ZKms4dQ3u5h7lHeTe4pDdQs/PbgXXIqs4dxnUMtb9SLMQFngReUQuJOeBHgK81tYVMB9+u29Ec8GNE/p2N6nwEeDdwqmQenAeGH79ZaaS6+J1Tlfyz4LeB/8ZYzBzp7F1TrRh6STvB367wtOhviEhSN" +
                "DudB4Yf6YBZywk9cpBKRR5PAI8Dv16tHRY5wKf0mdWcE7zIZ+1UJSbyFPzllwqHssCjwL9yPSn0iCX9W7eznRxYyNAzIi5isTi3nHrhh4XsSj4FHnGZbpv5zl62XNIOpjv6TypmSvBi77W67swocgv4zUZO1I5YgcmCmUgCw2cgy4150U+Bm7TgKxCnGi1iVcmgTVIoR0mK4lonE5YSaaSD4bByMBx3Xc2Es8+iKniNmo7Nwpp1lO2dXa1CZbAGXXe0KsVCH1EDnir0B9iK61OhGO4a4Mr/46edy42OnxobYWG2F//72Czbz6bZDCnsKfY0O8DiYGfYPtd3Fnu6FYl8biBK28/LiMgd3QJqv4gabSpg/QWKGlmuh76uLI82xjzLGfMFTb3yxt89vdKws+oqJvo6euRePQ/8FrgeWMW6HthwfSiBnwIb+FtHb7xaap6902VxUhpOtNan23oWXVUElerOziV0QUPNvKfmiV4fl05/+aAXbZWde/7q0KXTJWN51GNFF/irmVsZOjPuseEfw3+GV8PvhT8M/y69LX0qfSWdlz6XLpMiXZ" +
                "AuSl9L30ofS1+4+rvNkHv2JDIXcyXyFtPVrbC315hYOSpvlx+W4/IO+VF51lUp8og8JafkXbBsd8/Nm2+lt3L05Siidftz51jiWdFcTzgD3/2YAM2L2DcD88hYo+PwaaLfYt4MOglt75PXqYiF2BRLb5nuaTHzXd/BRDAejJAS3B2cCU4FDwncfZaDu2CbwZrozQ3z4Sr6KuU2PyG+JxSr1U+aWrliK3vC4SeVCD59XEkb6uS4UtB1xTFZisktbjZ5cZLEd1PsI7qZc76Hvm1XPM5+hmj/X3j3fe9xxxpEKxbRyOMeN4Z35QPvEp17Qm2YzbY/8vm+I7JKe/c4976hKN5fP7daN/EeG3iLaPPNVuuf91utzQ/gf4Pogv4foJ98VQplbmRzdHJlYW0KZW5kb2JqCjEzIDAgb2JqCjEwNzkKZW5kb2JqCjggMCBvYmoKWyAvSUNDQmFzZWQgMTIgMCBSIF0KZW5kb2JqCjMgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9NZWRpYUJveCBbMCAwIDU5NSA4NDJdIC9Db3VudCAxIC9LaWR" +
                "zIFsgMiAwIFIgXSA+PgplbmRvYmoKMTQgMCBvYmoKPDwgL1R5cGUgL0NhdGFsb2cgL1BhZ2VzIDMgMCBSID4+CmVuZG9iago5IDAgb2JqCjw8IC9UeXBlIC9Gb250IC9TdWJ0eXBlIC9UcnVlVHlwZSAvQmFzZUZvbnQgL0NOVFpYVStNZW5" +
                "sby1SZWd1bGFyIC9Gb250RGVzY3JpcHRvcgoxNSAwIFIgL0VuY29kaW5nIC9NYWNSb21hbkVuY29kaW5nIC9GaXJzdENoYXIgMzIgL0xhc3RDaGFyIDExNiAvV2lkdGhzIFsgNjAyCjAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgNjAyIDYwMiA2MDIgNjAyIDYwMiA2MDIgMCAwIDAgMCAwIDAgMCAwIDAKMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgNjAyIDAgMAo2MDIgNjAyIDYwMiA2MDIgNjAyIDYwMiAwIDAgNjAyIDYwMiAwIDAgNjAyIDAgMCA2MDIgNjAyIF0gPj4KZW5kb2JqCjE1IDAgb2JqCjw8IC9UeXBlIC9Gb250RGVzY3JpcHRvciAvRm9udE5hbWUgL0NOVFpYVStNZW5sby1SZWd1bGFyIC9GbGFncyAzMyAvRm9udEJCb3gKWy01NTggLTM3NSA3MTggMTA0MV0g" +
                "L0l0YWxpY0FuZ2xlIDAgL0FzY2VudCA5MjggL0Rlc2NlbnQgLTIzNiAvQ2FwSGVpZ2h0IDcyOQovU3RlbVYgOTkgL1hIZWlnaHQgNTQ3…/ZfICj5JcLdi/ATmQZKogDPg0lIDBunI0ZGOB1OB/Lpyce1TbJqCpBThycVs3GyQPZSLKexbMGyFss8LF4sNb2lElu5HPlJ2439G1jKsbRh6cTyPNpx8I6AFxa8P+xD2E4e/G+5PqJ/8aDzERFvGBJR/WLkfwcM3kRCiZpokDMdxhn5MeD9Rn5MSm0mYUpLSF98J5HXaQgtpJvoDWGesEe4C4NgK3woWsQ88RgzszXsMM4WyALeIC5gO5B/FYk/pNxVCJGoZT8NYc8LIknrONeVQYznus51pYeZHCaXw+RYIJLAEogJfMEbVPrvv31S6icvTMlp1EQhO41cOuXb0EEkSYkmGaMXSzuIfhCKAA4Y/YScTs9ASizblWVyWB1UT4fwNfSp9+mgwLFd4oI3D++9++kuheYWpOnEeBhLJrv7kVg" +
                "Xk1hkVDRExLgkieUZTTt1jZYGkTTiXU8tULUtIsEIfeKMgY5AV3u7yZyTQdK6Mm923fwgHe1GZWTfmCJy5CYi05PgwqWzB5HBw2n2wL7OBEmVPZxmZYpWi6TSU7pM2BNY1kojs0sLN1bPOLZ4/nuzL1CNp/S+zt27dx+lA4Y/2/hA1fq8kR9kZF57u6R96YgvZRmsvfe5OBj5TSKjkN+wRqu6LrRF1yjF19lbYhudDVKTdVe/8DAClihbX6MNEuItofH9kF9k+FwXMofC7rqCDHcZu293G7tz0qmNWi2iM6FvYrYN2RuEvCbT7GDnZ0xDyMZt/Otb8z+aP+/dOS17927ZurVu24ZVnrYFz7w95jxlayE+8b3Nf/m6b5/j2QMb1v26qeXZ8iWVSUkH7fYLb1bKBw7aA57LYgVGYAGtLM8dT3WgIwC6PAIaVSOjsCaUatXEFiJKBm0fvTEQODe0K9Mki/mK3DPnBOUsHkchH/ckhFIHZJmyrE6T0+TIFi7xfvRjx/X33jves5rFBb6Gk4GsHXwbLX1Hlp0XZZeKa8eRYe4EURUX3agy" +
                "1RnXWxp1QiNZo2tS7baBjUTYqDqBGONtspI7UEwosSsoMUVevAM5CEO9mmRVEquF/ExwsrxOCTd7OpKnpXxFjfzzO8uPTnz44Oydb7bunLy1kHXu5huMBt59vYvfsNtPZmb4tjfvdblQGjXI23jUayTpg9w5VfFRjer4RqP6DRGPs/ViY3iDscmVYCN9dQkqKZaGxbuMga6uwBXZeYLq/MKI6jShPq0DqDNBUBg0Wy2C0y6YjMSRGU4TJKslPKhYuJS7fkL7u+m7F33yzc3PeOBb6qSWsZv4Zys3bVq5as0atu+gK5Ff4ldLH+d3vvuW36bL6Ab6LF0X37Pw4I4dB//4+z0+RZ8y306xEuNGP7LI3V+tItF2baRBRfZHqurNjjr7O3H1fdrMTZE6GilG6dWSNt8uStbh/Y03u9AkM1G3snI7rtwMyCKWd2DKMeegZ6W749Lj0+3pjvSEZtJMm4VmdbNme3hzRHNkc1RztH4m7rJ3Q4OzB5uc2XpE9M0eOOh+mi1LoNfdwlGfQtuwV159duGWPfTAgfv/VP3GBz98d4eu2jirfca81uK6o8P62oWsJxaXLT57sN/4npUtpY/8eXvr4bhVzwwa6E9MnDIlc2PQditxr2bMIowYLdLd0YxYouv1lvqQJn0bfREiRCIJo0xmzeg43Ju8NTk2KIaDe0ynpqxeHlEd5ixUx790gazCdL9/QFPpiWvX3y/byg1ramr" +
                "q6mpq1sAZYeQ/utYVTaP3Uys10cHTuOaj8xfPdV44L/uSzE8Jyt6K/GQFIyKGKSUIChgEY09jScPcUUJf02C4DCNRShuL32qS0zOo1WGVZIMYbEXZ2QmaSVamWRUUnlgS+DzknT3F7eWPHpnBf+Dnqf3GR3d82g1ran4XItRPl744dl/OW8nJNIeGUS118782Lt3lWyT72RH08USUUxgZiFIyUm3IfonWkxf10mG1EKYioUzSGTQW47mhHYGhHZmKAVzJDKD60b9lA0aJxFHZyWSndqBKs8TEM3Mn0JV8hZ930uRdf5IsTZPnz/UG0uCMd6JfTq9lefDRornXFke7E6O0tpjEUDDXhYWH1tvC6w2AlmgzHEk63D8xikjaUZLZ7BiNhtjRqy10846gERo7u9EC0RKRGyV0Bx0nDL3pxzg5TJANrleZEdlZMH31ytXrvWtWrPZ3Xx3fUjSneeTmNSlbyjuuX+9Y2JDmF3JOffzxqVOfnuefBXggNmb/gJTtvpCqWQ/TIVSFZ+mQh6ZvkPcRlF+MIr8Ud2SoHvC3OKne1KZ9UU0FiYzVhUqaQgvaGIoMTWwoxnKM67KFOU1BZrGTpfh/uBhz4LEnVtb5/RmvL3ljl7C/Z6ywv3H9W2/0rJYsPTtK5l6W5daN+qqWDHh+6oicYqKpyD9kyocpRTtSXcR8Em1J7muwlW1LexrtSs5JZLuScwa5pXgGyx/hdZxIeA" +
                "JTPMvxBMSaYoSmQ+nHtDywiJbzyzTe7xcfDmR5vTBcyPsKv7yBPEyXopGDxCAHOoUoppRILPQiribnP/IqOjlLka3XEo5eIbu8bCTCqRmej6+99ib/lF6im3/13ItnD8OtF4LyxN+YxQq0iwTyqjsx0mwIFVUkLkZSWbX1dmiLORxlVBGTIWSC" +
                "NNE0wTAxNnJCdIHTeHOcTzt1nM80dUbxARJ9r/0+T2BoAA0leOYPHXrlpnIwoYmg8NPdo9LFdJYupavSQ9JD09Xpmtzw3IjcyNyo3OjcmNzY3LhcWzVUi9WsWqpWVYdUh1arqzXecG+EN9Ib5Y32xnhjvXFem5POpPLJEh5Ff6LMf2vVqgwKOx" +
                "IeHbu64vXswkn3v54zdkzOzp2Oubnjy6B7dMEZfqlnubDymyWVX/SsEFbeWCy3YknJ0NxCWddt/CFxKspCjmFZ7tgfY1ibvokegcNxGL9GKZGsUI5imYqJoV/8GMZcsm0pXJhNRtkbfuofdPmBA3IYu/rV+/Oa6I3VNatqa1fVrF7Xc1xSe4um" +
                "8Xf5df53fnwavfXR+Qud5y5iFJPtvRPjmIQ8JZJlbrdOK+g1EfG2kFBBpY6wxdvy4myRao0tXrSSOtouWuqs7ZH1JrHe1WZqSopTa+JjVOSBGEk/RiVZEgqSgu58RXZfObDIh6OR3+o23uo2RyjHipKn6ZU8Tak9CcETUz5L4pVkSPq3k2cPTBMGYPo2CFUCJx9oLqqqfPitsWvXdX1YtP+x+YemPrvqVkjBy789//70FjFn34ABk4vGjXXqo7dVtbQ6nW3Z2XM91RmCPn7jilf+4FD2incAMYS9hLExwx2pZyEG2E9M9HDIfnWIJhTzYclo1v88MnbdHNohp0Cyg8sx8Wdmb8Lr7nY+a9ayU5dP7ZZDI3uJH/b2NP9qzsaWE0KJlw5HnSvPvefwlwRZ2r988CqMnmzBUyScRGD+EUXyySgymowhY8k4Mp48gLl+EXmITFM+pPjvhSANSb5Ej5w4dXrxg8kTyhYtrEidUjZ/2cLZTxLyT2S78dEKZW5kc3RyZWFtCmVuZG9iagoxNyAwIG9iago0ODAxCmVuZG9iagoxOCAwIG9iagooKQplbmRvYmoKMTkgMCBvYmoKKE1hYyBPUyBYIDEwLjEyLjYgUXVhcnR6IFBERkNvbnRleHQpCmVuZG9iagoyMCAwIG9iagooKQplbmRvYmoKMjEgMCBvYmoKKCkKZW5kb2JqCjIyIDAgb2JqCihUZXh0TWF0ZSkKZW5kb2JqCjIzIDAgb2JqCihEOjIwMTcxMjEyMTMwMzQ4WjAwJzAwJykKZW5kb2JqCjI0IDAgb2JqCigpCmVuZG9iagoyNSAwIG9iagpbICgpIF0KZW5kb2JqCjEgMCBvYmoKPDwgL1RpdGxlIDE4IDAgUiAvQXV0aG9yIDIwIDAgUiAvU3ViamVjdCAyMSAwIFIgL1Byb2R1Y2VyIDE5IDAgUiAvQ3JlYXRvcgoyMiAwIFIgL0NyZWF0aW9uRGF0ZSAyMyAwIFIgL01vZERhdGUgMjMgMCBSIC9LZXl3b3JkcyAyNCAwIFIgL0FBUEw6S2V5d29yZHMKMjUgMCBSID4+CmVuZG9iagp4cmVmCjAgMjYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDA4OTI5IDAwMDAwIG4gCjAwMDAwMDAzMDAgMDAwMDAgbiAKMDAwMDAwMzAyOCAwMDAwMCBuIAowMDAwMDAwMDIyIDAwMDAwIG4gCjAwMDAwMDAyODEgMDAwMDAgbiAKMDAwMDAwMDQwNCAwMDAwMCBuIAowMDAwMDAxNzUzIDAwMDAwIG4gCjAwMDAwMDI5OTIgMDAwMDAgbiAKMDAwMDAwMzE2MSAwMDAwMCBuIAowMDAwMDAwNTEyIDAwMDAwIG4gCjAwMDAwMDE3MzIgMDAwMDAgbiAKMDAwMDAwMTc4OSAwMDAwMCBuIAowMDAwMDAyOTcxIDAwMDAwIG4gCjAwMDAwMDMxMTEgMDAwMDAgbiAKMDAwMDAwMzU0NCAwMDAwMCB" +
                "uIAowMDAwMDAzNzk2IDAwMDAwIG4gCjAwMDAwMDg2ODcgMDAwMDAgbiAKMDAwMDAwODcwOCAwMDAwMCBuIAowMDAwMDA4NzI3IDAwMDAwIG4gCjAwMDAwMDg3ODAgMDAwMDAgbiAKMDAwMDAwODc5OSAwMDAwMCBuIAowMDAwMDA4ODE4IDAwMDAwIG4gCjAwMDAwMDg4NDUgMDAwMDAgbiAKMDAwMDAwODg4NyAwMDAwMCBuIAowMDAwMDA4OTA2IDAwMDAwIG4gCnRyYWlsZXIKPDwgL1NpemUgMjYgL1Jvb3QgMTQgMCBSIC9JbmZvIDEgMCBSIC9JRCBbIDxkYjc4M2NhNDM2Mzg4YzI5ZDc5MDQ2NzY3NjUxNjE3OT4KPGRiNzgzY2E0MzYzODhjMjlkNzkwNDY3Njc2NTE2MTc5PiBdID4+CnN0YXJ0eHJlZgo5MTA0CiUlRU9GCg==";
        String content = encodedContent.substring("data:application/pdf;base64," .length());
        return Base64.decodeBase64(content);
    }

    public static byte[] createByteArray() {
        String pathToBinaryData = "/bla-bla/src/main/resources/small.pdf";

        File file = new File(pathToBinaryData);
        if (!file.exists()) {
            System.out.println(" could not be found in folder " + pathToBinaryData);
            return null;
        }

        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        byte fileContent[] = new byte[(int) file.length()];

        try {
            fin.read(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileContent;
    }
}

Python list subtraction operation

I think the easiest way to achieve this is by using set().

>>> x = [1,2,3,4,5,6,7,8,9,0]  
>>> y = [1,3,5,7,9]  
>>> list(set(x)- set(y))
[0, 2, 4, 6, 8]

Bootstrap dropdown sub menu missing

I make another solution for dropdown. Hope this is helpfull Just add this js script

<script type="text/javascript"> jQuery("document").ready(function() {
  jQuery("ul.dropdown-menu > .dropdown.parent").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    if (jQuery(this).hasClass('open2'))
      jQuery(this).removeClass('open2');
    else {
      jQuery(this).addClass('open2');
    }

  });
}); < /script>

<style type="text/css">.open2{display:block; position:relative;}</style>

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

I face the same issue. I am using docker version:17.09.0-ce.

I follow below steps:

  1. Create Dockerfile and added commands for creating docker image
  2. Go to directory where we have created Dockfile
  3. execute below command $ sudo docker build -t ubuntu-test:latest .

It resolved issue and image created successsfully.

Note: build command depend on docker version as well as which build option we are using. :)

Changing datagridview cell color dynamically

This works for me

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

Removing viewcontrollers from navigation stack

Swift 5, Xcode 11.3

I found this approach simple by specifying which view controller(s) you want to remove from the navigation stack.

extension UINavigationController {

    func removeViewController(_ controller: UIViewController.Type) {
        if let viewController = viewControllers.first(where: { $0.isKind(of: controller.self) }) {
            viewController.removeFromParent()
        }
    }
}

Example use:

navigationController.removeViewController(YourViewController.self)

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

Inserting the iframe into react component

If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution

var Iframe = React.createClass({     
  render: function() {
    return(         
      <div>          
        <iframe src={this.props.src} height={this.props.height} width={this.props.width}/>         
      </div>
    )
  }
});

ReactDOM.render(
  <Iframe src="http://plnkr.co/" height="500" width="500"/>,
  document.getElementById('example')
);

here live demo is available Demo

Sleep function in ORACLE

If executed within "sqlplus", you can execute a host operating system command "sleep" :

!sleep 1

or

host sleep 1

HashSet vs. List performance

It depends. If the exact answer really matters, do some profiling and find out. If you're sure you'll never have more than a certain number of elements in the set, go with a List. If the number is unbounded, use a HashSet.

How to prove that a problem is NP complete?

In order to prove that a problem L is NP-complete, we need to do the following steps:

  1. Prove your problem L belongs to NP (that is that given a solution you can verify it in polynomial time)
  2. Select a known NP-complete problem L'
  3. Describe an algorithm f that transforms L' into L
  4. Prove that your algorithm is correct (formally: x ? L' if and only if f(x) ? L )
  5. Prove that algo f runs in polynomial time

Exit a Script On Error

Here is the way to do it:

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE *** 
************
'

Java: Enum parameter in method

You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.

Convert string with comma to integer

I would do using String#tr :

"1,112".tr(',','').to_i # => 1112

How can I display a tooltip on an HTML "option" tag?

It seems in the 2 years since this was asked, the other browsers have caught up (at least on Windows... not sure about others). You can set a "title" attribute on the option tag:

<option value="" title="Tooltip">Some option</option>

This worked in Chrome 20, IE 9 (and its 8 & 7 modes), Firefox 3.6, RockMelt 16 (Chromium based) all on Windows 7

Show only two digit after decimal

I think the best and simplest solution is (KISS):

double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;

How to get the bluetooth devices as a list?

You should change your code as below:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

List<String> s = new ArrayList<String>();
for(BluetoothDevice bt : pairedDevices)
   s.add(bt.getName());

setListAdapter(new ArrayAdapter<String>(this, R.layout.list, s));

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.

Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.

However the overhead of creating the large dataset may offset the benefits of parallel processing...

PHP: Inserting Values from the Form into MySQL

There are two problems in your code.

  1. No action found in form.
  2. You have not executed the query mysqli_query()

dbConfig.php

<?php

$conn=mysqli_connect("localhost","root","password","testDB");

if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}

?>

index.php

 include('dbConfig.php');

<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="style.css">

<title>test</title>


</head>
<body>

 <?php

  if(isset($_POST['save']))
{
    $sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    $result = mysqli_query($conn,$sql);
}

?>

<form action="index.php" method="post"> 
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>

<label id="first">Password</label><br/>
<input type="password" name="password"><br/>

<label id="first">Email</label><br/>
<input type="text" name="email"><br/>

<button type="submit" name="save">save</button>

</form>

</body>
</html>

Run C++ in command prompt - Windows

Sure, it's how most compilers got started. GCC is probably the most popular (comes with most flavors of *nix). Syntax is just gcc my_source_code.cpp, or gcc -o my_executable.exe my_source_code.cpp. It gets more complicated, of course, when you have multiple source files (as in implementation; anything #included works automatically as long as GCC can find it).

MinGW appears to be a version of GCC for Windows, if that's what you're using. I haven't tried it though.

Pretty sure most IDEs also include a command line interface. I know Visual Studio does, though I have never used it.

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Save ArrayList to SharedPreferences

After API 11 the SharedPreferences Editor accepts Sets. You could convert your List into a HashSet or something similar and store it like that. When you read it back, convert it into an ArrayList, sort it if needed and you're good to go.

//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

You can also serialize your ArrayList and then save/read it to/from SharedPreferences. Below is the solution:

EDIT:
Ok, below is the solution to save ArrayList as a serialized object to SharedPreferences and then read it from SharedPreferences.

Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, it's simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into a string.

In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method:

public void addTask(Task t) {
  if (null == currentTasks) {
    currentTasks = new ArrayList<task>();
  }
  currentTasks.add(t);
 
  // save the task list to preference
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
  Editor editor = prefs.edit();
  try {
    editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
  } catch (IOException e) {
    e.printStackTrace();
  }
  editor.commit();
}

Similarly we have to retrieve the list of tasks from the preference in the onCreate() method:

public void onCreate() {
  super.onCreate();
  if (null == currentTasks) {
    currentTasks = new ArrayList<task>();
  }
 
  // load tasks from preference
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
 
  try {
    currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
  } catch (IOException e) {
    e.printStackTrace();
  } catch (ClassNotFoundException e) {
    e.printStackTrace();
  }
}

You can get the ObjectSerializer class from the Apache Pig project ObjectSerializer.java

Reading a resource file from within jar

For some reason classLoader.getResource() always returned null when I deployed the web application to WildFly 14. getting classLoader from getClass().getClassLoader() or Thread.currentThread().getContextClassLoader() returns null.

getClass().getClassLoader() API doc says,

"Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader."

may be if you are using WildFly and yours web application try this

request.getServletContext().getResource() returned the resource url. Here request is an object of ServletRequest.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Following from Ryan's answer, I think that the interface you are looking for is defined as follows:

interface Param {
    title: string;
    callback: () => void;
}

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

I was getting this error; I just put a WHERE clause for the field which was used within count clause. it solved the issue. Note: if null value exist, check whether its critical for the report, as its excluded in the count.

Old query:

select city, Count(Emp_ID) as Emp_Count 
from Emp_DB
group by city

New query:

select city, Count(Emp_ID) as Emp_Count 
from Emp_DB
where Emp_ID is not null
group by city

Groovy executing shell commands

command = "ls *"

def execute_state=sh(returnStdout: true, script: command)

but if the command failure the process will terminate

Doing a join across two databases with different collations on SQL Server and getting an error

You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)

select sone_field collate SQL_Latin1_General_CP850_CI_AI
  from table_1
    inner join table_2
      on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
  where whatever

How do you loop through each line in a text file using a windows batch file?

@MrKraus's answer is instructive. Further, let me add that if you want to load a file located in the same directory as the batch file, prefix the file name with %~dp0. Here is an example:

cd /d %~dp0
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

NB:: If your file name or directory (e.g. myfile.txt in the above example) has a space (e.g. 'my file.txt' or 'c:\Program Files'), use:

for /F "tokens=*" %%A in ('type "my file.txt"') do [process] %%A

, with the type keyword calling the type program, which displays the contents of a text file. If you don't want to suffer the overhead of calling the type command you should change the directory to the text file's directory. Note that type is still required for file names with spaces.

I hope this helps someone!

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

Completely nothing worked out for me from these answers. Had to create the project again by running cordova platform add ios. What I've noticed, even freshly generated project with (in my case) Firebase pods caused the error message over and over again. In my opinion looks like a bug for some (Firebase, RestKit) pods in Xcode or CocoaPods. To have the pods included I could simply edit my config.xml and run cordova platform add iOS, which did everything for me automatically. Not sure if it will work in all scenarios though.

Edit: I had a Podfile from previous iOS/Xcode, but the newest as of today have # DO NOT MODIFY -- auto-generated by Apache Cordova in the Podfile. This turned on a light in my head to try the approach. Looks a bit trivial, but works and my Firebase features worked out.

Should switch statements always contain a default clause?

Some (outdated) guidelines say so, such as MISRA C:

The requirement for a final default clause is defensive programming. This clause shall either take appropriate action or contain a suitable comment as to why no action is taken.

That advice is outdated because it is not based on currently relevant criteria. The glaring omission being what Harlan Kassler said:

Leaving out the default case enables the compiler to optionally warn or fail when it sees an unhandled case. Static verifiability is after all better than any dynamic check, and therefore not a worthy sacrifice for when you need the dynamic check as well.

As Harlan also demonstrated, the functional equivalent of a default case can be recreated after the switch. Which is trivial when each case is an early return.

The typical need for a dynamic check is input handling, in a wide sense. If a value comes from outside the program's control, it can't be trusted.

This is also where Misra takes the standpoint of extreme defensive programming, whereby as long as an invalid value is physically representable, it must be checked for, no matter if the program is provably correct. Which makes sense if the software needs to be as reliable as possible in the presence of hardware errors. But as Ophir Yoktan said, most software are better off not "handling" bugs. The latter practice is sometimes called offensive programming.

SQL, How to convert VARCHAR to bigint?

an alternative would be to do something like:

SELECT
   CAST(P0.seconds as bigint) as seconds
FROM
   (
   SELECT
      seconds
   FROM
      TableName
   WHERE
      ISNUMERIC(seconds) = 1
   ) P0

jQuery: Setting select list 'selected' based on text, failing strangely

When an <option> isn't given a value="", the text becomes its value, so you can just use .val() on the <select> to set by value, like this:

var text1 = 'Monkey';
$("#mySelect1").val(text1);

var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);

You can test it out here, if the example is not what you're after and they actually have a value, use the <option> element's .text property to .filter(), like this:

var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
    return this.text == text1; 
}).attr('selected', true);

var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
    return this.text == text2; 
}).attr('selected', true);?

You can test that version here.

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

How do I go about adding an image into a java project with eclipse?

If you still have problems with Eclipse finding your files, you might try the following:

  1. Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
  2. Verify the default working directory by printing the following in your main:

        System.out.println("Working dir:  " + System.getProperty("user.dir"));
    

For (1) above, I put the following debugging code around the specific file I was trying to access:

            File imageFile = new File(source);
            System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
            if (!imageFile.exists()) {
                System.out.println("file " + imageFile + " does not exist");
            }
            image = ImageIO.read(imageFile);                

For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).

Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.

if checkbox is checked, do this

I found out a crazy solution for dealing with this issue of checkbox not checked or checked here is my algorithm... create a global variable lets say var check_holder

check_holder has 3 states

  1. undefined state
  2. 0 state
  3. 1 state

If the checkbox is clicked,

$(document).on("click","#check",function(){
    if(typeof(check_holder)=="undefined"){
          //this means that it is the first time and the check is going to be checked
          //do something
          check_holder=1; //indicates that the is checked,it is in checked state
    }
    else if(check_holder==1){
          //do something when the check is going to be unchecked
          check_holder=0; //it means that it is not checked,it is in unchecked state
    }
     else if(check_holder==0){
            //do something when the check is going to be checked
            check_holder=1;//indicates that it is in a checked state
     }
});

The code above can be used in many situation to find out if a checkbox has been checked or not checked. The concept behind it is to save the checkbox states in a variable, ie when it is on,off. i Hope the logic can be used to solve your problem.

I want to execute shell commands from Maven's pom.xml

The problem here is that I don't know what is expected. With your current setup, invoking the plugin on the command line would just work:

$ mvn exec:exec
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [exec:exec]
[INFO] ------------------------------------------------------------------------
[INFO] [exec:exec {execution: default-cli}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

The global configuration is used, the hostname command is executed (laptop is my hostname). In other words, the plugin works as expected.

Now, if you want a plugin to get executed as part of the build, you have to bind a goal on a specific phase. For example, to bind it on compile:

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1.1</version>
    <executions>
      <execution>
        <id>some-execution</id>
        <phase>compile</phase>
        <goals>
          <goal>exec</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <executable>hostname</executable>
    </configuration>
  </plugin>

And then:

$ mvn compile
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/pascal/Projects/Q3491937/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [exec:exec {execution: some-execution}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
...

Note that you can specify a configuration inside an execution.

Using @property versus getters and setters

Using properties lets you begin with normal attribute accesses and then back them up with getters and setters afterwards as necessary.

What's the difference between "Layers" and "Tiers"?

Read Scott Hanselman's post on the issue: http://www.hanselman.com/blog/AReminderOnThreeMultiTierLayerArchitectureDesignBroughtToYouByMyLateNightFrustrations.aspx

Remember though, that in "Scott World" (which is hopefully your world also :) ) a "Tier" is a unit of deployment, while a "Layer" is a logical separation of responsibility within code. You may say you have a "3-tier" system, but be running it on one laptop. You may say your have a "3-layer" system, but have only ASP.NET pages that talk to a database. There's power in precision, friends.

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

How to view the roles and permissions granted to any database user in Azure SQL server instance?

To view database roles assigned to users, you can use sys.database_role_members

The following query returns the members of the database roles.

SELECT DP1.name AS DatabaseRoleName,   
    isnull (DP2.name, 'No members') AS DatabaseUserName   
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
ORDER BY DP1.name;  

Calculate MD5 checksum for a file

And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine

How to rename array keys in PHP?

class DataHelper{

    private static function __renameArrayKeysRecursive($map = [], &$array = [], $level = 0, &$storage = []) {
        foreach ($map as $old => $new) {
            $old = preg_replace('/([\.]{1}+)$/', '', trim($old));
            if ($new) {
                if (!is_array($new)) {
                    $array[$new] = $array[$old];
                    $storage[$level][$old] = $new;
                    unset($array[$old]);
                } else {
                    if (isset($array[$old])) {
                        static::__renameArrayKeysRecursive($new, $array[$old], $level + 1, $storage);
                    } else if (isset($array[$storage[$level][$old]])) {
                        static::__renameArrayKeysRecursive($new, $array[$storage[$level][$old]], $level + 1, $storage);
                    }
                }
            }
        }
    }

    /**
     * Renames array keys. (add "." at the end of key in mapping array if you want rename multidimentional array key).
     * @param type $map
     * @param type $array
    */
    public static function renameArrayKeys($map = [], &$array = [])
    {
        $storage = [];
        static::__renameArrayKeysRecursive($map, $array, 0, $storage);
        unset($storage);
    }
}

Use:

DataHelper::renameArrayKeys([
    'a' => 'b',
    'abc.' => [
       'abcd' => 'dcba'
    ]
], $yourArray);

T-SQL Subquery Max(Date) and Joins

In SQL Server 2005 and later use ROW_NUMBER():

SELECT * FROM 
    ( SELECT p.*,
        ROW_NUMBER() OVER(PARTITION BY Partid ORDER BY PriceDate DESC) AS rn
    FROM MyPrice AS p ) AS t
WHERE rn=1

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

HTTP GET in VB.NET

In VB.NET:

Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")

In C#:

System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

My website's correct path was not specified in IIS.

Setting the default Java character encoding

I can't answer your original question but I would like to offer you some advice -- don't depend on the JVM's default encoding. It's always best to explicitly specify the desired encoding (i.e. "UTF-8") in your code. That way, you know it will work even across different systems and JVM configurations.

Android check internet connection

All official methods only tells whether a device is open for network or not,
If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt network detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

    @Override
    public void onConnectionSuccess() {
        Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFail(String msg) {
        Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
    }
}).execute();

Network Call from async Task

public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
    private OnConnectionCallback onConnectionCallback;
    private Context context;

    public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
        super();
        this.onConnectionCallback = onConnectionCallback;
        this.context = con;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void...params) {
        if (context == null)
            return false;

        boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
        return isConnected;
    }

    @Override
    protected void onPostExecute(Boolean b) {
        super.onPostExecute(b);

        if (b) {
            onConnectionCallback.onConnectionSuccess();
        } else {
            String msg = "No Internet Connection";
            if (context == null)
                msg = "Context is null";
            onConnectionCallback.onConnectionFail(msg);
        }

    }

    public interface OnConnectionCallback {
        void onConnectionSuccess();

        void onConnectionFail(String errorMsg);
    }
}

Actual Class which will ping to server

class NetWorkInfoUtility {

    public boolean isWifiEnable() {
        return isWifiEnable;
    }

    public void setIsWifiEnable(boolean isWifiEnable) {
        this.isWifiEnable = isWifiEnable;
    }

    public boolean isMobileNetworkAvailable() {
        return isMobileNetworkAvailable;
    }

    public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
        this.isMobileNetworkAvailable = isMobileNetworkAvailable;
    }

    private boolean isWifiEnable = false;
    private boolean isMobileNetworkAvailable = false;

    public boolean isNetWorkAvailableNow(Context context) {
        boolean isNetworkAvailable = false;

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
        setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

        if (isWifiEnable() || isMobileNetworkAvailable()) {
            /*Sometime wifi is connected but service provider never connected to internet
            so cross check one more time*/
            if (isOnline())
                isNetworkAvailable = true;
        }

        return isNetworkAvailable;
    }

    public boolean isOnline() {
        /*Just to check Time delay*/
        long t = Calendar.getInstance().getTimeInMillis();

        Runtime runtime = Runtime.getRuntime();
        try {
            /*Pinging to Google server*/
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long t2 = Calendar.getInstance().getTimeInMillis();
            Log.i("NetWork check Time", (t2 - t) + "");
        }
        return false;
    }
}

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank() will also check for null, whereas this:

String foo = getvalue("foo");
if (foo.isEmpty())

will throw a NullPointerException if foo is null.

How to handle a lost KeyStore password in Android?

IF you're able to build your app from a PC, but you don't recall the password, here's what you can do to retrieve the password:

Method 1:

In your build.gradle, add println MYAPP_RELEASE_KEY_PASSWORD as below:

signingConfigs {
    release {
        if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
            storeFile file(MYAPP_RELEASE_STORE_FILE)
            storePassword MYAPP_RELEASE_STORE_PASSWORD
            keyAlias MYAPP_RELEASE_KEY_ALIAS
            keyPassword MYAPP_RELEASE_KEY_PASSWORD
            println MYAPP_RELEASE_KEY_PASSWORD
        }
    }
}

After that, run cd android && ./gradlew assembleRelease

Method 2:

Run keytool -list -v -keystore your <.keystore file path> e.g. keytool -list -v -keystore ./app/my-app-key.keystore.

It will ask for you to Enter keystore password: Just press enter key here. and you will be able to find mapped to Alias name:

Then, run grep -rn "<your alias name>" . in your terminal and you will be able to see your signing.json file as below:

./app/build/intermediates/signing_config/release/out/signing-config.json

The file will have your password in json format with key "mKeyPassword":" < your password > "

Convert a list of characters into a string

This may be the fastest way:

>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'

Difference between logical addresses, and physical addresses?

This answer is by no means exhaustive but it may explain it enough to make things click.

In virtual memory systems, there is a disconnect between logical and physical addresses.

An application can be given a virtual address space of (let's say) 4G. This is its usable memory and it's free to use it as it sees fit. It's a nice contiguous block of memory (from the point of view of the application).

However, it is not the only application running, and the OS has to mediate between them all. Underneath that nice contiguous model, there is a lot of mapping going on to convert logical to physical addresses.

With this mapping, the OS and hardware (I'll just call these the lower layers from here on in) is free to put the application pages anywhere it wants (either in physical memory or swapped out to secondary storage).

When the application tries to access memory at logical address 50, the lower levels can translate that to a physical address using translation tables. And, if it tries to access logical memory that's been swapped out to disk, a page fault is raised and the lower levels can bring the relevant data back into memory, at whatever physical address it wants.

In the bad old days when physical addresses were all you had, code had to be relocatable (or fixed up on load) since it could load anywhere. With virtual memory, that code (and data) can be at logical memory location 50 in a dozen different processes at the same time - it's actual physical address will be different however.

It can even be shared so that one physical copy exists in the address space of many processes at once. This is the crux of shared code (so we don't use more physical memory than we need) and shared memory to allow easy inter-process communication).

It is, of course, less efficient than a pure physical-address environment but the CPU manufacturers try to make it as insanely efficient as possible, since it's used heavily. The advantages far outweigh the disadvantages.

Background images: how to fill whole div if image is small and vice versa

To automatically enlarge the image and cover the entire div section without leaving any part of it unfilled, use:

background-size: cover;

Creating a list/array in excel using VBA to get a list of unique names in a column

You don't need arrays for this. Try something like:

ActiveSheet.Range("$A$1:$A$" & LastRow).RemoveDuplicates Columns:=1, Header:=xlYes

If there's no header, change accordingly.

EDIT: Here's the traditional method, which takes advantage of the fact that each item in a Collection must have a unique key:

Sub test()
Dim ws As Excel.Worksheet
Dim LastRow As Long
Dim coll As Collection
Dim cell As Excel.Range
Dim arr() As String
Dim i As Long

Set ws = ActiveSheet
With ws
    LastRow = .Range("C" & .Rows.Count).End(xlUp).Row
    Set coll = New Collection
    For Each cell In .Range("C4:C" & LastRow)
        On Error Resume Next
        coll.Add cell.Value, CStr(cell.Value)
        On Error GoTo 0
    Next cell
    ReDim arr(1 To coll.Count)
    For i = LBound(arr) To UBound(arr)
        arr(i) = coll(i)
        'to show in Immediate Window
        Debug.Print arr(i)
    Next i
End With
End Sub

sequelize findAll sort order in nodejs

If you are using MySQL, you can use order by FIELD(id, ...) approach:

Company.findAll({
    where: {id : {$in : companyIds}},
    order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})

Keep in mind, it might be slow. But should be faster, than manual sorting with JS.

Python: can't assign to literal

The left hand side of the = operator needs to be a variable. What you're doing here is telling python: "You know the number one? Set it to the inputted string.". 1 is a literal number, not a variable. 1 is always 1, you can't "set" it to something else.

A variable is like a box in which you can store a value. 1 is a value that can be stored in the variable. The input call returns a string, another value that can be stored in a variable.

Instead, use lists:

import random

namelist = []
namelist.append(input("Please enter name 1:"))  #Stored in namelist[0]
namelist.append(input('Please enter name 2:'))  #Stored in namelist[1]
namelist.append(input('Please enter name 3:'))  #Stored in namelist[2]
namelist.append(input('Please enter name 4:'))  #Stored in namelist[3]
namelist.append(input('Please enter name 5:'))  #Stored in namelist[4]

nameindex = random.randint(0, 5)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Using a for loop, you can cut down even more:

import random

namecount = 5
namelist=[]
for i in range(0, namecount):
  namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]

nameindex = random.randint(0, namecount)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

LINQ query to select top five

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

Simply install the 32-bit version of the program, instead of the 64-bit version.

This is much safer than installing packages that are not intended for the distribution at hand.

I got this suggestion from the Google Earth installation instructions for Ubuntu 14.04. Google Earth used to employ ia32-libs under 64-bit Ubuntu 12.04.

Quoting webupd8.org:

The ia32-libs package is no longer available in Ubuntu, starting with Ubuntu 13.10. The package was superseded by multiarch support so you don't need it any more, but some 64bit packages (which are actually 32bit applications) still depend on this package and because of this, they can't be installed in Ubuntu 14.04 or 13.10, 64bit. [...]

The "fix" or more specifically the correct way of installing these apps which depend on ia32-libs is to simply install the 32bit package on Ubuntu 64bit. Of course, that will install quite a few 32bit packages, but that's how multiarch works.

The problem with some programs (like Google Earth) is that the 32-bit package does not support multiarch. Consequently, some 32-bit dependencies need to be installed manually to make the 32-bit version of the program run on Ubuntu 64-bit.

sudo dpkg --add-architecture i386 # only needed once
sudo apt-get update
sudo apt-get install libfontconfig1:i386 libx11-6:i386 libxrender1:i386 libxext6:i386 libgl1-mesa-glx:i386 libglu1-mesa:i386 libglib2.0-0:i386 libsm6:i386

Facebook api: (#4) Application request limit reached

now Application-Level Rate Limiting 200 calls per hour !

you can look this image.enter image description here

Rails params explained?

On the Rails side, params is a method that returns an ActionController::Parameters object. See https://stackoverflow.com/a/44070358/5462485

Java - Check if JTextField is empty or not

What you need is something called Document Listener. See How to Write a Document Listener.

Closing Applications

Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.

How to select all instances of a variable and edit variable name in Sublime

To me, this is the biggest mistake in Sublime. Alt+F3 is hard to reach/remember, and Ctrl+Shift+G makes no sense considering Ctrl+D is "add next instance to selection".

Add this to your User Key Bindings (Preferences > Key Bindings):

{ "keys": ["ctrl+shift+d"], "command": "find_all_under" },

Now you can highlight something, press Ctrl+Shift+D, and it will add every other instance in the file to the selection.

Reset local repository branch to be just like remote repository HEAD

The only solution that works in all cases that I've seen is to delete and reclone. Maybe there's another way, but obviously this way leaves no chance of old state being left there, so I prefer it. Bash one-liner you can set as a macro if you often mess things up in git:

REPO_PATH=$(pwd) && GIT_URL=$(git config --get remote.origin.url) && cd .. && rm -rf $REPO_PATH && git clone --recursive $GIT_URL $REPO_PATH && cd $REPO_PATH

* assumes your .git files aren't corrupt

Could not resolve all dependencies for configuration ':classpath'

Tools > SDK Manager > SDK Tools > Show Package Details and remove all the old versions

enter image description here

How can I detect the encoding/codepage of a text file

Since it basically comes down to heuristics, it may help to use the encoding of previously received files from the same source as a first hint.

Most people (or applications) do stuff in pretty much the same order every time, often on the same machine, so its quite likely that when Bob creates a .csv file and sends it to Mary it'll always be using Windows-1252 or whatever his machine defaults to.

Where possible a bit of customer training never hurts either :-)

How to escape the % (percent) sign in C's printf?

Like this:

printf("hello%%");
//-----------^^ inside printf, use two percent signs together

How to upgrade rubygems

I wouldn't use the debian packages, have a look at RVM or Rbenv.

OS X cp command in Terminal - No such file or directory

In my case, I had accidentally named a folder 'samples '. I couldn't see the space when I did 'ls -la'.

Eventually I realized this when I tried tabbing to autocomplete and saw 'samples\ /'.

To fix this I ran

mv samples\  samples

Check if an element is a child of a parent

If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').

Example: http://jsfiddle.net/6BX9n/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parent('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Or if you want to check to see if there are any ancestors that match, then use .parents().

Example: http://jsfiddle.net/6BX9n/1/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parents('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Why doesn't the height of a container element increase if it contains floated elements?

Its because of the float of the div. Add overflow: hidden on the outside element.

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

Demo

How to get previous page url using jquery

var from = document.referrer;
console.log(from);

document.referrer won't be always available.

Create aar file in Android Studio

If your library is set up as an Android library (i.e. it uses the apply plugin: 'com.android.library' statement in its build.gradle file), it will output an .aar when it's built. It will show up in the build/outputs/aar/ directory in your module's directory.

You can choose the "Android Library" type in File > New Module to create a new Android Library.

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

Iterating through all the cells in Excel VBA or VSTO 2005

You basically can loop over a Range

Get a sheet

myWs = (Worksheet)MyWb.Worksheets[1];

Get the Range you're interested in If you really want to check every cell use Excel's limits

The Excel 2007 "Big Grid" increases the maximum number of rows per worksheet from 65,536 to over 1 million, and the number of columns from 256 (IV) to 16,384 (XFD). from here http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel

and then loop over the range

        Range myBigRange = myWs.get_Range("A1", "A256");

        string myValue;

        foreach(Range myCell in myBigRange )
        {
            myValue = myCell.Value2.ToString();
        }

How do I change the android actionbar title and icon

You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this

getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

How to put scroll bar only for modal-body?

A simple js solution to set modal height proportional to body's height :

$(document).ready(function () {
    $('head').append('<style type="text/css">.modal .modal-body {max-height: ' + ($('body').height() * .8) + 'px;overflow-y: auto;}.modal-open .modal{overflow-y: hidden !important;}</style>');
});

body's height has to be 100% :

html, body {
    height: 100%;
    min-height: 100%;
}

I set modal body height to 80% of body, this can be of course customized.

Hope it helps.

Clear text input on click with AngularJS

In Your Controller

$scope.clearSearch = function() {
     $scope.searchAll = '';
}

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

SWT by itself is pretty low-level, and it uses the platform's native widgets through JNI. It is not related to Swing and AWT at all. The Eclipse IDE and all Eclipse-based Rich Client Applications, like the Vuze BitTorrent client, are built using SWT. Also, if you are developing Eclipse plugins, you will typically use SWT.
I have been developing Eclipse-based applications and plugins for almost 5 years now, so I'm clearly biased. However, I also have extensive experience in working with SWT and the JFace UI toolkit, which is built on top of it. I have found JFace to be very rich and powerful; in some cases it might even be the main reason for choosing SWT. It enables you to whip up a working UI quite quickly, as long as it is IDE-like (with tables, trees, native controls, etc). Of course you can integrate your custom controls as well, but that takes some extra effort.

Git Bash doesn't see my PATH

Following @Daniel's comment and thanks to @Tom's answer, I found out that Git bash was indeed using the PATH but not the latest paths I recently installed. To work around this problem, I added a file in my home (windows) directory named:

.bashrc

and the content as follow:

PATH=$PATH:/c/Go/bin

because I was installing Go and this path contained the executable go.exe Now Git bash was able to recognize the command:

go

Perhaps just a system reboot would have been enough in my case, but I'm happy that this solution work in any case.

Install apps silently, with granted INSTALL_PACKAGES permission

I made a test app for silent installs, using PackageManager.installPackage method.

I get installPackage method through reflection, and made android.content.pm.IPackageInstallObserver interface in my src folder (because it's hidden in android.content.pm package).

When i run installPackage, i got SecurityException with string indication, that my app has no android.permission.INSTALL_PACKAGES, but it defined in AndroidManifest.xml.

So, i think, it's not possible to use this method.

PS. I tested in on Android SDK 2.3 and 4.0. Maybe it will work with earlier versions.

jQuery.css() - marginLeft vs. margin-left?

I think it is so it can keep consistency with the available options used when settings multiple css styles in one function call through the use of an object, for example...

$(".element").css( { marginLeft : "200px", marginRight : "200px" } );

as you can see the property are not specified as strings. JQuery also supports using string if you still wanted to use the dash, or for properties that perhaps cannot be set without the dash, so the following still works...

$(".element").css( { "margin-left" : "200px", "margin-right" : "200px" } );

without the quotes here, the javascript would not parse correctly as property names cannot have a dash in them.

EDIT: It would appear that JQuery is not actually making the distinction itsleft, instead it is just passing the property specified for the DOM to care about, most likely with style[propertyName];

Convert a String of Hex into ASCII in Java

Check out Convert a string representation of a hex dump to a byte array using Java?

Disregarding encoding, etc. you can do new String (hexStringToByteArray("75546..."));

How to set only time part of a DateTime variable in C#

date = new DateTime(date.year, date.month, date.day, HH, MM, SS);

Performance of Java matrix math libraries?

I'm the main author of jblas and wanted to point out that I've released Version 1.0 in late December 2009. I worked a lot on the packaging, meaning that you can now just download a "fat jar" with ATLAS and JNI libraries for Windows, Linux, Mac OS X, 32 and 64 bit (except for Windows). This way you will get the native performance just by adding the jar file to your classpath. Check it out at http://jblas.org!

How to uninstall a windows service and delete its files without rebooting

Should it be necessary to manually remove a service:

  1. Run Regedit or regedt32.
  2. Find the registry key entry for your service under the following key: HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services
  3. Delete the Registry Key

You will have to reboot before the list gets updated in services

Better naming in Tuple classes than "Item1", "Item2"

Why is everyone making life so hard. Tuples are for rather temporary data processing. Working with Tuples all the time will make the code very hard to understand at some point. Creating classes for everything could eventually bloat your project.

It's about balance, however...

Your problem seems to be something you would want a class for. And just for the sake of completeness, this class below also contains constructors.


This is the proper pattern for

  • A custom data type
    • with no further functionality. Getters and setters can also be expanded with code, getting/setting private members with the name pattern of "_orderGroupId", while also executing functional code.
  • Including constructors. You can also choose to include just one constructor if all properties are mandatory.
  • If you want to use all constructors, bubbling like this is the proper pattern to avoid duplicate code.

public class OrderRelatedIds
{
    public int OrderGroupId { get; set; }
    public int OrderTypeId { get; set; }
    public int OrderSubTypeId { get; set; }
    public int OrderRequirementId { get; set; }

    public OrderRelatedIds()
    {
    }
    public OrderRelatedIds(int orderGroupId)
        : this()
    {
        OrderGroupId = orderGroupId;
    }
    public OrderRelatedIds(int orderGroupId, int orderTypeId)
        : this(orderGroupId)
    {
        OrderTypeId = orderTypeId;
    }
    public OrderRelatedIds(int orderGroupId, int orderTypeId, int orderSubTypeId)
        : this(orderGroupId, orderTypeId)
    {
        OrderSubTypeId = orderSubTypeId;
    }
    public OrderRelatedIds(int orderGroupId, int orderTypeId, int orderSubTypeId, int orderRequirementId)
        : this(orderGroupId, orderTypeId, orderSubTypeId)
    {
        OrderRequirementId = orderRequirementId;
    }
}

Or, if you want it really simple: You can also use type initializers:

OrderRelatedIds orders = new OrderRelatedIds
{
    OrderGroupId = 1,
    OrderTypeId = 2,
    OrderSubTypeId = 3,
    OrderRequirementId = 4
};

public class OrderRelatedIds
{
    public int OrderGroupId;
    public int OrderTypeId;
    public int OrderSubTypeId;
    public int OrderRequirementId;
}

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

I don't see a reference to this:

SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");

above format is also useful.

http://www.java2s.com/Tutorials/Java/Date/Date_Format/Format_date_in_yyyyMMddHHmmssSSS_format_in_Java.htm

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.